package com.huimv.video.video.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huimv.common.utils.Result;
import com.huimv.common.utils.ResultCode;
import com.huimv.video.video.entity.BaseRoom;
import com.huimv.video.video.entity.BaseScreenCameraAccount;
import com.huimv.video.video.entity.Camera;
import com.huimv.video.video.entity.CameraBrand;
import com.huimv.video.video.entity.vo.CameraListVo;
import com.huimv.video.video.entity.vo.CameraListsVo;
import com.huimv.video.video.entity.vo.CameraVo;
import com.huimv.video.video.mapper.*;
import com.huimv.video.video.service.ICameraService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author astupidcoder
 * @since 2021-09-13
 */
@Service
public class CameraServiceImpl extends ServiceImpl<CameraMapper, Camera> implements ICameraService {


    @Autowired
    private CameraBrandMapper cameraBrandMapper;

    @Autowired
    private CameraAreaMapper cameraAreaMapper;

    @Autowired
    private BaseScreenCameraAccountMapper cameraAccountMapper;


    @Autowired
    private BaseRoomMapper baseRoomMapper;


    @Override
    public Result listPage(CameraListVo cameraListVo) {
        Integer current = cameraListVo.getCurrent();
        String strchStr = cameraListVo.getStrchStr();
        Integer size = cameraListVo.getSize();
        Integer areaId = cameraListVo.getAreaId();
        Integer brandId = cameraListVo.getBrandId();
        Integer sort = cameraListVo.getSort();
        Integer farmId = cameraListVo.getFarmId();
        Integer isOnline = cameraListVo.getIsOnline();

        QueryWrapper<Camera> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(strchStr)) {
            wrapper.and(i -> i.like("camera_name", strchStr)
                    .or().like("camera_ip", strchStr));
        }

        if (farmId != null) {
            wrapper.eq("farm_id", farmId);
        }

        if (areaId != null) {
            wrapper.eq("area_id", areaId);
        }

        if (brandId != null) {
            wrapper.eq("brand_id", brandId);
        }

        if (isOnline != null) {
            wrapper.eq("is_online", isOnline);
        }

        if (sort == null) {
            wrapper.orderByDesc("id");
        } else if (sort == 1) {
            wrapper.orderByDesc("sort");
        } else {
            wrapper.orderByAsc("sort");
        }
        wrapper.orderByDesc("id");
        return new Result(ResultCode.SUCCESS, page(new Page<>(current, size), wrapper));
    }

    @Override
    public List getCameraDetails(CameraListsVo cameraListsVo) {
        List<Integer> cameraIds = cameraListsVo.getCameraIds();
        CameraListVo cameraListVo = new CameraListsVo();
        cameraListVo.setCurrent(1);
        cameraListVo.setSize(10000);
        cameraListVo.setStrchStr(cameraListsVo.getStrchStr());
        cameraListVo.setAreaId(cameraListsVo.getAreaId());
        cameraListVo.setBrandId(cameraListsVo.getBrandId());
        cameraListVo.setSort(cameraListsVo.getSort());

        if (cameraIds == null || cameraIds.size() == 0){
            return null;
        }
        List cameraDetailsList = new ArrayList();
        IPage<Camera> page = (IPage<Camera>)this.listPage(cameraListVo).getData();
        List<Camera> list = page.getRecords();
        int i = 0;
        final String farmAppPort = "8081";
        final String farmVideoApp = "/appleVideo/play?";
        final String hlsMediaPort= "85";
        for (Camera camera : list) {
            for (Integer cameraId : cameraIds) {
                if (cameraId.equals( camera.getId())){

                    String cameraAccount = camera.getAccount();
                    String cameraPassword = camera.getPassword();
                    String camerIp = camera.getCameraIp();
                    String cameraName = camera.getCameraName();
                    Integer areaId = camera.getAreaId();
                    String url = cameraAreaMapper.selectById(areaId).getPublicUrl();
                    String rtsp ;
                    CameraBrand cameraBrand = cameraBrandMapper.selectById(camera.getBrandId());
                    Integer type = cameraBrand.getStreamType();
                    if (type == 0){
                        rtsp = cameraBrand.getMainStream();
                    }else {
                        rtsp = cameraBrand.getAssistStream();
                    }
                    CameraVo cameraVo= new CameraVo();
                    cameraVo.setId(camera.getId());
                    cameraVo.setAreaId(areaId);
                    if (camera.getId() == 767){
                        cameraVo.setWsUrl("ws://" + url + "/camera_relay?tcpaddr=" + cameraAccount + "%3A" + cameraPassword + "%40" + camerIp);
                        cameraVo.setRtspUrl("rtsp://" + cameraAccount + ":" + cameraPassword + "@" + camerIp + "/cam/realmonitor?channel=2&subtype=0");
                    }else {
                        cameraVo.setWsUrl("ws://" + url + "/camera_relay?tcpaddr=" + cameraAccount + "%3A" + cameraPassword + "%40" + camerIp);
                        cameraVo.setRtspUrl("rtsp://" + cameraAccount + ":" + cameraPassword + "@" + camerIp + rtsp);
                    }
                    cameraVo.setCameraName(cameraName);
                    cameraVo.setHttpUrl(handleHlsHttpUrl(url,cameraAccount,cameraPassword,camerIp,farmAppPort,farmVideoApp,hlsMediaPort));
                    if (i > 0){
                        cameraVo.setLastId(list.get(i-1).getId());
                    }
                    if (i < list.size()-1 ){
                        cameraVo.setNextId(list.get(i+1).getId());
                    }
                    cameraDetailsList.add(cameraVo);
                }
            }
            i++;
        }
        return cameraDetailsList;
    }

    //构造HlsHttp地址
    private String handleHlsHttpUrl(String url, String cameraAccount, String cameraPassword, String camerIp, String farmAppPort, String farmVideoApp, String hlsMediaPort) {
        url = url.substring(0,url.indexOf(":"));
        url="http://"+url;
        //return url+":"+farmAppPort+farmVideoApp+"url="+cameraAccount + ":" + cameraPassword + "@" + camerIp+"&name="+"&dt=3000&targetUrl="+url+":"+hlsMediaPort;
        return url+":"+farmAppPort+farmVideoApp+"url="+cameraAccount + ":" + cameraPassword + "@" + camerIp+"&dt=3000&targetUrl="+url+":"+hlsMediaPort;
    }

    //    @Override
    public List getCameraDetails_yu(CameraListsVo cameraListsVo) {
        List<Integer> cameraIds = cameraListsVo.getCameraIds();
        CameraListVo cameraListVo = new CameraListsVo();
        cameraListVo.setCurrent(1);
        cameraListVo.setSize(10000);
        cameraListVo.setStrchStr(cameraListsVo.getStrchStr());
        cameraListVo.setAreaId(cameraListsVo.getAreaId());
        cameraListVo.setBrandId(cameraListsVo.getBrandId());
        cameraListVo.setSort(cameraListsVo.getSort());


        if (cameraIds == null || cameraIds.size() == 0) {
            return null;
        }
        List cameraDetailsList = new ArrayList();
        IPage<Camera> page = (IPage<Camera>) this.listPage(cameraListVo).getData();
        List<Camera> list = page.getRecords();
        int i = 0;
        for (Camera camera : list) {
            for (Integer cameraId : cameraIds) {
                if (cameraId.equals(camera.getId())) {

                    String cameraAccount = camera.getAccount();
                    String cameraPassword = camera.getPassword();
                    String camerIp = camera.getCameraIp();
                    String cameraName = camera.getCameraName();
                    Integer areaId = camera.getAreaId();
                    String url = cameraAreaMapper.selectById(areaId).getPublicUrl();

                    String rtsp;
                    CameraBrand cameraBrand = cameraBrandMapper.selectById(camera.getBrandId());
                    Integer type = cameraBrand.getStreamType();
                    if (type == 0) {
                        rtsp = cameraBrand.getMainStream();
                    } else {
                        rtsp = cameraBrand.getAssistStream();
                    }
                    CameraVo cameraVo = new CameraVo();
                    cameraVo.setAreaId(areaId);
                    cameraVo.setWsUrl("ws://" + url + "/camera_relay?tcpaddr=" + cameraAccount + "%3A" + cameraPassword + "%40" + camerIp);
                    cameraVo.setRtspUrl("rtsp://" + cameraAccount + ":" + cameraPassword + "@" + camerIp + rtsp);
                    cameraVo.setCameraName(cameraName);
                    if (i > 0) {
                        cameraVo.setLastId(list.get(i - 1).getId());
                    }
                    if (i < list.size() - 1) {
                        cameraVo.setNextId(list.get(i + 1).getId());
                    }

                    cameraDetailsList.add(cameraVo);

                }

            }
            i++;
        }


        return cameraDetailsList;
    }

    @Override
    public Result updateStatus(Integer id) {
        Camera byId = this.getById(id);

        if (byId.getRunStatus()) {
            byId.setRunStatus(false);
            this.updateById(byId);
            return new Result(10000, "已停用", true);
        } else {
            byId.setRunStatus(true);
            this.updateById(byId);
            return new Result(10000, "已启用", true);
        }


    }

    @Override
    public Result add(Camera camera) {
        Integer areaId = camera.getAreaId();
        Integer brandId = camera.getBrandId();

        int brandName = this.count(new QueryWrapper<Camera>().eq("camera_name", camera.getCameraName()).eq("farm_id", camera.getFarmId()));
        if (brandName > 0) {
            return new Result(10001, "摄像头名称重复", false);
        }
        if (areaId != null) {
            camera.setAreaName(cameraAreaMapper.selectById(areaId).getAreaName());
        }
        if (brandId != null) {
            camera.setBrandName(cameraBrandMapper.selectById(brandId).getBrandName());
        }
        this.save(camera);

        return new Result(10000, "添加成功", true);
    }

    @Override
    public Result updates(Camera camera) {
        Integer areaId = camera.getAreaId();
        Integer brandId = camera.getBrandId();
        this.updateById(camera);
        int brandName = this.count(new QueryWrapper<Camera>().eq("camera_name", camera.getCameraName()));
        if (brandName > 1) {
            return new Result(10001, "摄像头名称重复", false);
        }
        if (areaId != null) {
            camera.setAreaName(cameraAreaMapper.selectById(areaId).getAreaName());
        }
        if (brandId != null) {
            camera.setBrandName(cameraBrandMapper.selectById(brandId).getBrandName());
        }
        this.updateById(camera);
        return new Result(10000, "修改成功", true);
    }

    @Override
    public CameraVo getCameraDetailsByRoomId(Integer roomId) {


        Camera camera = this.getOne(new QueryWrapper<Camera>().eq("room_id", roomId));

        return getCameraVo(camera);
    }


    @Override
    public Result initCamera(Integer farmId, Integer userId) {
        BaseScreenCameraAccount cameraAccount = cameraAccountMapper.selectOne(new QueryWrapper<BaseScreenCameraAccount>().eq("farm_id", farmId).eq("account_id", userId));
        Integer cameraId;
        if (ObjectUtil.isEmpty(cameraAccount)) {
            cameraId = this.getOne(new QueryWrapper<Camera>().eq("run_status", 1).eq("farm_id", farmId).last("limit 1")).getId();
        } else {
            cameraId = cameraAccount.getCameraId();
        }


        Camera camera = this.getById(cameraId);
        if (!camera.getRunStatus()) {
            return new Result(10001, "该摄像头已经被禁用", false);
        }

        return new Result(ResultCode.SUCCESS, getCameraVo(camera));
    }

    @Override
    public Result listScreenCamera(Integer farmId) {
        List<Camera> cameras = this.list(new QueryWrapper<Camera>().eq("farm_id", farmId));
        List list = new ArrayList();
        for (int i = 0; i < 6; i++) {
            list.add(getCameraVo(cameras.get(RandomUtil.randomInt(0, cameras.size()))));
        }

        return new Result(ResultCode.SUCCESS, list);
    }

    @Override
    public Result screenCamera(Integer farmId) {

        BaseRoom baseRoom = baseRoomMapper.selectOne(new QueryWrapper<BaseRoom>().eq("farm_id", farmId).last("limit 1"));
        Integer roomId;
        if (ObjectUtil.isNotEmpty(baseRoom)) {

            roomId = baseRoom.getId();
        } else {
            return new Result(ResultCode.SUCCESS, null);
        }
        Camera room_id = this.getOne(new QueryWrapper<Camera>().eq("room_id", roomId));
        CameraVo cameraVo = getCameraVo(room_id);

        return new Result(ResultCode.SUCCESS, cameraVo);
    }

    @Override
    public List getCameraDetails2(CameraListsVo cameraListsVo) {
        List<Integer> cameraIds = cameraListsVo.getCameraIds();
        CameraListVo cameraListVo = new CameraListsVo();
        cameraListVo.setCurrent(1);
        cameraListVo.setSize(10000);
        cameraListVo.setStrchStr(cameraListsVo.getStrchStr());
        cameraListVo.setAreaId(cameraListsVo.getAreaId());
        cameraListVo.setBrandId(cameraListsVo.getBrandId());
        cameraListVo.setSort(cameraListsVo.getSort());

        if (cameraIds == null || cameraIds.size() == 0){
            return null;
        }
        List cameraDetailsList = new ArrayList();
        IPage<Camera> page = (IPage<Camera>)this.listPage(cameraListVo).getData();
        List<Camera> list = page.getRecords();
        int i = 0;
        final String farmAppPort = "8081";
        final String farmVideoApp = "/appleVideo/play?";
        final String hlsMediaPort= "85";
        for (Camera camera : list) {
            for (Integer cameraId : cameraIds) {
                if (cameraId.equals( camera.getId())){
                    String cameraAccount = camera.getAccount();
                    String cameraPassword = camera.getPassword();
                    String camerIp = camera.getCameraIp();
                    String cameraName = camera.getCameraName();
                    Integer areaId = camera.getAreaId();
                    String url = cameraAreaMapper.selectById(areaId).getPublicUrl();
                    url = url.substring(0,url.indexOf(":"));
                    url="http://"+url;
//                    String rtsp ;
//                    CameraBrand cameraBrand = cameraBrandMapper.selectById(camera.getBrandId());
//                    Integer type = cameraBrand.getStreamType();
//                    if (type == 0){
//                        rtsp = cameraBrand.getMainStream();
//                    }else {
//                        rtsp = cameraBrand.getAssistStream();
//                    }

                    CameraVo cameraVo= new CameraVo();
                    cameraVo.setAreaId(areaId);
//                    cameraVo.setWsUrl("ws://" + url + "/camera_relay?tcpaddr=" + cameraAccount + "%3A" + cameraPassword + "%40" + camerIp);
//                    cameraVo.setRtspUrl("rtsp://" + cameraAccount + ":" + cameraPassword + "@" + camerIp + rtsp);
                    //示例
//                    cameraVo.setHttpUrl("http://183.249.204.153:8081/appleVideo/play?url=admin:hmkj6688@192.168.1.108&name=101&dt=3000&targetUrl=http://183.249.204.153:85");
                    cameraVo.setHttpUrl(url+":"+farmAppPort+farmVideoApp+"url="+cameraAccount + ":" + cameraPassword + "@" + camerIp+"&name="+"&dt=3000&targetUrl="+url+":"+hlsMediaPort);
                    cameraVo.setCameraName(cameraName);
                    if (i > 0){
                        cameraVo.setLastId(list.get(i-1).getId());
                    }
                    if (i < list.size()-1 ){
                        cameraVo.setNextId(list.get(i+1).getId());
                    }
                    cameraDetailsList.add(cameraVo);
                }
            }
            i++;
        }


        return cameraDetailsList;
    }

    @Override
    public Result saveCamera(Integer farmId) {
        ExcelReader reader = ExcelUtil.getReader("G:/test/test1.xlsx");
        List<Camera> all = reader.readAll(Camera.class);
        for (Camera camera : all) {
           camera.setAccount("admin");
           camera.setPassword("hmkj6688");
           camera.setBrandName("大华");
           camera.setBrandId(18);
           camera.setAttention(0);
           camera.setFarmId(22);
           this.save(camera);
            System.out.println(camera.getCameraIp());
        }
        return null;
    }


    @Override
    public List getByAreaId(Integer areaId) {
        return null;
    }


    public CameraVo getCameraVo(Camera camera) {

        String cameraAccount = camera.getAccount();
        String cameraPassword = camera.getPassword();
        String camerIp = camera.getCameraIp();
        String cameraName = camera.getCameraName();
        Integer areaId = camera.getAreaId();
        String url = cameraAreaMapper.selectById(areaId).getPublicUrl();

        String rtsp;
        CameraBrand cameraBrand = cameraBrandMapper.selectById(camera.getBrandId());
        Integer type = cameraBrand.getStreamType();
        if (type == 0) {
            rtsp = cameraBrand.getMainStream();
        } else {
            rtsp = cameraBrand.getAssistStream();
        }


        CameraVo cameraVo = new CameraVo();
        cameraVo.setAreaId(areaId);

        if (camera.getId() == 767){
            cameraVo.setWsUrl("ws://" + url + "/camera_relay?tcpaddr=" + cameraAccount + "%3A" + cameraPassword + "%40" + camerIp);
            cameraVo.setRtspUrl("rtsp://" + cameraAccount + ":" + cameraPassword + "@" + camerIp + "/cam/realmonitor?channel=2&subtype=0");
        }else {
            cameraVo.setWsUrl("ws://" + url + "/camera_relay?tcpaddr=" + cameraAccount + "%3A" + cameraPassword + "%40" + camerIp);
            cameraVo.setRtspUrl("rtsp://" + cameraAccount + ":" + cameraPassword + "@" + camerIp + rtsp);
        }
//        cameraVo.setWsUrl("ws://" + url + "/camera_relay?tcpaddr=" + cameraAccount + "%3A" + cameraPassword + "%40" + camerIp);
//        cameraVo.setRtspUrl("rtsp://" + cameraAccount + ":" + cameraPassword + "@" + camerIp + rtsp);
        cameraVo.setCameraName(cameraName);
        return cameraVo;
    }

}
