package com.njcn.harmonic.service.upload.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.common.pojo.enums.common.DataStateEnum;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.device.pms.enums.PmsEnum;


import com.njcn.harmonic.mapper.upload.PmsTemProcessApprovalMapper;
import com.njcn.harmonic.mapper.upload.PmsTemProcessTrackMapper;
import com.njcn.harmonic.mapper.upload.PmsTemUserMapper;
import com.njcn.harmonic.pojo.dto.upload.RUploadMainMonitorDataDTO;
import com.njcn.harmonic.pojo.param.UploadDataParam;
import com.njcn.harmonic.pojo.param.upload.PmsTemUserParam;
import com.njcn.harmonic.pojo.po.upload.PmsTemProcessApproval;
import com.njcn.harmonic.pojo.po.upload.PmsTemProcessTrackPO;
import com.njcn.harmonic.pojo.po.upload.PmsTemUserPO;
import com.njcn.harmonic.pojo.po.upload.RUploadMainMonitorData;
import com.njcn.harmonic.service.upload.IPmsTemProcessTrackService;
import com.njcn.harmonic.service.upload.IPmsTemUserService;
import com.njcn.system.enums.DicDataEnum;
import com.njcn.user.api.DeptFeignClient;
import com.njcn.user.pojo.vo.DeptTreeVO;
import com.njcn.user.pojo.vo.PvTerminalTreeVO;
import com.njcn.web.enums.GWSendEnum;
import com.njcn.web.factory.PageFactory;
import com.njcn.web.pojo.param.SendParam;
import com.njcn.web.utils.GwSendUtil;
import com.njcn.web.utils.RequestUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 * 电能质量全过程管理用户 服务实现类
 * </p>
 *
 * @author cdf
 * @since 2024-10-09
 */
@Service
@RequiredArgsConstructor
public class PmsTemUserServiceImpl extends ServiceImpl<PmsTemUserMapper, PmsTemUserPO> implements IPmsTemUserService {

    private final DeptFeignClient deptFeignClient;

    private final PmsTemProcessTrackMapper pmsTemProcessTrackMapper;

    private final PmsTemProcessApprovalMapper pmsTemProcessApprovalMapper;




    @Override
    public Boolean addPmsTemUser(PmsTemUserParam param) {
        PmsTemUserPO pmsTemUserPO = new PmsTemUserPO();
        BeanUtil.copyProperties(param, pmsTemUserPO);
        assOrg(pmsTemUserPO);
        pmsTemUserPO.setUploadStatus(Integer.valueOf(DicDataEnum.No_Upload.getCode()));
        pmsTemUserPO.setCreateTime(new Timestamp(new Date().getTime()));
        pmsTemUserPO.setUpdateTime(new Timestamp(new Date().getTime()));
        return this.save(pmsTemUserPO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updatePmsTemUser(PmsTemUserParam.UpdatePmsTemUserParam updatePmsTemUserParam) {
        PmsTemUserPO result = this.getById(updatePmsTemUserParam.getObjId());
        PmsTemUserPO pmsTemUserPO = new PmsTemUserPO();
        BeanUtil.copyProperties(updatePmsTemUserParam, pmsTemUserPO);
        if(!result.getMaintOrg().equals(updatePmsTemUserParam.getMaintOrg())){
            assOrg(pmsTemUserPO);
        }

        if(!updatePmsTemUserParam.getConsName().equals(result.getConsName())){
            //修改全过程表数据
            LambdaUpdateWrapper<PmsTemProcessTrackPO> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.set(PmsTemProcessTrackPO::getTempUserDossierName,updatePmsTemUserParam.getConsName()).eq(PmsTemProcessTrackPO::getTempUserDossierId,result.getObjId());
            pmsTemProcessTrackMapper.update(null,updateWrapper);
        }

        if(Integer.valueOf(DicDataEnum.Has_Upload.getCode()).equals(result.getUploadStatus())){
            pmsTemUserPO.setUploadStatus(Integer.valueOf(DicDataEnum.Return_Upload.getCode()));
        }
        pmsTemUserPO.setUpdateTime(new Timestamp(new Date().getTime()));
        pmsTemUserPO.setUploadStatus(Integer.valueOf(DicDataEnum.Return_Upload.getCode()));
        return this.updateById(pmsTemUserPO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean delPmsTemUser(List<String> ids) {

        long count = pmsTemProcessApprovalMapper.selectCount(new LambdaQueryWrapper<PmsTemProcessApproval>().in(PmsTemProcessApproval::getTempUserDossierId,ids));
        if(count>0){
            throw new BusinessException("当前用户存在评估文档整改情况,不可删除");
        }
        this.removeByIds(ids);
        pmsTemProcessTrackMapper.delete(new LambdaQueryWrapper<PmsTemProcessTrackPO>().in(PmsTemProcessTrackPO::getTempUserDossierId,ids));
        return true;
    }

    @Override
    public Page<PmsTemUserPO> pageList(PmsTemUserParam.QueryPmsTemUserParam parkQuery) {
        List<String> deptCodes = deptFeignClient.getDepSonSelfCodetByDeptId(parkQuery.getMaintOrg()).getData();
        LambdaQueryWrapper<PmsTemUserPO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(PmsTemUserPO::getMaintOrg, deptCodes).orderByDesc(PmsTemUserPO::getCreateTime, PmsTemUserPO::getCityOrgName);
        return this.page(new Page<>(PageFactory.getPageNum(parkQuery), PageFactory.getPageSize(parkQuery)), lambdaQueryWrapper);
    }

    @Override
    public List<PmsTemUserPO> selectList(PmsTemUserParam.QueryPmsTemUserParam param) {
        if(StrUtil.isBlank(param.getMaintOrg())){
            throw new BusinessException("请选择单位组织");
        }
        List<String> deptCodes = deptFeignClient.getDepSonSelfCodetByCode(param.getMaintOrg()).getData();
        LambdaQueryWrapper<PmsTemUserPO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.select(PmsTemUserPO::getObjId,PmsTemUserPO::getConsName)
                .in(PmsTemUserPO::getMaintOrg, deptCodes).orderByDesc(PmsTemUserPO::getCreateTime, PmsTemUserPO::getCityOrgName);
        return this.list(lambdaQueryWrapper);
    }

    @Override
    public Boolean upGwTemUser(List<String> ids) {
        LambdaQueryWrapper<PmsTemUserPO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(PmsTemUserPO::getObjId,ids);
        List<PmsTemUserPO> pmsTemUserPOList = this.list(lambdaQueryWrapper);
        if(CollUtil.isEmpty(pmsTemUserPOList)){
            throw new BusinessException("查询用户临时档案数据为空");
        }


        pmsTemUserPOList.forEach(item->{
            item.setGcVoltageLevel(String.format("%02d",Integer.valueOf(item.getGcVoltageLevel())));
            item.setGcSubstationVoltageLevel(String.format("%02d",Integer.valueOf(item.getGcSubstationVoltageLevel())));
        });

        List<List<PmsTemUserPO>> list = CollUtil.split(pmsTemUserPOList,100);
        for(int i=0;i<list.size();i++){
            SendParam sendParam = new SendParam();
            if(i==0){
                sendParam.setIsAppend("0");
            }else if(i==list.size()-1){
                sendParam.setIsAppend("2");
            }else {
                sendParam.setIsAppend("1");
            }
            sendParam.setStats(list.get(i));
            Map<String, String> sendRes = GwSendUtil.newSend(sendParam, GWSendEnum.TEMP_USER_CREATE);
            List<String> pmsTemUserPOIds = list.get(i).stream().map(PmsTemUserPO::getObjId).collect(Collectors.toList());
            int count = GwSendUtil.returnInfoMsg(pmsTemUserPOIds,sendRes);
            System.out.println("上送成功,上送成功返回"+count+"条");
            if(count == list.get(i).size()){
                LambdaUpdateWrapper<PmsTemUserPO> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                lambdaUpdateWrapper.set(PmsTemUserPO::getUploadStatus,Integer.valueOf(DicDataEnum.Has_Upload.getCode())).in(PmsTemUserPO::getObjId,ids);
                this.update(lambdaUpdateWrapper);
            }
        }
        return true;
    }

    private void assOrg(PmsTemUserPO pmsTemUserPO){
        List<PvTerminalTreeVO> deptTreeVOList = deptFeignClient.allDeptList().getData();
        List<PvTerminalTreeVO> provinceList = deptTreeVOList.stream().filter(item->item.getLevel() == 2).collect(Collectors.toList());
        pmsTemUserPO.setProvinceOrg(provinceList.get(0).getCode());
        pmsTemUserPO.setProvinceOrgName(provinceList.get(0).getName());
        Map<String,PvTerminalTreeVO> deptCodeMap = deptTreeVOList.stream().collect(Collectors.toMap(PvTerminalTreeVO::getCode, Function.identity()));
        Map<String,PvTerminalTreeVO> deptIdMap = deptTreeVOList.stream().collect(Collectors.toMap(PvTerminalTreeVO::getId, Function.identity()));
        PvTerminalTreeVO pvTerminalTreeVO = deptCodeMap.get(pmsTemUserPO.getMaintOrg());
        if(pvTerminalTreeVO.getLevel() == 4){
            //运维单位是县级
            PvTerminalTreeVO parent =  deptIdMap.get(pvTerminalTreeVO.getPid());
            pmsTemUserPO.setCityOrg(parent.getCode());
            pmsTemUserPO.setCityOrgName(parent.getName());
        }else if(pvTerminalTreeVO.getLevel() == 3){
            pmsTemUserPO.setCityOrg(pvTerminalTreeVO.getCode());
            pmsTemUserPO.setCityOrgName(pvTerminalTreeVO.getName());
        }else if(pvTerminalTreeVO.getLevel() == 2){

        }else {
            throw new BusinessException("请选择正确的运维单位！");
        }


    }

}
