package com.njcn.process.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.njcn.common.config.GeneralInfo;
import com.njcn.oss.constant.OssPath;
import com.njcn.device.pms.api.DistributionMonitorClient;
import com.njcn.oss.utils.FileStorageUtil;
import com.njcn.process.constant.Param;
import com.njcn.process.mapper.LoadTypeUserManageMapper;
import com.njcn.process.pojo.param.*;
import com.njcn.process.pojo.po.RLoadTypeUserManage;
import com.njcn.process.pojo.vo.LoadTypeRelationExcel;
import com.njcn.process.pojo.vo.LoadTypeUserExcel;
import com.njcn.process.pojo.vo.RLoadTypeUserManageVO;
import com.njcn.process.service.LoadTypeUserManageService;
import com.njcn.system.api.DicDataFeignClient;
import com.njcn.system.enums.DicDataEnum;
import com.njcn.system.enums.DicDataTypeEnum;
import com.njcn.system.pojo.po.DictData;
import com.njcn.user.api.DeptFeignClient;
import com.njcn.user.pojo.vo.PvTerminalTreeVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 干扰源用户管理
 *
 * @author qijian
 * @version 1.0.0
 * @createTime 2022/11/11 - 9:20
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class LoadTypeUserManageServiceImpl implements LoadTypeUserManageService {

    private final LoadTypeUserManageMapper loadTypeUserManageMapper;

    private final DicDataFeignClient dicDataFeignClient;

    private final DistributionMonitorClient distributionMonitorClient;

    private final DeptFeignClient deptFeignClient;

    @Resource
    private GeneralInfo generalInfo;

    private final FileStorageUtil fileStorageUtil;



    /**
     * 干扰源用户分页查询
     *
     * @param loadTypeUserSearchParam
     * @return
     */
    @Override
    public Page<RLoadTypeUserManageVO> getLoadTypeUserList(LoadTypeUserSearchParam loadTypeUserSearchParam) {
        Page<RLoadTypeUserManageVO> page = new Page<>(loadTypeUserSearchParam.getPageNum(), loadTypeUserSearchParam.getPageSize());
        Page<RLoadTypeUserManageVO> loadTypeUserPage = loadTypeUserManageMapper.getLoadTypeUserPage(page, loadTypeUserSearchParam);

        //部门处理：根据部门code取名称
        List<RLoadTypeUserManageVO> list = loadTypeUserPage.getRecords();
        List<PvTerminalTreeVO> dept = deptFeignClient.allDeptList().getData();
        Map<String, PvTerminalTreeVO> pvTerminalTreeVOMap = dept.stream().collect(Collectors.toMap(PvTerminalTreeVO::getId, pvTerminalTreeVO -> pvTerminalTreeVO));
        List<RLoadTypeUserManageVO> resultList = list.stream().map(item -> {
            RLoadTypeUserManageVO rLoadTypeUserManageVO = new RLoadTypeUserManageVO();
            BeanUtils.copyProperties(item, rLoadTypeUserManageVO);
            rLoadTypeUserManageVO.setOrgName(pvTerminalTreeVOMap.get(item.getOrgNo()).getName()); //单位名称
            return rLoadTypeUserManageVO;
        }).collect(Collectors.toList());

        //返回新的数据组
        return loadTypeUserPage.setRecords(resultList);
    }

    /**
     * 根据id查询干扰源用户
     *
     * @param id
     * @return
     */
    @Override
    public RLoadTypeUserManageVO getLoadTypeUserById(String id) {
        RLoadTypeUserManage rLoadTypeUserManage = loadTypeUserManageMapper.selectById(id);
        RLoadTypeUserManageVO rLoadTypeUserManageVO = new RLoadTypeUserManageVO();
        BeanUtils.copyProperties(rLoadTypeUserManage, rLoadTypeUserManageVO);
        //文件
        if (rLoadTypeUserManageVO.getIFilePath() != null) {
            String iFile = fileStorageUtil.getFileUrl(rLoadTypeUserManageVO.getIFilePath());
            rLoadTypeUserManageVO.setIFile(iFile);
        }
        if (rLoadTypeUserManageVO.getAFilePath() != null) {
            String aFile = fileStorageUtil.getFileUrl(rLoadTypeUserManageVO.getAFilePath());
            rLoadTypeUserManageVO.setIFile(aFile);
        }
        return rLoadTypeUserManageVO;
    }

    /**
     * 新增干扰源用户
     *
     * @param loadTypeUserParam
     * @return
     */
    @Override
    public boolean addLoadTypeUser(LoadTypeUserParam loadTypeUserParam) {
        //参数转换
        RLoadTypeUserManage rLoadTypeUserManage = new RLoadTypeUserManage();
        BeanUtils.copyProperties(loadTypeUserParam, rLoadTypeUserManage);

        //塞入建档时间
        Date date = DateUtil.parse(loadTypeUserParam.getRecordTime(), "yyyy-MM-dd HH:mm:ss");
        rLoadTypeUserManage.setRecordTime(date);
        loadTypeUserManageMapper.insert(rLoadTypeUserManage);
        return true;
    }

    /**
     * 上传干扰源用户入网报告
     *
     * @param loadTypeUserIUploadParam
     * @return
     */
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public boolean uploadLoadTypeUserI(LoadTypeUserIUploadParam loadTypeUserIUploadParam) {

        RLoadTypeUserManage rLoadTypeUserManage = new RLoadTypeUserManage();
        BeanUtils.copyProperties(loadTypeUserIUploadParam, rLoadTypeUserManage);
        MultipartFile multipartFile = loadTypeUserIUploadParam.getFile();
        //文件上传到Minio服务器，存入文件名
        if (Objects.nonNull(multipartFile)) {
            rLoadTypeUserManage.setIFilePath(fileStorageUtil.uploadMultipart(multipartFile,OssPath.LOAD_TYPE_USER));
            rLoadTypeUserManage.setIUploadTime(new Date());
        }

        //提交：待审核/保存：新建
        DictData dictData;
        if (Objects.equals(Param.LOAD_TYPE_USER_SUBMIT, loadTypeUserIUploadParam.getStatus())) {
            dictData = dicDataFeignClient.getDicDataByCode(DicDataEnum.AUDIT.getCode()).getData();
        } else {
            dictData = dicDataFeignClient.getDicDataByCode(DicDataEnum.NEWLY.getCode()).getData();
        }
        rLoadTypeUserManage.setIStatus(dictData.getId());
        rLoadTypeUserManage.setIIsFileUpload(1);
        loadTypeUserManageMapper.updateById(rLoadTypeUserManage);

        return true;
    }

    /**
     * 关联营销用户
     *
     * @param
     * @return
     */
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public boolean linkUser(LoadTypeUserAssociateParam loadTypeUserAssociateParam) {
        RLoadTypeUserManage rLoadTypeUserManage = new RLoadTypeUserManage();
        //填入数据修改
        BeanUtils.copyProperties(loadTypeUserAssociateParam, rLoadTypeUserManage);
        loadTypeUserManageMapper.updateById(rLoadTypeUserManage);
        return true;
    }

    /**
     * 查询所有干扰源用户（与营销系统关联）
     *
     * @param loadTypeUserSearchParam
     * @return
     */
    @Override
    public Page<RLoadTypeUserManageVO> getLoadTypeRelationList(LoadTypeUserSearchParam loadTypeUserSearchParam) {
        Page<RLoadTypeUserManageVO> page = new Page<>(loadTypeUserSearchParam.getPageNum(), loadTypeUserSearchParam.getPageSize());
        Page<RLoadTypeUserManageVO> loadTypeUserPage = loadTypeUserManageMapper.getLoadTypeRelationPage(page, loadTypeUserSearchParam);

        //部门处理：根据部门code取名称
        List<RLoadTypeUserManageVO> list = loadTypeUserPage.getRecords();
        List<PvTerminalTreeVO> dept = deptFeignClient.allDeptList().getData();
        Map<String, PvTerminalTreeVO> pvTerminalTreeVOMap = dept.stream().collect(Collectors.toMap(PvTerminalTreeVO::getId, pvTerminalTreeVO -> pvTerminalTreeVO));
        List<RLoadTypeUserManageVO> resultList = list.stream().map(item -> {
            RLoadTypeUserManageVO rLoadTypeUserManageVO = new RLoadTypeUserManageVO();
            BeanUtils.copyProperties(item, rLoadTypeUserManageVO);
            rLoadTypeUserManageVO.setOrgName(pvTerminalTreeVOMap.get(item.getOrgNo()).getName()); //单位名称
            return rLoadTypeUserManageVO;
        }).collect(Collectors.toList());

        //返回新的数据组
        return loadTypeUserPage.setRecords(resultList);
    }



    /**
     * 上传干扰源用户入网报告
     *
     * @param loadTypeUserAUploadParam
     * @return
     */
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public boolean uploadLoadTypeUserA(LoadTypeUserAUploadParam loadTypeUserAUploadParam) {

        RLoadTypeUserManage rLoadTypeUserManage = new RLoadTypeUserManage();
        BeanUtils.copyProperties(loadTypeUserAUploadParam, rLoadTypeUserManage);
        MultipartFile multipartFile = loadTypeUserAUploadParam.getFile();
        //文件上传到文件服务器，存入文件名
        if (Objects.nonNull(multipartFile)) {
            rLoadTypeUserManage.setAFilePath(fileStorageUtil.uploadMultipart(multipartFile,OssPath.LOAD_TYPE_USER));
            rLoadTypeUserManage.setAUploadTime(new Date());
        }

        //提交：待审核/保存：新建
        DictData dictData;
        if (Objects.equals(Param.LOAD_TYPE_USER_SUBMIT, loadTypeUserAUploadParam.getStatus())) {
            dictData = dicDataFeignClient.getDicDataByCode(DicDataEnum.AUDIT.getCode()).getData();
        } else {
            dictData = dicDataFeignClient.getDicDataByCode(DicDataEnum.NEWLY.getCode()).getData();
        }
        rLoadTypeUserManage.setAStatus(dictData.getId());
        loadTypeUserManageMapper.updateById(rLoadTypeUserManage);

        return true;
    }

    /**
     * 导出未建档干扰源用户管理信息
     *
     * @param list
     * @return
     */
    @Override
    public List<LoadTypeUserExcel> exportLoadTypeUserList(List<String> list) {
        //数据处理
        LambdaQueryWrapper<RLoadTypeUserManage> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(RLoadTypeUserManage::getId, list);
        List<RLoadTypeUserManage> rLoadTypeUserManages = loadTypeUserManageMapper.selectList(queryWrapper);
        //1、部门数据
        List<PvTerminalTreeVO> dept = deptFeignClient.allDeptList().getData();
        Map<String, PvTerminalTreeVO> pvTerminalTreeVOMap = dept.stream().collect(Collectors.toMap(PvTerminalTreeVO::getId, pvTerminalTreeVO -> pvTerminalTreeVO));

        //2、取干扰源类型
        List<DictData> loadTypeList = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.MONITORING_LABELS.getCode()).getData();
        Map<String, DictData> loadTypeMap = loadTypeList.stream().collect(Collectors.toMap(DictData::getId, dictData -> dictData));

        //3、取入网报告状态
        List<DictData> iStatusList = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.ON_NETWORK_STATUS.getCode()).getData();
        Map<String, DictData> iStatusMap = iStatusList.stream().collect(Collectors.toMap(DictData::getId, dictData -> dictData));

        List<LoadTypeUserExcel> resultList = rLoadTypeUserManages.stream().map(item -> {
            LoadTypeUserExcel loadTypeUserExcel = new LoadTypeUserExcel();
            if (item.getUserName() != null) {
                loadTypeUserExcel.setUserName(item.getUserName());
            }
            if (item.getRecordTime() != null) {
                loadTypeUserExcel.setRecordTime(item.getRecordTime());
            }
            if (item.getAIsFileUpload() != null) {
                loadTypeUserExcel.setIIsFileUpload(item.getIIsFileUpload() == 0 ? "否" : "是"); //实测报告是否上传
            }
            if (item.getOrgNo() != null) {
                loadTypeUserExcel.setOrgName(pvTerminalTreeVOMap.get(item.getOrgNo()).getName()); //单位
            }
            if (item.getLoadType() != null) {
                loadTypeUserExcel.setLoadTypeName(loadTypeMap.get(item.getLoadType()).getName()); //入网报告状态
            }
            if (item.getIStatus() != null) {
                loadTypeUserExcel.setIStatusName(iStatusMap.get(item.getIStatus()).getName()); //入网报告状态
            }
            if (item.getAIsFileUpload() != null) {
                loadTypeUserExcel.setIIsFileUpload(item.getIIsFileUpload() == 0 ? "否" : "是"); //实测报告是否上传
            }
            return loadTypeUserExcel;
        }).collect(Collectors.toList());

        return resultList;
    }

    /**
     * 导出干扰源用户常态化管理信息
     *
     * @param list
     * @return
     */
    @Override
    public List<LoadTypeRelationExcel> exportLoadTypeRelationList(List<String> list) {
        //数据处理
        LambdaQueryWrapper<RLoadTypeUserManage> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(RLoadTypeUserManage::getId, list);
        List<RLoadTypeUserManage> rLoadTypeUserManages = loadTypeUserManageMapper.selectList(queryWrapper);
        //1、部门数据
        List<PvTerminalTreeVO> dept = deptFeignClient.allDeptList().getData();
        Map<String, PvTerminalTreeVO> pvTerminalTreeVOMap = dept.stream().collect(Collectors.toMap(PvTerminalTreeVO::getId, pvTerminalTreeVO -> pvTerminalTreeVO));

        //2、取干扰源类型
        List<DictData> loadTypeList = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.MONITORING_LABELS.getCode()).getData();
        Map<String, DictData> loadTypeMap = loadTypeList.stream().collect(Collectors.toMap(DictData::getId, dictData -> dictData));

        //3、取实测报告状态
        List<DictData> aStatusList = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.ON_NETWORK_STATUS.getCode()).getData();
        Map<String, DictData> aStatusMap = aStatusList.stream().collect(Collectors.toMap(DictData::getId, dictData -> dictData));

        List<LoadTypeRelationExcel> resultList = rLoadTypeUserManages.stream().map(item -> {
            LoadTypeRelationExcel loadTypeRelationExcel = new LoadTypeRelationExcel();
            if (item.getOrgNo() != null) {
                loadTypeRelationExcel.setOrgName(pvTerminalTreeVOMap.get(item.getOrgNo()).getName());
            }
            if (item.getLoadType() != null) {
                loadTypeRelationExcel.setLoadTypeName(loadTypeMap.get(item.getLoadType()).getName());
            }
            if (item.getUserName() != null) {
                loadTypeRelationExcel.setUserName(item.getUserName());
            }
            if (item.getRelationUserName() != null) {
                loadTypeRelationExcel.setRelationUserName(item.getRelationUserName());
            }
            if (item.getAStatus() != null) {
                loadTypeRelationExcel.setAStatusName(aStatusMap.get(item.getIStatus()).getName());
            }
            return loadTypeRelationExcel;
        }).collect(Collectors.toList());

        return resultList;
    }

    /**
     * @param loadTypeUserCheckParam
     * @Description: 入网评估报告审核
     * @Param: [loadTypeUserCheckParam]
     * @return: java.lang.Boolean
     * @Author: clam
     * @Date: 2023/2/22
     */
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public Boolean checkLoadTypeUserI(LoadTypeUserCheckParam loadTypeUserCheckParam) {
        boolean result = true;
        UpdateWrapper<RLoadTypeUserManage> updateWrapper = new UpdateWrapper();
        updateWrapper.eq("id", loadTypeUserCheckParam.getId());
        updateWrapper.set("i_check_comment", loadTypeUserCheckParam.getCheckComment());
        updateWrapper.set("i_check_person", loadTypeUserCheckParam.getCheckPerson());

        DictData fail = dicDataFeignClient.getDicDataByCode(DicDataEnum.FAIL.getCode()).getData();
        DictData finish = dicDataFeignClient.getDicDataByCode(DicDataEnum.SUCCESS.getCode()).getData();

        updateWrapper.set("i_status", Objects.equals("1", loadTypeUserCheckParam.getCheckResult()) ? finish.getId() : fail.getId());
        int i = loadTypeUserManageMapper.update(null, updateWrapper);
        result = i == 1;
        return result;
    }

    /**
     * @param loadTypeUserCheckParam
     * @Description: 实测报告审核
     * @Param: [loadTypeUserCheckParam]
     * @return: java.lang.Boolean
     * @Author: clam
     * @Date: 2023/2/22
     */
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public Boolean checkLoadTypeUserA(LoadTypeUserCheckParam loadTypeUserCheckParam) {
        boolean result = true;
        UpdateWrapper<RLoadTypeUserManage> updateWrapper = new UpdateWrapper();
        updateWrapper.eq("id", loadTypeUserCheckParam.getId());
        updateWrapper.set("a_check_comment", loadTypeUserCheckParam.getCheckComment());
        updateWrapper.set("a_check_person", loadTypeUserCheckParam.getCheckPerson());

        DictData fail = dicDataFeignClient.getDicDataByCode(DicDataEnum.FAIL.getCode()).getData();
        DictData finish = dicDataFeignClient.getDicDataByCode(DicDataEnum.SUCCESS.getCode()).getData();

        updateWrapper.set("a_status", Objects.equals("1", loadTypeUserCheckParam.getCheckResult()) ? finish.getId() : fail.getId());
        int i = loadTypeUserManageMapper.update(null, updateWrapper);
        result = i == 1;
        return result;
    }
}
