package com.mortals.xhx.daemon.task;

import com.alibaba.fastjson.JSON;
import com.mortals.framework.common.Rest;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.service.ITask;
import com.mortals.framework.service.ITaskExcuteService;
import com.mortals.xhx.common.code.RecognitionResourceEnum;
import com.mortals.xhx.common.code.YesNoEnum;
import com.mortals.xhx.module.device.model.DeviceEntity;
import com.mortals.xhx.module.device.model.DeviceQuery;
import com.mortals.xhx.module.device.service.DeviceService;
import com.mortals.xhx.module.hik.camera.model.req.CameraListReq;
import com.mortals.xhx.module.hik.camera.model.req.CameraReq;
import com.mortals.xhx.module.hik.camera.model.rsp.CameraDataInfo;
import com.mortals.xhx.module.hik.camera.model.rsp.CameraInfo;
import com.mortals.xhx.module.hik.camera.service.IHikCameraService;
import com.mortals.xhx.module.hik.face.model.req.resource.ResourceReq;
import com.mortals.xhx.module.hik.face.model.rsp.resource.ResourceDataInfo;
import com.mortals.xhx.module.hik.face.service.IHikFaceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 同步监控视频点
 */
@Slf4j
@Service("SyncSiteDeviceTask")
public class SyncSiteDeviceTaskImpl implements ITaskExcuteService {

    @Autowired
    private DeviceService deviceService;
    @Autowired
    private IHikCameraService hikCameraService;
    @Autowired
    private IHikFaceService hikFaceService;


    @Override
    public void excuteTask(ITask task) throws AppException {
        log.info("开始同步设备列表！");
        syncDevice();
        log.info("结束同步设备列表！");

    }

    /**
     * "altitude": null,
     * "cameraIndexCode": "d271545ad77c4fb28728101d765d76bb",
     * "cameraName": "Camera 02",
     * "cameraType": 0,
     * "cameraTypeName": "枪机",
     * "capabilitySet": "event_audio,io,MixMixedRoot,MixRoot,event_veh_recognition,face,event_vss,record,vss,ptz,event_io,net,maintenance,event_device,status,event_body,event_face,event_rule,event_veh",
     * "capabilitySetName": "音频事件能力,IO能力,,,车辆识别事件能力,人脸识别能力,视频事件能力,录像能力,视频能力,云台能力,IO事件能力,网络参数配置能力,设备维护能力,设备事件能力,状态能力,人体事件能力,人脸事件能力,行为分析事件能力,车辆事件能力",
     * "intelligentSet": null,
     * "intelligentSetName": null,
     * "channelNo": "2",
     * "channelType": "analog",
     * "channelTypeName": "模拟通道",
     * "createTime": "2023-04-10T13:59:08.194+08:00",
     * "encodeDevIndexCode": "f01277c1d6f842b581e6931fa7cc34b4",
     * "encodeDevResourceType": null,
     * "encodeDevResourceTypeName": null,
     * "gbIndexCode": null,
     * "installLocation": null,
     * "keyBoardCode": null,
     * "latitude": null,
     * "longitude": null,
     * "pixel": null,
     * "ptz": null,
     * "ptzName": null,
     * "ptzController": null,
     * "ptzControllerName": null,
     * "recordLocation": null,
     * "recordLocationName": null,
     * "regionIndexCode": "root000000",
     * "status": null,
     * "statusName": null,
     * "transType": 1,
     * "transTypeName": "TCP",
     * "treatyType": null,
     * "treatyTypeName": null,
     * "viewshed": null,
     * "updateTime": "2023-04-10T15:11:56.446+08:00"
     */
    private void syncDevice() {


        //获取识别资源

        ResourceReq resourceReq = new ResourceReq();
        resourceReq.setRecognitionResourceType(RecognitionResourceEnum.SUPER_BRAIN.getValue());
        Rest<List<ResourceDataInfo>> resourceRecognition = hikFaceService.getResourceRecognition(resourceReq);
        if (resourceRecognition.getCode() == YesNoEnum.YES.getValue() && !ObjectUtils.isEmpty(resourceRecognition.getData())) {
            ArrayList<String> recognitionResourceIndexCodes = new ArrayList<>();
            recognitionResourceIndexCodes.add(resourceRecognition.getData().get(0).getIndexCode());
            // planRecognWhiteReq.setRecognitionResourceIndexCodes(recognitionResourceIndexCodes);
            CameraListReq cameraListReq = new CameraListReq();
            cameraListReq.setPageNo(1);
            cameraListReq.setPageSize(200);
            cameraListReq.setEncodeDevIndexCode(resourceRecognition.getData().get(0).getIndexCode());
            //cameraListReq.setRegionIndexCode("root000000");
            Rest<CameraDataInfo> rest = hikCameraService.findCameraList(cameraListReq);
            if (rest.getCode() == YesNoEnum.YES.getValue()) {
                List<CameraInfo> cameraDataInfoList = rest.getData().getList();
                log.info("视频设备总数量：{}", cameraDataInfoList.size());
                if (!ObjectUtils.isEmpty(cameraDataInfoList)) {

                    List<DeviceEntity> newDeviceList = cameraDataInfoList.stream().map(camera -> {
                        DeviceEntity deviceEntity = new DeviceEntity();
                        deviceEntity.initAttrValue();
                        deviceEntity.setDeviceName(camera.getCameraName());
                        deviceEntity.setDeviceId(camera.getCameraIndexCode());
                        deviceEntity.setDeviceCode(camera.getCameraIndexCode());
                        deviceEntity.setCameraType(camera.getCameraType());
                        deviceEntity.setCameraTypeName(camera.getCameraTypeName());
                        deviceEntity.setCapabilitySet(camera.getCapabilitySet());
                        deviceEntity.setCapabilitySetName(camera.getCapabilitySetName());
                        deviceEntity.setRegionIndexCode(camera.getRegionIndexCode());
                        deviceEntity.setEncodeDevIndexCode(camera.getEncodeDevIndexCode());
                        deviceEntity.setCreateTime(camera.getCreateTime());
                        deviceEntity.setUpdateTime(camera.getUpdateTime());
                        return deviceEntity;
                    }).collect(Collectors.toList());

                    List<DeviceEntity> oldDeviceList = deviceService.find(new DeviceQuery());
                    Map<String, DeviceEntity> oldDeviceMap = oldDeviceList.stream().collect(Collectors.toMap(x -> x.getDeviceCode(), y -> y, (o, n) -> n));
                    Map<String, DeviceEntity> newDeviceMap = newDeviceList.stream().collect(Collectors.toMap(x -> x.getDeviceCode(), y -> y, (o, n) -> n));


                    List<DeviceEntity> saveDeviceList = newDeviceList.stream().map(item -> {
                        if (!oldDeviceMap.containsKey(item.getDeviceCode())) {
                            item.setCreateUserId(1L);
                            item.setCreateUserName("系统管理员");
                            return item;
                        }
                        return null;
                    }).filter(f -> f != null).collect(Collectors.toList());

                    //做差集
                    List<Long> delDeviceList = oldDeviceList.stream().map(item -> {
                        if (!newDeviceMap.containsKey(item.getDeviceCode())) {
                            return item.getId();
                        }
                        return null;
                    }).filter(f -> f != null).collect(Collectors.toList());


                    if (!ObjectUtils.isEmpty(saveDeviceList)) {
                        log.info("设备新增，size:{}", saveDeviceList.size());
                        deviceService.save(saveDeviceList);
                    }

                    if (!ObjectUtils.isEmpty(delDeviceList)) {
                        log.info("设备删除，size:{}", delDeviceList.size());
                        deviceService.remove(delDeviceList, null);
                    }
                }
            } else {
                log.info("同步设备异常=>{}", JSON.toJSONString(rest));
            }

        }
    }


    @Override
    public void stopTask(ITask task) throws AppException {

    }
}
