package cn.gintone.service;

import cn.gintone.ErrorInfo;
import cn.gintone.controller.vo.DeviceReqConfListReqVO;
import cn.gintone.controller.vo.DeviceReqConfSaveReqVO;
import cn.gintone.dal.DeviceReqConfMapper;
import cn.gintone.dal.DeviceTypeMapper;
import cn.gintone.dto.PtExportDevice;
import cn.gintone.dto.PtExportDeviceType;
import cn.gintone.dtoPt.*;
import cn.gintone.entity.DeviceReqConfDO;
import cn.gintone.entity.DeviceTypeDO;
import cn.gintone.myconf.BasicUrlConf;
import cn.gintone.utils.BasicInfoHttpUtils;
import cn.gintone.utils.PtExportDeviceUtils;
import cn.iocoder.yudao.module.system.controller.admin.auth.myVo.PtResult;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;

import java.io.IOException;
import java.util.*;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;


import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;

/**
 * 物联网设备请求配置 Service 实现类
 *
 * @author 安全系统管理
 */
@Service
@Validated
public class DeviceReqConfServiceImpl implements DeviceReqConfService {
    @Resource
    private BasicUrlConf basicUrlConf;
    @Resource
    private DeviceReqConfMapper deviceReqConfMapper;
    @Resource
    private DeviceTypeMapper deviceTypeMapper;

    @Override
    public Long createDeviceReqConf(DeviceReqConfSaveReqVO createReqVO) {
        // 校验父级id的有效性
        validateParentDeviceReqConf(null, createReqVO.getParentId());
        // 校验设备名称的唯一性
        validateDeviceReqConfDeviceNameUnique(null, createReqVO.getParentId(), createReqVO.getDeviceName());

        // 插入
        DeviceReqConfDO deviceReqConf = BeanUtils.toBean(createReqVO, DeviceReqConfDO.class);
        deviceReqConfMapper.insert(deviceReqConf);
        // 返回
        return deviceReqConf.getId();
    }

    @Override
    public void updateDeviceReqConf(DeviceReqConfSaveReqVO updateReqVO) {
        // 校验存在
        validateDeviceReqConfExists(updateReqVO.getId());
        // 校验父级id的有效性
        validateParentDeviceReqConf(updateReqVO.getId(), updateReqVO.getParentId());
        // 校验设备名称的唯一性
        validateDeviceReqConfDeviceNameUnique(updateReqVO.getId(), updateReqVO.getParentId(), updateReqVO.getDeviceName());

        // 更新
        DeviceReqConfDO updateObj = BeanUtils.toBean(updateReqVO, DeviceReqConfDO.class);
        deviceReqConfMapper.updateById(updateObj);
    }

    @Override
    public void deleteDeviceReqConf(Long id) {
        // 校验存在
        validateDeviceReqConfExists(id);
        // 校验是否有子物联网设备请求配置
        if (deviceReqConfMapper.selectCountByParentId(id) > 0) {
            throw exception(ErrorInfo.DEVICE_REQ_CONF_EXITS_CHILDREN);
        }
        // 删除
        deviceReqConfMapper.deleteById(id);
    }

    private void validateDeviceReqConfExists(Long id) {
        if (deviceReqConfMapper.selectById(id) == null) {
            throw exception(ErrorInfo.DEVICE_REQ_CONF_NOT_EXISTS);
        }
    }

    private void validateParentDeviceReqConf(Long id, Long parentId) {
        if (parentId == null || DeviceReqConfDO.PARENT_ID_ROOT.equals(parentId)) {
            return;
        }
        // 1. 不能设置自己为父物联网设备请求配置
        if (Objects.equals(id, parentId)) {
            throw exception(ErrorInfo.DEVICE_REQ_CONF_PARENT_ERROR);
        }
        // 2. 父物联网设备请求配置不存在
        DeviceReqConfDO parentDeviceReqConf = deviceReqConfMapper.selectById(parentId);
        if (parentDeviceReqConf == null) {
            throw exception(ErrorInfo.DEVICE_REQ_CONF_PARENT_NOT_EXITS);
        }
        // 3. 递归校验父物联网设备请求配置，如果父物联网设备请求配置是自己的子物联网设备请求配置，则报错，避免形成环路
        if (id == null) { // id 为空，说明新增，不需要考虑环路
            return;
        }
        for (int i = 0; i < Short.MAX_VALUE; i++) {
            // 3.1 校验环路
            parentId = parentDeviceReqConf.getParentId();
            if (Objects.equals(id, parentId)) {
                throw exception(ErrorInfo.DEVICE_REQ_CONF_PARENT_IS_CHILD);
            }
            // 3.2 继续递归下一级父物联网设备请求配置
            if (parentId == null || DeviceReqConfDO.PARENT_ID_ROOT.equals(parentId)) {
                break;
            }
            parentDeviceReqConf = deviceReqConfMapper.selectById(parentId);
            if (parentDeviceReqConf == null) {
                break;
            }
        }
    }

    private void validateDeviceReqConfDeviceNameUnique(Long id, Long parentId, String deviceName) {
        DeviceReqConfDO deviceReqConf = deviceReqConfMapper.selectByParentIdAndDeviceName(parentId, deviceName);
        if (deviceReqConf == null) {
            return;
        }
        // 如果 id 为空，说明不用比较是否为相同 id 的物联网设备请求配置
        if (id == null) {
            throw exception(ErrorInfo.DEVICE_REQ_CONF_DEVICE_NAME_DUPLICATE);
        }
        if (!Objects.equals(deviceReqConf.getId(), id)) {
            throw exception(ErrorInfo.DEVICE_REQ_CONF_DEVICE_NAME_DUPLICATE);
        }
    }

    @Override
    public DeviceReqConfDO getDeviceReqConf(Long id) {
        return deviceReqConfMapper.selectById(id);
    }

    @Override
    public List<DeviceReqConfDO> getDeviceReqConfList(DeviceReqConfListReqVO listReqVO) {
        return deviceReqConfMapper.selectList(listReqVO);
    }

    /*@Override
    public String syncPtDevice() {
        DeviceReqConfDO deviceReqConfDO_bz_type = deviceReqConfMapper.selectOne(new QueryWrapper<DeviceReqConfDO>()
                .lambda()
                .eq(DeviceReqConfDO::getDeviceEn, "bz")
        );
        PtResult<PtData<PtBzInfo>> bzInfo = BasicInfoHttpUtils.getBzInfo(basicUrlConf.getBzInfoUrl(), "", "");
        if (null != bzInfo) {
            PtData<PtBzInfo> data = bzInfo.getData();
            if (null != data) {
                List<PtBzInfo> rowDataList = data.getRowData();
                if (null != rowDataList) {
                    for (PtBzInfo ptBzInfo : rowDataList) {
                        DeviceReqConfDO deviceReqConf = new DeviceReqConfDO();
                        deviceReqConf.setDeviceName(ptBzInfo.getName());
                        deviceReqConf.setDeviceId(ptBzInfo.getId() + "");
                        deviceReqConf.setDeviceTypeId(ptBzInfo.getBztype_id());
                        deviceReqConf.setDeviceTypeName(ptBzInfo.getBztype());
                        deviceReqConf.setParentId(deviceReqConfDO_bz_type.getId());
                        deviceReqConf.setSnCode(ptBzInfo.getId() + "");
                        deviceReqConf.setAddress(ptBzInfo.getAddress());
                        deviceReqConf.setRegionName(ptBzInfo.getBgq());
                        DeviceReqConfDO deviceReqConfDO = deviceReqConfMapper.selectOne(new QueryWrapper<DeviceReqConfDO>()
                                .lambda()
                                .eq(DeviceReqConfDO::getDeviceId, deviceReqConf.getDeviceId())
                                .eq(DeviceReqConfDO::getSnCode, deviceReqConf.getSnCode())
                        );
                        if (null != deviceReqConfDO) {
                            deviceReqConfDO.setDeviceName(ptBzInfo.getName());
                            deviceReqConfDO.setDeviceId(ptBzInfo.getId() + "");
                            deviceReqConfDO.setDeviceTypeId(ptBzInfo.getBztype_id());
                            deviceReqConfDO.setDeviceTypeName(ptBzInfo.getBztype());
                            deviceReqConfDO.setParentId(deviceReqConfDO_bz_type.getId());
                            deviceReqConfDO.setSnCode(ptBzInfo.getId() + "");
                            deviceReqConfDO.setAddress(ptBzInfo.getAddress());
                            deviceReqConfDO.setRegionName(ptBzInfo.getBgq());
                            deviceReqConfMapper.updateById(deviceReqConfDO);
                        } else {
                            deviceReqConfMapper.insert(deviceReqConf);
                        }
                    }
                }
            }
        }


        DeviceReqConfDO deviceReqConfDO_fkcl_type = deviceReqConfMapper.selectOne(new QueryWrapper<DeviceReqConfDO>()
                .lambda()
                .eq(DeviceReqConfDO::getDeviceEn, "fk")
        );
        PtResult<PtData<PtCarInfo>> fkclInfoList = BasicInfoHttpUtils.getFKCLInfo(basicUrlConf.getFkclInfoUrl(), "", "");
        if (null != fkclInfoList) {
            PtData<PtCarInfo> data = fkclInfoList.getData();
            if (null != data) {
                List<PtCarInfo> rowDataList = data.getRowData();
                if (null != rowDataList) {
                    for (PtCarInfo ptCarInfo : rowDataList) {
                        DeviceReqConfDO deviceReqConf = new DeviceReqConfDO();
                        deviceReqConf.setDeviceId(ptCarInfo.getId() + "");
                        deviceReqConf.setSnCode(ptCarInfo.getCphm());
                        deviceReqConf.setDeviceTypeId(ptCarInfo.getCllxbm());
                        deviceReqConf.setParentId(deviceReqConfDO_fkcl_type.getId());
                        deviceReqConf.setDeviceTypeName(ptCarInfo.getCllx());
                        DeviceReqConfDO deviceReqConfDO = deviceReqConfMapper.selectOne(new QueryWrapper<DeviceReqConfDO>()
                                .lambda()
                                .eq(DeviceReqConfDO::getDeviceId, deviceReqConf.getDeviceId())
                                .eq(DeviceReqConfDO::getSnCode, deviceReqConf.getSnCode())
                        );
                        if (null != deviceReqConfDO) {
                            deviceReqConfDO.setDeviceId(ptCarInfo.getId() + "");
                            deviceReqConfDO.setSnCode(ptCarInfo.getCphm());
                            deviceReqConfDO.setDeviceTypeId(ptCarInfo.getCllxbm());
                            deviceReqConfDO.setDeviceTypeName(ptCarInfo.getCllx());
                            deviceReqConfDO.setParentId(deviceReqConfDO_fkcl_type.getId());
                            deviceReqConfMapper.updateById(deviceReqConfDO);
                        } else {
                            deviceReqConfMapper.insert(deviceReqConf);
                        }
                    }
                }
            }
        }


        DeviceReqConfDO deviceReqConfDO_sxt_type = deviceReqConfMapper.selectOne(new QueryWrapper<DeviceReqConfDO>()
                .lambda()
                .eq(DeviceReqConfDO::getDeviceEn, "sxt")
        );
        PtResult<PtData<PtSXTInfo>> sxtInfoList = BasicInfoHttpUtils.getSXTInfo(basicUrlConf.getSxtInfoUrl(), "", "");
        if (null != sxtInfoList) {
            PtData<PtSXTInfo> data = sxtInfoList.getData();
            if (null != data) {
                List<PtSXTInfo> rowDataList = data.getRowData();
                if (null != rowDataList) {
                    for (PtSXTInfo ptSXTInfo : rowDataList) {
                        DeviceReqConfDO deviceReqConf = new DeviceReqConfDO();
                        deviceReqConf.setDeviceName(ptSXTInfo.getSxtmc());
                        deviceReqConf.setDeviceId(ptSXTInfo.getId() + "");
                        deviceReqConf.setDeviceTypeId(ptSXTInfo.getSxtlxbh());
                        deviceReqConf.setDeviceTypeName(ptSXTInfo.getSxtlxmc());
                        deviceReqConf.setParentId(deviceReqConfDO_sxt_type.getId());
                        deviceReqConf.setSnCode(ptSXTInfo.getSxtbh() + "");
                        deviceReqConf.setAddress(ptSXTInfo.getWzbs());

                        DeviceReqConfDO deviceReqConfDO = deviceReqConfMapper.selectOne(new QueryWrapper<DeviceReqConfDO>()
                                .lambda()
                                .eq(DeviceReqConfDO::getDeviceId, deviceReqConf.getDeviceId())
                                .eq(DeviceReqConfDO::getSnCode, deviceReqConf.getSnCode())
                        );
                        if (null != deviceReqConfDO) {
                            deviceReqConfDO.setDeviceName(ptSXTInfo.getSxtmc());
                            deviceReqConfDO.setDeviceId(ptSXTInfo.getId() + "");
                            deviceReqConfDO.setDeviceTypeId(ptSXTInfo.getSxtlxbh());
                            deviceReqConfDO.setDeviceTypeName(ptSXTInfo.getSxtlxmc());
                            deviceReqConfDO.setParentId(deviceReqConfDO_sxt_type.getId());
                            deviceReqConfDO.setSnCode(ptSXTInfo.getSxtbh() + "");
                            deviceReqConfDO.setAddress(ptSXTInfo.getWzbs());
                            deviceReqConfMapper.updateById(deviceReqConfDO);
                        } else {
                            deviceReqConfMapper.insert(deviceReqConf);
                        }
                    }
                }
            }
        }


        DeviceReqConfDO deviceReqConfDO_yld_type = deviceReqConfMapper.selectOne(new QueryWrapper<DeviceReqConfDO>()
                .lambda()
                .eq(DeviceReqConfDO::getDeviceEn, "yld")
        );
        PtResult<PtData<PtYLDInfo>> yldInfoList = BasicInfoHttpUtils.getYLDInfo(basicUrlConf.getYldInfoUrl(), "", "");
        if (null != yldInfoList) {
            PtData<PtYLDInfo> data = yldInfoList.getData();
            if (null != data) {
                List<PtYLDInfo> rowDataList = data.getRowData();
                if (null != rowDataList) {
                    for (PtYLDInfo ptYLDInfo : rowDataList) {
                        DeviceReqConfDO deviceReqConf = new DeviceReqConfDO();
                        deviceReqConf.setDeviceName(ptYLDInfo.getSbname());
                        deviceReqConf.setDeviceId(ptYLDInfo.getId() + "");
                        deviceReqConf.setDeviceTypeId(ptYLDInfo.getCategory_id());
                        deviceReqConf.setDeviceTypeName(ptYLDInfo.getCategory());
                        deviceReqConf.setParentId(deviceReqConfDO_yld_type.getId());
                        deviceReqConf.setSnCode(ptYLDInfo.getSncode() + "");
                        deviceReqConf.setAddress(ptYLDInfo.getAddress());
                        deviceReqConf.setRegionName(ptYLDInfo.getRegion_name());

                        DeviceReqConfDO deviceReqConfDO = deviceReqConfMapper.selectOne(new QueryWrapper<DeviceReqConfDO>()
                                .lambda()
                                .eq(DeviceReqConfDO::getDeviceId, deviceReqConf.getDeviceId())
                                .eq(DeviceReqConfDO::getSnCode, deviceReqConf.getSnCode())
                        );
                        if (null != deviceReqConfDO) {
                            deviceReqConfDO.setDeviceName(ptYLDInfo.getSbname());
                            deviceReqConfDO.setDeviceId(ptYLDInfo.getId() + "");
                            deviceReqConfDO.setDeviceTypeId(ptYLDInfo.getCategory_id());
                            deviceReqConfDO.setDeviceTypeName(ptYLDInfo.getCategory());
                            deviceReqConfDO.setParentId(deviceReqConfDO_yld_type.getId());
                            deviceReqConfDO.setSnCode(ptYLDInfo.getSncode() + "");
                            deviceReqConfDO.setAddress(ptYLDInfo.getAddress());
                            deviceReqConfDO.setRegionName(ptYLDInfo.getRegion_name());
                            deviceReqConfMapper.updateById(deviceReqConfDO);
                        } else {
                            deviceReqConfMapper.insert(deviceReqConf);
                        }

                    }
                }
            }
        }

        DeviceReqConfDO deviceReqConfDO_gd_type = deviceReqConfMapper.selectOne(new QueryWrapper<DeviceReqConfDO>()
                .lambda()
                .eq(DeviceReqConfDO::getDeviceEn, "gd")
        );
        PtResult<PtData<PtGdInfo>> gdInfoList = BasicInfoHttpUtils.getGDInfo(basicUrlConf.getGdInfoUrl(), "", "");
        if (null != gdInfoList) {
            PtData<PtGdInfo> data = gdInfoList.getData();
            if (null != data) {
                List<PtGdInfo> rowDataList = data.getRowData();
                if (null != rowDataList) {
                    for (PtGdInfo ptGdInfo : rowDataList) {
                        DeviceReqConfDO deviceReqConf = new DeviceReqConfDO();
                        deviceReqConf.setDeviceName(ptGdInfo.getSbname());
                        deviceReqConf.setDeviceId(ptGdInfo.getId() + "");
                        deviceReqConf.setDeviceTypeId(ptGdInfo.getCategory_id());
                        deviceReqConf.setDeviceTypeName(ptGdInfo.getCategory());
                        deviceReqConf.setParentId(deviceReqConfDO_gd_type.getId());
                        deviceReqConf.setSnCode(ptGdInfo.getSncode() + "");
                        deviceReqConf.setAddress(ptGdInfo.getAddress());
                        deviceReqConf.setRegionName(ptGdInfo.getRegion_name());

                        DeviceReqConfDO deviceReqConfDO = deviceReqConfMapper.selectOne(new QueryWrapper<DeviceReqConfDO>()
                                .lambda()
                                .eq(DeviceReqConfDO::getDeviceId, deviceReqConf.getDeviceId())
                                .eq(DeviceReqConfDO::getSnCode, deviceReqConf.getSnCode())
                        );
                        if (null != deviceReqConfDO) {
                            deviceReqConfDO.setDeviceName(ptGdInfo.getSbname());
                            deviceReqConfDO.setDeviceId(ptGdInfo.getId() + "");
                            deviceReqConfDO.setDeviceTypeId(ptGdInfo.getCategory_id());
                            deviceReqConfDO.setDeviceTypeName(ptGdInfo.getCategory());
                            deviceReqConfDO.setParentId(deviceReqConfDO_gd_type.getId());
                            deviceReqConfDO.setSnCode(ptGdInfo.getSncode() + "");
                            deviceReqConfDO.setAddress(ptGdInfo.getAddress());
                            deviceReqConfDO.setRegionName(ptGdInfo.getRegion_name());
                            deviceReqConfMapper.updateById(deviceReqConfDO);
                        } else {
                            deviceReqConfMapper.insert(deviceReqConf);
                        }
                    }
                }
            }
        }

        DeviceReqConfDO deviceReqConfDO_jg_type = deviceReqConfMapper.selectOne(new QueryWrapper<DeviceReqConfDO>()
                .lambda()
                .eq(DeviceReqConfDO::getDeviceEn, "jg")
        );
        PtResult<PtData<PtJgInfo>> jgInfo = BasicInfoHttpUtils.getJgInfo(basicUrlConf.getJgInfoUrl(), "", "");
        if (null != jgInfo) {
            PtData<PtJgInfo> data = jgInfo.getData();
            if (null != data) {
                List<PtJgInfo> rowDataList = data.getRowData();
                if (null != rowDataList) {
                    for (PtJgInfo ptJgInfo : rowDataList) {
                        DeviceReqConfDO deviceReqConf = new DeviceReqConfDO();
                        deviceReqConf.setDeviceName(ptJgInfo.getSbname());
                        deviceReqConf.setDeviceId(ptJgInfo.getId() + "");
                        deviceReqConf.setDeviceTypeId(ptJgInfo.getCategory_id());
                        deviceReqConf.setDeviceTypeName(ptJgInfo.getCategory());
                        deviceReqConf.setParentId(deviceReqConfDO_jg_type.getId());
                        deviceReqConf.setSnCode(ptJgInfo.getSncode() + "");
                        deviceReqConf.setAddress(ptJgInfo.getAddress());
                        deviceReqConf.setRegionName(ptJgInfo.getRegion_name());

                        DeviceReqConfDO deviceReqConfDO = deviceReqConfMapper.selectOne(new QueryWrapper<DeviceReqConfDO>()
                                .lambda()
                                .eq(DeviceReqConfDO::getDeviceId, deviceReqConf.getDeviceId())
                                .eq(DeviceReqConfDO::getSnCode, deviceReqConf.getSnCode())
                        );
                        if (null != deviceReqConfDO) {
                            deviceReqConfDO.setDeviceName(ptJgInfo.getSbname());
                            deviceReqConfDO.setDeviceId(ptJgInfo.getId() + "");
                            deviceReqConfDO.setDeviceTypeId(ptJgInfo.getCategory_id());
                            deviceReqConfDO.setDeviceTypeName(ptJgInfo.getCategory());
                            deviceReqConfDO.setParentId(deviceReqConfDO_jg_type.getId());
                            deviceReqConfDO.setSnCode(ptJgInfo.getSncode() + "");
                            deviceReqConfDO.setAddress(ptJgInfo.getAddress());
                            deviceReqConfDO.setRegionName(ptJgInfo.getRegion_name());
                            deviceReqConfMapper.updateById(deviceReqConfDO);
                        } else {
                            deviceReqConfMapper.insert(deviceReqConf);
                        }
                    }
                }
            }
        }

        return "同步成功";
    }*/

    @Override
    public String exportPtDevice() {
        try {
            List<PtExportDevice> ptExportDeviceList = PtExportDeviceUtils.readDevicesFromExcel("D:\\yqd\\2025\\secure\\对接文档\\设备清单.xlsx");
            if(null != ptExportDeviceList && ptExportDeviceList.size() > 0) {
                List<DeviceTypeDO> deviceTypeDOS = deviceTypeMapper.selectList();
                if(null != deviceTypeDOS && deviceTypeDOS.size() > 0) {
                    Map<String, DeviceTypeDO> deviceTypeDOMap = new HashMap<>();
                    for (DeviceTypeDO deviceTypeDO : deviceTypeDOS) {
                        deviceTypeDOMap.put(deviceTypeDO.getModelCode(), deviceTypeDO);
                    }
                    for (PtExportDevice ptExportDevice : ptExportDeviceList) {
                        DeviceReqConfDO deviceReqConf = new DeviceReqConfDO();
                        deviceReqConf.setSnCode(ptExportDevice.getDeviceSerialNo());
                        String modelCode = ptExportDevice.getModelCode();
                        DeviceTypeDO deviceTypeDO = deviceTypeDOMap.get(modelCode);
                        deviceReqConf.setDeviceTypeName(deviceTypeDO.getName());
                        deviceReqConf.setDeviceTypeId(deviceTypeDO.getId());
                        deviceReqConf.setDeviceName(ptExportDevice.getDeviceName());
                        deviceReqConf.setAddress(ptExportDevice.getDescription());
                        deviceReqConf.setDeviceEn(modelCode);
                        deviceReqConfMapper.insert(deviceReqConf);
                    }

                }

            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return "同步成功";
    }

    @Override
    public String exportPtDeviceType() {
        try {
            List<PtExportDeviceType> ptExportDeviceTypes = PtExportDeviceUtils.readDevicesTypeFromExcel("D:\\yqd\\2025\\secure\\对接文档\\产品类型.xlsx");
            if (null != ptExportDeviceTypes && ptExportDeviceTypes.size() > 0) {
                for (PtExportDeviceType deviceType : ptExportDeviceTypes) {
                    DeviceTypeDO deviceTypeDO = new DeviceTypeDO();
                    deviceTypeDO.setName(deviceType.getName());
                    deviceTypeDO.setModelCode(deviceType.getModelCode());
                    deviceTypeDO.setManufacturer(deviceType.getManufacturer());
                    deviceTypeDO.setIntegratedApplicationOwnership(deviceType.getIntegratedApplicationOwnership());
                    deviceTypeMapper.insert(deviceTypeDO);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

}