package com.jpsoft.shinestar.modules.pacs.service.impl;

import com.jpsoft.shinestar.modules.base.entity.*;
import com.jpsoft.shinestar.modules.base.service.*;
import com.jpsoft.shinestar.modules.common.utils.OSSUtil;
import com.jpsoft.shinestar.modules.hikvision.service.IEHomeService;
import com.jpsoft.shinestar.modules.pacs.service.IGuardService;
import com.jpsoft.shinestar.modules.pacs.dto.IsPersonExistVo;
import com.jpsoft.shinestar.modules.pacs.dto.PacsMsgResult;
import com.jpsoft.shinestar.modules.pacs.dto.PacsResult;
import com.jpsoft.shinestar.modules.uniview.exception.OfflineException;
import com.jpsoft.shinestar.modules.uniview.request.LapiRequest;
import com.jpsoft.shinestar.modules.uniview.service.ILapiService;
import com.jpsoft.shinestar.modules.sys.service.SysLogService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.*;


@Slf4j
@Service
public class GuardServiceImpl implements IGuardService {
    @Autowired
    private DeviceInfoService deviceInfoService;

    @Autowired
    private PersonInfoService personInfoService;

    @Autowired
    private PersonDeviceRelationService personDeviceRelationService;

    @Autowired
    private CompanyInfoService companyInfoService;

    @Autowired
    private LapiRequest lapiRequest;

    @Autowired
    private ExecuteFailLogService executeFailLogService;

    @Autowired
    private SysLogService sysLogService;

    @Autowired
    private ILapiService lapiService;

    @Autowired
    private IEHomeService eHomeService;

    //海康威视设备
    private final String HIK_VISION = "2";

    @Override
    public Boolean keepAlive(String id) throws Exception {
        boolean alive = false;

        DeviceInfo deviceInfo = deviceInfoService.get(id);

        if (deviceInfo == null) {
            throw new Exception("设备不存在");
        }

        if (HIK_VISION.equals(deviceInfo.getManufacturer())){
            //海康设备
            alive = eHomeService.keepAlive(id);
        }
        else {
            //宇视设备
            alive = lapiService.keepAlive(id);
        }

        return alive;
    }

    @Override
    public List<PacsResult> addPerson(Long id) throws Exception {

        PersonInfo personInfo = personInfoService.get(id);
        if (personInfo == null) {
            throw new Exception("人员不存在");
        }

        List<PersonDeviceRelation> listRelation = personDeviceRelationService.findByPersonId(id);

        if (listRelation.size() <= 0) {
            throw new Exception("人员未绑定设备");
        }

//        CompanyInfo companyInfo = companyInfoService.get(personInfo.getCompanyId());

        List<DeviceInfo> deviceList = new ArrayList<>();

        for (PersonDeviceRelation personDeviceRelation : listRelation) {
            DeviceInfo deviceInfo = deviceInfoService.get(personDeviceRelation.getDeviceId());
            if (deviceInfo != null && !deviceInfo.getDelFlag()) {
                deviceList.add(deviceInfo);
            }
        }

        if (deviceList.size() <= 0) {
            throw new Exception("人员未绑定设备");
        }

        String base64Data = OSSUtil.downloadToBase64(personInfo.getFaceImageUrl() + "?x-oss-process=image/resize,h_600");

        List<PacsResult> pacsResultList = new ArrayList<>();

        for (DeviceInfo deviceInfo : deviceList) {
            try {
                PacsResult pacsResult = new PacsResult();

                if (HIK_VISION.equals(deviceInfo.getManufacturer())){
                    pacsResult = eHomeService.addPersonToDevice(id, deviceInfo.getId());
                }
                else{
                    pacsResult = lapiService.addPersonToDevice(id, deviceInfo.getId());
                }

                pacsResultList.add(pacsResult);
            } catch (OfflineException e) {
                log.error(e.getMessage());
                HashMap<String, Object> dataMap = new HashMap<>();
                dataMap.put("deviceId", deviceInfo.getId());
                dataMap.put("deviceAliasName", deviceInfo.getAliasName());
                dataMap.put("personName", personInfo.getName());
                PacsResult pacsResult = new PacsResult();
                pacsResult.setSuccess(false);
                pacsResult.setMsg(e.getMessage().contains("timed out") ? "设备连接超时" : e.getMessage());
                pacsResult.setData(dataMap);
                pacsResultList.add(pacsResult);
                personDeviceRelationService.updateIsBound(personInfo.getId(), deviceInfo.getId(), null);

                ExecuteFailLog executeFailLog = new ExecuteFailLog();
                executeFailLog.setPersonId(personInfo.getId());
                executeFailLog.setDeviceId(deviceInfo.getId());
                executeFailLog.setCreateTime(new Date());
                executeFailLog.setType("1");
                executeFailLog.setDelFlag(false);
                executeFailLogService.insert(executeFailLog);
            } catch (Exception e) {
                log.error(e.getMessage());
                HashMap<String, Object> dataMap = new HashMap<>();
                dataMap.put("deviceId", deviceInfo.getId());
                dataMap.put("deviceAliasName", deviceInfo.getAliasName());
                dataMap.put("personName", personInfo.getName());
                PacsResult pacsResult = new PacsResult();
                pacsResult.setSuccess(false);
                pacsResult.setMsg(e.getMessage().contains("timed out") ? "设备连接超时" : e.getMessage());
                pacsResult.setData(dataMap);
                pacsResultList.add(pacsResult);
                personDeviceRelationService.updateIsBound(personInfo.getId(), deviceInfo.getId(), null);
            }
        }

        return pacsResultList;
    }

    @Override
    public List<PacsResult> addPersonToDevices(Long id, String deviceIds) throws Exception {
        if (StringUtils.isBlank(deviceIds)) {
            throw new Exception("设备为空");
        }

        PersonInfo personInfo = personInfoService.get(id);
        CompanyInfo companyInfo = companyInfoService.get(personInfo.getCompanyId());
        String base64Data = OSSUtil.downloadToBase64(personInfo.getFaceImageUrl() + "?x-oss-process=image/resize,h_600");

        List<String> deviceIdList = Arrays.asList(deviceIds.split(","));
        List<PacsResult> pacsResultList = new ArrayList<>();

        for (String deviceId : deviceIdList) {
            DeviceInfo deviceInfo = deviceInfoService.get(deviceId);

            try {
                PacsResult pacsResult = null;

                if (HIK_VISION.equals(deviceInfo.getManufacturer())){
                    pacsResult = eHomeService.addPersonToDevice(id, deviceInfo.getId());
                }
                else{
                    pacsResult = lapiService.addPersonToDevice(id, deviceInfo.getId());
                }

                pacsResultList.add(pacsResult);
            } catch (OfflineException e) {
                log.error(e.getMessage());
                HashMap<String, Object> dataMap = new HashMap<>();
                dataMap.put("deviceId", deviceInfo.getId());
                dataMap.put("deviceAliasName", deviceInfo.getAliasName());
                dataMap.put("personName", personInfo.getName());
                PacsResult pacsResult = new PacsResult();
                pacsResult.setSuccess(false);
                pacsResult.setMsg(e.getMessage().contains("timed out") ? "设备连接超时" : e.getMessage());
                pacsResult.setData(dataMap);
                pacsResultList.add(pacsResult);
                personDeviceRelationService.updateIsBound(personInfo.getId(), deviceInfo.getId(), null);

                ExecuteFailLog executeFailLog = new ExecuteFailLog();
                executeFailLog.setPersonId(personInfo.getId());
                executeFailLog.setDeviceId(deviceInfo.getId());
                executeFailLog.setCreateTime(new Date());
                executeFailLog.setType("1");
                executeFailLog.setDelFlag(false);
                executeFailLogService.insert(executeFailLog);
            } catch (Exception e) {
                log.error(e.getMessage());
                HashMap<String, Object> dataMap = new HashMap<>();
                dataMap.put("deviceId", deviceInfo.getId());
                dataMap.put("deviceAliasName", deviceInfo.getAliasName());
                dataMap.put("personName", personInfo.getName());
                PacsResult pacsResult = new PacsResult();
                pacsResult.setSuccess(false);
                pacsResult.setMsg(e.getMessage().contains("timed out") ? "设备连接超时" : e.getMessage());
                pacsResult.setData(dataMap);
                pacsResultList.add(pacsResult);
                personDeviceRelationService.updateIsBound(personInfo.getId(), deviceInfo.getId(), null);
            }
        }


        return pacsResultList;
    }

    @Override
    public PacsResult addPersonToDevice(Long id, String deviceId) throws Exception {
        PacsResult pacsResult = new PacsResult();
        DeviceInfo deviceInfo = null;

        try {
            deviceInfo = deviceInfoService.get(deviceId);

            if (HIK_VISION.equals(deviceInfo.getManufacturer())){
                pacsResult = eHomeService.addPersonToDevice(id, deviceInfo.getId());
            }
            else{
                pacsResult = lapiService.addPersonToDevice(id, deviceInfo.getId());
            }
        } catch (OfflineException e) {
            pacsResult.setMsg(e.getMessage());
            pacsResult.setSuccess(false);

            ExecuteFailLog executeFailLog = new ExecuteFailLog();
            executeFailLog.setPersonId(id);
            executeFailLog.setDeviceId(deviceInfo.getId());
            executeFailLog.setCreateTime(new Date());
            executeFailLog.setType("1");
            executeFailLog.setDelFlag(false);
            executeFailLogService.insert(executeFailLog);
        } catch (Exception ex) {
            pacsResult.setMsg(ex.getMessage());
            pacsResult.setSuccess(false);
        }

        return pacsResult;
    }

    @Override
    public List<PacsMsgResult> deletePerson(Long personId) throws Exception {
        PersonInfo personInfo = personInfoService.getIgnoreDelFlag(personId);
        if (personInfo == null) {
            throw new Exception("人员不存在");
        }

        List<PersonDeviceRelation> listRelation = personDeviceRelationService.findByPersonId(personId);

        if (listRelation.size() <= 0) {
            throw new Exception("人员未绑定设备");
        }

        List<DeviceInfo> deviceList = new ArrayList<>();
        for (PersonDeviceRelation personDeviceRelation : listRelation) {
            DeviceInfo deviceInfo = deviceInfoService.get(personDeviceRelation.getDeviceId());
            if (deviceInfo != null && !deviceInfo.getDelFlag()) {
                deviceList.add(deviceInfo);
            }
        }
        if (deviceList.size() <= 0) {
            throw new Exception("人员与设备绑定错误");
        }

        List<PacsMsgResult> pacsMsgResults = new ArrayList<>();

        for (DeviceInfo deviceInfo : deviceList) {
            PacsMsgResult pacsMsgResult = new PacsMsgResult();
            pacsMsgResult.setPersonId(personId);
            pacsMsgResult.setDeviceId(deviceInfo.getId());
            pacsMsgResult.setPersonName(personInfo.getName());
            pacsMsgResult.setAliasName(deviceInfo.getAliasName());

            try {
                if (HIK_VISION.equals(deviceInfo.getManufacturer())){
                    pacsMsgResult = eHomeService.deletePersonFromDevice(personId,deviceInfo.getId());
                }
                else{
                    pacsMsgResult = lapiService.deletePersonFromDevice(personId,deviceInfo.getId());
                }

                pacsMsgResults.add(pacsMsgResult);
            } catch (OfflineException e) {
                log.error(e.getMessage());
                pacsMsgResult = new PacsMsgResult();
                pacsMsgResult.setPersonName(personInfo.getName());
                pacsMsgResult.setSuccess(false);
                pacsMsgResult.setMsg(e.getMessage());
                pacsMsgResult.setAliasName(deviceInfo.getAliasName());
                pacsMsgResults.add(pacsMsgResult);

                ExecuteFailLog executeFailLog = new ExecuteFailLog();
                executeFailLog.setPersonId(personInfo.getId());
                executeFailLog.setDeviceId(deviceInfo.getId());
                executeFailLog.setCreateTime(new Date());
                executeFailLog.setType("2");
                executeFailLog.setDelFlag(false);
                executeFailLogService.insert(executeFailLog);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                pacsMsgResult = new PacsMsgResult();
                pacsMsgResult.setPersonName(personInfo.getName());
                pacsMsgResult.setSuccess(false);
                pacsMsgResult.setMsg(e.getMessage());
                pacsMsgResult.setAliasName(deviceInfo.getAliasName());
                pacsMsgResults.add(pacsMsgResult);
            }
        }

        return pacsMsgResults;
    }

    @Override
    public List<PacsMsgResult> deletePersonFromDevice(Long personId, String deviceIds) throws Exception {
        if (StringUtils.isBlank(deviceIds)) {
            throw new Exception("相关设备不能为空");
        }
        PersonInfo personInfo = personInfoService.getIgnoreDelFlag(personId);

        if (personInfo == null) {
            throw new Exception("人员信息不存在");
        }

        CompanyInfo companyInfo = companyInfoService.get(personInfo.getCompanyId());
        if (companyInfo == null) {
            throw new Exception("人员没有相应公司");
        }

        List<PacsMsgResult> pacsMsgResults = new ArrayList<>();
        List<String> deviceIdList = Arrays.asList(deviceIds.split(","));

        for (String deviceId : deviceIdList) {
            DeviceInfo deviceInfo = deviceInfoService.get(deviceId);

            PacsMsgResult pacsMsgResult = new PacsMsgResult();
            pacsMsgResult.setPersonId(personId);
            pacsMsgResult.setDeviceId(deviceId);
            pacsMsgResult.setPersonName(personInfo.getName());
            pacsMsgResult.setAliasName(deviceInfo.getAliasName());

            try {
                if (HIK_VISION.equals(deviceInfo.getManufacturer())){
                    pacsMsgResult = eHomeService.deletePersonFromDevice(personId,deviceInfo.getId());
                }
                else{
                    pacsMsgResult = lapiService.deletePersonFromDevice(personId,deviceInfo.getId());
                }

                pacsMsgResults.add(pacsMsgResult);
            } catch (OfflineException e) {
                log.error(e.getMessage() + ",personId={},deviceIds={}",personId,deviceIds);
                pacsMsgResult.setSuccess(false);
                pacsMsgResult.setMsg(e.getMessage());

                ExecuteFailLog executeFailLog = new ExecuteFailLog();
                executeFailLog.setPersonId(personInfo.getId());
                executeFailLog.setDeviceId(deviceInfo.getId());
                executeFailLog.setCreateTime(new Date());
                executeFailLog.setDelFlag(false);
                executeFailLog.setType("2");
                executeFailLogService.insert(executeFailLog);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                pacsMsgResult.setSuccess(false);
                pacsMsgResult.setMsg(e.getMessage());
            }

            pacsMsgResults.add(pacsMsgResult);
        }

        return pacsMsgResults;
    }

    @Override
    public PacsMsgResult remoteOpen(String deviceId) throws Exception {
        PacsMsgResult msgResult = new PacsMsgResult();

        DeviceInfo deviceInfo = deviceInfoService.get(deviceId);
        if (deviceInfo == null) {
            throw new Exception("设备不存在");
        }
        if (deviceInfo.getDelFlag()) {
            throw new Exception("设备已删除");
        }

        if (HIK_VISION.equals(deviceInfo.getManufacturer())){
            msgResult = eHomeService.remoteOpen(deviceId);
        }
        else{
            msgResult = lapiService.remoteOpen(deviceId);
        }

        return msgResult;
    }

    @Override
    public Boolean reboot(String deviceId) throws Exception {
        boolean result = false;

        DeviceInfo deviceInfo = deviceInfoService.get(deviceId);
        if (deviceInfo == null) {
            throw new Exception("设备不存在");
        }
        if (deviceInfo.getDelFlag()) {
            throw new Exception("设备已删除");
        }

        if (HIK_VISION.equals(deviceInfo.getManufacturer())){
            result = eHomeService.reboot(deviceId);
        }
        else{
            result = lapiService.reboot(deviceId);
        }

        return result;
    }

    @Override
    public List<IsPersonExistVo> existPersonInDevice(List<Long> personIdList, DeviceInfo deviceInfo) {
        List<IsPersonExistVo> isPersonExistVoList = null;

        if (HIK_VISION.equals(deviceInfo.getManufacturer())){
            isPersonExistVoList = eHomeService.existPersonInDevice(personIdList,deviceInfo);
        }
        else{
            try {
                isPersonExistVoList = lapiService.existPersonInDevice(personIdList,deviceInfo);
            } catch (Exception e) {
                log.error(e.getMessage(),e);
            }
        }

        return isPersonExistVoList;
    }

    @Override
    public void updateDeviceServerConfig(List<String> deviceNoList, String newAddress, String newPort) throws Exception {
        for (String deviceNo : deviceNoList) {
            DeviceInfo deviceInfo = deviceInfoService.getByDeviceNo(deviceNo);

            if (HIK_VISION.equals(deviceInfo.getManufacturer())) {
                eHomeService.updateDeviceServerConfig(deviceInfo,newAddress,newPort);
            } else {
                lapiService.updateDeviceServerConfig(deviceInfo,newAddress,newPort);
            }
        }
    }
}
