package cn.cecep.talroad.service.impl;

import cn.cecep.talroad.common.core.utils.DateUtils;
import cn.cecep.talroad.domain.BasDevice;
import cn.cecep.talroad.domain.BasDeviceInfoOperationLog;
import cn.cecep.talroad.enums.BasDeviceTypeEnum;
import cn.cecep.talroad.enums.OperationTypeEnum;
import cn.cecep.talroad.mapper.BasDeviceInfoOperationLogMapper;
import cn.cecep.talroad.mapper.FacilityInformationManagementMapper;
import cn.cecep.talroad.service.FacilityInformationManagementService;
import cn.cecep.talroad.system.api.domain.SysUser;
import cn.cecep.talroad.vo.FacilityInformationManagementVO;
import cn.cecep.talroad.vo.query.FacilityInformationQuery;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @className: FacilityInformationManagementServiceImpl
 * @description: TODO 类描述
 * @author: Mr.Yanghongtao
 * @date: 2023/04/28 11:20
 * @Company: Copyright© [2023/04/28 11:20] by [Mr.Yanghongtao]
 **/
@Service
public class FacilityInformationManagementServiceImpl implements FacilityInformationManagementService {

    @Autowired
    private FacilityInformationManagementMapper facilityInformationManagementMapper;

    @Autowired
    private BasDeviceInfoOperationLogMapper basDeviceInfoOperationLogMapper;

    /**
     * @Author: Mr.Yanghongtao
     * @data: 2023/4/28 12:28
     * @Deseription: 分表计电生产设施匹配列表
     * @Params: dto
     * @Return: com.baomidou.mybatisplus.core.metadata.IPage<cn.cecep.talroad.vo.FacilityInformationManagementVO>
     * @Throws:
     */
    @Override
    public IPage<FacilityInformationManagementVO> getProductionDeviceList(FacilityInformationQuery dto) {
        Page<FacilityInformationManagementVO> page = new Page<>(dto.getPageNum(), dto.getPageSize());
        List<FacilityInformationManagementVO> facilityInformationManagementVOS = facilityInformationManagementMapper.selectFacilityInformationManagementListByParams(page, dto);
        page.setRecords(facilityInformationManagementVOS);
        return page;
    }


    /**
     * @Author: Mr.Yanghongtao
     * @data: 2023/4/28 12:30
     * @Deseription: 查询排污许可设施列表
     * @Params: factoryId
     * @Params: deviceType
     * @Return: java.util.List<cn.cecep.talroad.domain.BasDevice>
     * @Throws:
     */
    @Override
    public List<BasDevice> getPollutantDeviceList(String factoryId, Integer deviceType) {
        return facilityInformationManagementMapper.selectPollutantDeviceList(factoryId, BasDeviceTypeEnum.PW_PWXK.getCode(), deviceType);
    }


    /**
     * @Author: Mr.Yanghongtao
     * @data: 2023/4/28 13:38
     * @Deseription: 保存
     * @Params: dto
     * @Return:
     * @Throws:
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void modifyDeviceAndPollutantCodeList(SysUser sysUser, List<FacilityInformationQuery> dto, String type) {
        dto.forEach(x->x.setPollutantCodeOne(x.getPollutantCode().split(",")[0]));
        // 获取本次要修改的所有设施ID
        List<String> deviceIds = dto.stream().map(FacilityInformationQuery::getDeviceId).collect(Collectors.toList());
        Map<String, FacilityInformationQuery> after = dto.stream().collect(Collectors.toMap(FacilityInformationQuery::getDeviceId, Function.identity()));

        // 查询要更改的设施之前的信息
        List<FacilityInformationManagementVO> facilityInformationManagementVOS = facilityInformationManagementMapper.selectFacilityInformationManagementListByParams(new Page<>(1, Integer.MAX_VALUE), new FacilityInformationQuery(sysUser.getFactoryId(),deviceIds));
        // key为设施ID
        Map<String, FacilityInformationManagementVO> before = facilityInformationManagementVOS.stream().collect(Collectors.toMap(FacilityInformationManagementVO::getDeviceId, Function.identity()));
        Date date = new Date();
        List<BasDeviceInfoOperationLog> insertLogs = new ArrayList<>();
        // 查询未更新前的信息，存入操作日志表
        before.forEach((k, v) -> {
            BasDeviceInfoOperationLog log = new BasDeviceInfoOperationLog();
            log.setLogId(UUID.randomUUID().toString().trim().replaceAll("-", ""));
            log.setOperationTime(DateUtils.parseFormatDate("yyyy-MM-dd HH:mm:ss",date));
            // 分表计电设施名称
            log.setElecDeviceName(v.getDeviceName());
            // 修改前对应许可证生产设施名称
            log.setBeforeModifyName(v.getPollutantName());
            // 修改前对应许可证生产设施编号
            log.setBeforeModifyCode(v.getPollutantCode());
            // 操作状态
            log.setOperationStatus(getOperationStatus(v.getPollutantName(),after.get(k).getPollutantName()));
            // 修改后对应许可证生产设施编号
            log.setAfterModifyCode(after.get(k).getPollutantCode());
            // 修改后对应许可证生产设施名称
            log.setAfterModifyName(after.get(k).getPollutantName());
            // 操作人
            log.setOperator(sysUser.getNickName());
            // 操作人ID
            log.setOperatorId(String.valueOf(sysUser.getUserId()));
            // 1-分表计电生产设施匹配｜2-分表计电治理设施匹配｜3-DCS生产设施点位匹配
            log.setMonitoringPointType(type);
            // 企业ID
            log.setFactoryId(sysUser.getFactoryId());
            insertLogs.add(log);
        });
        // 批量更新bas_device表
        facilityInformationManagementMapper.updateDeviceAndPollutantCodeList(dto);
        // 批量插入日志表
        basDeviceInfoOperationLogMapper.batchInsert(insertLogs);

    }

    /**
     * @Author: Mr.Yanghongtao
     * @data: 2023/5/5 22:32
     * @Deseription: 获取操作状态
     * @Params: null
     * @Return:
     * @Throws:
     */
    private String getOperationStatus(String before, String after) {
        // 之前不存在，本次存在，新增
        if (StringUtils.isEmpty(before)) {
            if (StringUtils.isNotEmpty(after)) {
                return OperationTypeEnum.INSERT_OPERATION.getName();
            } else {
                return "-";
            }
        } else {
            // 之前存在，本次存在，修改
            if (StringUtils.isNotEmpty(after)) {
                return OperationTypeEnum.UPDATE_OPERATION.getName();
            } else {
                // 之前存在，本次不存在， 取消对应关系
                return OperationTypeEnum.CANCEL_THE_CORRESPONDENCE.getName();
            }
        }
    }

    /**
     * @param dto
     * @Author: Mr.Yanghongtao
     * @data: 2023/4/28 15:08
     * @Deseription: 查询日志
     * @Params: null
     * @Return:
     * @Throws:
     */
    @Override
    public IPage<BasDeviceInfoOperationLog> getBasDeviceInfoOperationLogList(FacilityInformationQuery dto) {
        Page<BasDeviceInfoOperationLog> page = new Page<>(dto.getPageNum(), dto.getPageSize());
        List<BasDeviceInfoOperationLog> list = basDeviceInfoOperationLogMapper.selectListByParam(page, dto,
                StringUtils.isEmpty(dto.getStartTime()) ? null : Timestamp.valueOf(dto.getStartTime()),
                StringUtils.isEmpty(dto.getEndTime()) ? null : Timestamp.valueOf(dto.getEndTime()));
        page.setRecords(list);
        return page;
    }

    /**
     * @Author: Mr.Yanghongtao
     * @data: 2023/4/28 15:36
     * @Deseription: 取消对应关系
     * @Params: dto
     * @Return:
     * @Throws:
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void cancelDeviceAndPollutantCodeList(SysUser sysUser, FacilityInformationQuery dto,String type) {
        // 更新设备表
        facilityInformationManagementMapper.cancelDeviceAndPollutantCodeList(Arrays.asList(dto));

        BasDeviceInfoOperationLog log = new BasDeviceInfoOperationLog();
        log.setLogId(UUID.randomUUID().toString().trim().replaceAll("-", ""));
        log.setOperationTime(DateUtils.parseFormatDate("yyyy-MM-dd HH:mm:ss",new Date()));
        // 分表计电设施名称
        log.setElecDeviceName(dto.getDeviceName());
        // 修改前对应许可证生产设施名称
        log.setBeforeModifyName(dto.getPollutantName());
        // 修改前对应许可证生产设施编号
        log.setBeforeModifyCode(dto.getPollutantCode());
        // 操作状态
        log.setOperationStatus(OperationTypeEnum.CANCEL_THE_CORRESPONDENCE.getName());
        // 修改后对应许可证生产设施编号
        log.setAfterModifyCode(null);
        // 修改后对应许可证生产设施名称
        log.setAfterModifyName(null);
        // 操作人
        log.setOperator(sysUser.getNickName());
        // 操作人ID
        log.setOperatorId(String.valueOf(sysUser.getUserId()));
        // 1-分表计电生产设施匹配｜2-分表计电治理设施匹配｜3-DCS生产设施点位匹配
        log.setMonitoringPointType(type);
        // 企业ID
        log.setFactoryId(dto.getFactoryId());
        basDeviceInfoOperationLogMapper.insertSelective(log);
    }

    /**
     * @param factoryId
     * @param queryType
     * @Author: Mr.Yanghongtao
     * @data: 2023/4/30 14:51
     * @Deseription:
     * @Params: null
     * @Return:
     * @Throws:
     */
    @Override
    public List<FacilityInformationManagementVO> getProductionDeviceSearchList(String factoryId, String queryType) {
        List<FacilityInformationManagementVO> facilityInformationManagementVOS = facilityInformationManagementMapper.selectFacilityInformationManagementSearchListByParams( factoryId,queryType);
        return facilityInformationManagementVOS;
    }
}
