package com.njcn.device.pms.service.majornetwork.impl;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
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.PmsDeviceResponseEnum;
import com.njcn.device.pms.mapper.majornetwork.*;
import com.njcn.device.pms.mapper.majornetwork.PmsMidLedgerMapper;
import com.njcn.device.pms.pojo.dto.GeneratrixAndPowerStationDTO;
import com.njcn.device.pms.pojo.dto.GeneratrixAndPowerStationSonDTO;
import com.njcn.device.pms.pojo.dto.PmsGeneratrixDTO;
import com.njcn.device.pms.pojo.param.ConditionParam;
import com.njcn.device.pms.pojo.param.GeneratrixWireParam;
import com.njcn.device.pms.pojo.param.PmsBaseParam;
import com.njcn.device.pms.pojo.param.PmsGeneratrixParam;
import com.njcn.device.pms.pojo.po.GeneratrixWire;
import com.njcn.device.pms.pojo.po.Monitor;
import com.njcn.device.pms.pojo.po.PmsMidLedger;
import com.njcn.device.pms.pojo.po.StatationStat;
import com.njcn.device.pms.service.majornetwork.IGeneratrixWireService;
import com.njcn.device.pms.service.majornetwork.IStatationStatService;
import com.njcn.event.pojo.po.PmsMonitorPO;
import com.njcn.user.api.DeptFeignClient;
import com.njcn.web.factory.PageFactory;
import com.njcn.web.pojo.param.BaseParam;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * pms-device
 *
 * @author cdf
 * @date 2022/10/26
 */
@Service
@RequiredArgsConstructor
public class GeneratrixWireImpl extends ServiceImpl<PmsGeneratrixWireMapper, GeneratrixWire> implements IGeneratrixWireService {

    private final DeptFeignClient deptFeignClient;
    private final IStatationStatService statationStatService;

    private final PmsMidLedgerMapper pmsMidLedgerMapper;

    private final StatationStatMapper statationStatMapper;

    private final MonitorMapper monitorMapper;

    @Override
    public boolean addGeneratrixWire(GeneratrixWireParam generatrixWireParam) {
        checkName(generatrixWireParam, false);

        GeneratrixWire generatrixWire = new GeneratrixWire();
        BeanUtils.copyProperties(generatrixWireParam, generatrixWire);
        generatrixWire.setStatus(DataStateEnum.ENABLE.getCode());
        return this.save(generatrixWire);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateGeneratrixWire(GeneratrixWireParam generatrixWireParam) {
        checkName(generatrixWireParam, true);
        GeneratrixWire generatrixWireVa = this.getById(generatrixWireParam.getId());
        if (Objects.isNull(generatrixWireVa)) {
            throw new BusinessException(PmsDeviceResponseEnum.VOLTAGE_EMPTY);
        }

        if(!generatrixWireParam.getName().equals(generatrixWireVa.getName())){
            //名称变更需要同步修改其他台账表的母线测点名称
            LambdaUpdateWrapper<Monitor> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            lambdaUpdateWrapper.set(Monitor::getLineName,generatrixWireParam.getName())
                    .eq(Monitor::getLineId,generatrixWireVa.getId());
            monitorMapper.update(null,lambdaUpdateWrapper);
        }

        GeneratrixWire generatrixWire = new GeneratrixWire();
        BeanUtils.copyProperties(generatrixWireParam, generatrixWire);
        return this.updateById(generatrixWire);
    }

    @Override
    public boolean delGeneratrixWire(List<String> generatrixWireIds) {
        return this.removeByIds(generatrixWireIds);
    }

    @Override
    public GeneratrixWire getGeneratrixWireById(String generatrixWireId) {
        return this.getById(generatrixWireId);
    }

    @Override
    public List<GeneratrixWire> getGeneratrixWireList(PmsBaseParam pmsBaseParam) {
        LambdaQueryWrapper<GeneratrixWire> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotBlank(pmsBaseParam.getGeneratrixId())) {
            lambdaQueryWrapper.eq(GeneratrixWire::getId, pmsBaseParam.getGeneratrixId());
        }

        if (StrUtil.isNotBlank(pmsBaseParam.getStationId())) {
            lambdaQueryWrapper.eq(GeneratrixWire::getStationId, pmsBaseParam.getStationId());
        }
        lambdaQueryWrapper.eq(GeneratrixWire::getStatus, DataStateEnum.ENABLE.getCode())
                .orderByAsc(GeneratrixWire::getCreateTime);
        return this.list(lambdaQueryWrapper);
    }

    @Override
    public Page<GeneratrixWire> getGeneratrixWirePageList(BaseParam baseParam) {
        LambdaQueryWrapper<GeneratrixWire> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(GeneratrixWire::getStatus, DataStateEnum.ENABLE.getCode())
                .and(StrUtil.isNotBlank(baseParam.getSearchValue()), i -> i.like(StrUtil.isNotBlank(baseParam.getSearchValue()), GeneratrixWire::getGeneratrixName, baseParam.getSearchValue())
                        .or(StrUtil.isNotBlank(baseParam.getSearchValue()))
                        .like(StrUtil.isNotBlank(baseParam.getSearchValue()), GeneratrixWire::getName, baseParam.getSearchValue())
                        .or(StrUtil.isNotBlank(baseParam.getSearchValue()))
                        .like(StrUtil.isNotBlank(baseParam.getSearchValue()), GeneratrixWire::getStationName, baseParam.getSearchValue()))
                .orderByDesc(GeneratrixWire::getUpdateTime);
        Page<GeneratrixWire> page = this.page(new Page<>(PageFactory.getPageNum(baseParam), PageFactory.getPageSize(baseParam)), lambdaQueryWrapper);
        List<GeneratrixWire> records = page.getRecords();
        if(CollUtil.isNotEmpty(records)){
            List<String> midIds = records.stream().map(GeneratrixWire::getMidBusId).collect(Collectors.toList());
            List<PmsMidLedger> pmsMidLedgers = pmsMidLedgerMapper.selectList(new LambdaQueryWrapper<PmsMidLedger>()
                    .in(PmsMidLedger::getId, midIds)
            );
            if(CollUtil.isNotEmpty(pmsMidLedgers)){
                Map<String, String> midMap = pmsMidLedgers.stream().collect(Collectors.toMap(PmsMidLedger::getId, PmsMidLedger::getName));
                for (GeneratrixWire record : records) {
                    if(midMap.containsKey(record.getMidBusId())){
                        record.setMidBusName(midMap.get(record.getMidBusId()));
                    }
                }
            }
        }
        return page;
    }


    private void checkName(GeneratrixWireParam generatrixWireParam, Boolean updateFlag) {
        LambdaQueryWrapper<GeneratrixWire> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(GeneratrixWire::getName, generatrixWireParam.getName())
                .eq(GeneratrixWire::getStationId, generatrixWireParam.getStationId())
                .eq(GeneratrixWire::getStatus, DataStateEnum.ENABLE.getCode());

        if (updateFlag) {
            //更新
            lambdaQueryWrapper.ne(GeneratrixWire::getId, generatrixWireParam.getId());
        } else {
            //新增校验
            if (StrUtil.isNotBlank(generatrixWireParam.getId())) {
                LambdaQueryWrapper<GeneratrixWire> lambdaQuery = new LambdaQueryWrapper<>();
                lambdaQuery.eq(GeneratrixWire::getId, generatrixWireParam.getId());
                int count = this.count(lambdaQuery);
                if (count > 0) {
                    throw new BusinessException(PmsDeviceResponseEnum.WIRE_SAME);

                }
            }
        }
        int count = this.count(lambdaQueryWrapper);
        if (count > 0) {
            throw new BusinessException(PmsDeviceResponseEnum.GENERATRIXWIRE_NAME_REPEAT);
        }
    }

    /**
     * 获取母线信息
     *
     * @param param 入参
     * @return 母线信息
     */
    @Override
    public List<PmsGeneratrixDTO> getGeneratrixInfo(PmsGeneratrixParam param) {
        if (CollUtil.isEmpty(param.getGeneratrixIds())) {
            return null;
        }
        return this.baseMapper.getGeneratrixInfo(param);
    }

    /**
     * 获取母线与电站关联信息
     *
     * @param param 条件参数
     * @return java.util.List<com.njcn.device.pms.pojo.dto.PmsGeneratrixDTO>
     * @author yzh
     * @date 2022/11/3
     */
    @Override
    public List<GeneratrixAndPowerStationDTO> getGeneratrixAndPowerStationInfo(PmsGeneratrixParam param) {
        return this.baseMapper.getGeneratrixAndPowerStationInfo(param);
    }

    /**
     * @param param
     * @Description: 普测计划页面调用根据条件查询母线信息
     * @Param: [param]
     * @return: java.util.List<com.njcn.device.pms.pojo.dto.GeneratrixAndPowerStationDTO>
     * @Author: clam
     * @Date: 2022/12/5
     */
    @Override
    public List<GeneratrixAndPowerStationSonDTO> getGeneratrixByCondition(ConditionParam param) {

        List<String> data = deptFeignClient.getDepSonSelfCodetByDeptId(param.getDeptId()).getData();

        return this.baseMapper.getGeneratrixByCondition(data, param);
    }

    @Override
    public List<PmsMidLedger> getBusBar(String stationId) {
        StatationStat stationStat = statationStatService.getStatationStatById(stationId);
        if(ObjectUtil.isNotNull(stationStat)){
            if(StrUtil.isNotBlank(stationStat.getMidStationId())){
               return pmsMidLedgerMapper.selectList(new LambdaQueryWrapper<PmsMidLedger>()
                        .eq(PmsMidLedger::getPid, stationStat.getMidStationId())
                );
            }
        }
        return new ArrayList<>();
    }

    @Override
    public Boolean batchSync() {
        List<GeneratrixWire> poList = new ArrayList<>();

        List<StatationStat> statationStatList = statationStatMapper.selectList(new LambdaQueryWrapper<StatationStat>().isNotNull(StatationStat::getMidStationId));
        List<String> ids = statationStatList.stream().map(StatationStat::getPowerId).distinct().collect(Collectors.toList());
        List<GeneratrixWire> generatrixWireList = this.list(new LambdaQueryWrapper<GeneratrixWire>().in(GeneratrixWire::getStationId, ids)
                .isNull(GeneratrixWire::getMidBusId));

        for (StatationStat statationStat : statationStatList) {

            if(statationStat.getPowerId().equals("3e214ecf89405c639515a1e71a0f9126")){
                System.out.println("5555");
            }

            LambdaQueryWrapper<PmsMidLedger> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(PmsMidLedger::getLevel, 1).eq(PmsMidLedger::getState, DataStateEnum.ENABLE.getCode()).in(PmsMidLedger::getPid, statationStat.getMidStationId());
            List<PmsMidLedger> pmsMidLedgerList = pmsMidLedgerMapper.selectList(lambdaQueryWrapper);
            if (CollUtil.isEmpty(pmsMidLedgerList)) {
                continue;
            }

            List<GeneratrixWire> gg = generatrixWireList.stream().filter(item -> item.getStationId().equals(statationStat.getPowerId())).collect(Collectors.toList());

            if (CollUtil.isEmpty(gg)) {
                continue;
            }

            for (GeneratrixWire generatrixWire : gg) {

                for (PmsMidLedger pmsMidLedger : pmsMidLedgerList) {
                    String tem = generatrixWire.getName().replace("#", "号");
                    if (tem.equals(pmsMidLedger.getName())) {
                        generatrixWire.setMidBusId(pmsMidLedger.getId());
                        break;
                    }

                 /*   String tem1 = generatrixWire.getName().replace(" II母","2号母线").replace(" Ⅱ母", "2号母线").replace("Ⅱ母", "2号母线")
                            .replace(" Ⅲ母", "三号母线").replace(" III母", "三号母线").replace("Ⅲ母", "三号母线").replace(" IV母", "4号母线").replace("IV母", "4号母线").replace("IV母", "4号母线").replace(" V母", "5号母线")
                            .replace("V母", "5号母线")
                            .replace(" VI母", "6号母线").replace("VI母", "6号母线").replace(" VⅡ母", "7号母线").replace("VⅡ母", "7号母线");
                  */
                  /*  String tem1 = generatrixWire.getName().replace("II母","2段母线").replace(" Ⅱ母", "2段母线").replace("Ⅱ母", "2段母线")
                            .replace(" Ⅲ母", "三号母线").replace("III母", "三段母线").replace("Ⅲ母", "三段母线").replace(" IV母", "4段母线").replace("IV母", "4段母线").replace("IV母", "4段母线").replace(" V母", "5段母线")
                            .replace("V母", "5号母线")
                            .replace(" VI母", "6段母线").replace("VI母", "6段母线").replace(" VⅡ母", "7段母线").replace("VⅡ母", "7段母线");
*/

                    String tem1 = generatrixWire.getName().replace("1#母线","1号母线");

                    if (tem1.equals(pmsMidLedger.getName())) {
                        generatrixWire.setMidBusId(pmsMidLedger.getId());
                        break;
                    }


                }

                if (StrUtil.isNotBlank(generatrixWire.getMidBusId())) {
                    poList.add(generatrixWire);
                }
            }


            System.out.println("5555");




        }
        for (GeneratrixWire generatrixWire : poList) {
            LambdaUpdateWrapper<GeneratrixWire> lambdaUpdateWrapper = new LambdaUpdateWrapper();
            lambdaUpdateWrapper.set(GeneratrixWire::getMidBusId, generatrixWire.getMidBusId()).eq(GeneratrixWire::getId, generatrixWire.getId());
            this.update(lambdaUpdateWrapper);
        }
        return true;
    }

}
