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

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
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.StatationStatMapper;
import com.njcn.device.pms.mapper.majornetwork.TerminalMapper;
import com.njcn.device.pms.pojo.param.PmsBaseParam;
import com.njcn.device.pms.pojo.param.PmsTerminalParam;
import com.njcn.device.pms.pojo.param.TerminalQueryParam;
import com.njcn.device.pms.pojo.po.DistributionMonitor;
import com.njcn.device.pms.pojo.po.Monitor;
import com.njcn.device.pms.pojo.po.PmsTerminal;
import com.njcn.device.pms.pojo.po.StatationStat;
import com.njcn.device.pms.service.majornetwork.IDistributionMonitorService;
import com.njcn.device.pms.service.majornetwork.IMonitorService;
import com.njcn.device.pms.service.majornetwork.IStatationStatService;
import com.njcn.device.pms.service.majornetwork.ITerminalService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.system.api.DicDataFeignClient;
import com.njcn.user.api.DeptFeignClient;
import com.njcn.user.pojo.po.Dept;
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 java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 *  监测终端台账
 * </p>
 *
 * @author hongawen
 * @since 2022-10-14
 */
@Service
@RequiredArgsConstructor
public class TerminalServiceImpl extends ServiceImpl<TerminalMapper, PmsTerminal> implements ITerminalService {

    private final DeptFeignClient deptFeignClient;

    private final IStatationStatService iStatationStatService;

    private final DicDataFeignClient dicDataFeignClient;

    private final IMonitorService iMonitorService;

    private final IDistributionMonitorService iDistributionMonitorService;

    @Override
    public Page<PmsTerminal> getTerminalList(TerminalQueryParam baseParam) {

        List<String> orgIds = new ArrayList<>();
        if(StrUtil.isNotBlank(baseParam.getOrgId())){
            orgIds.addAll(deptFeignClient.getDepSonSelfCodetByDeptId(baseParam.getOrgId()).getData());
        }

        LambdaQueryWrapper<PmsTerminal> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(PmsTerminal::getStatus,DataStateEnum.ENABLE.getCode())
                .in(CollUtil.isNotEmpty(orgIds),PmsTerminal::getOrgId,orgIds)
                .eq(StrUtil.isNotBlank(baseParam.getDeviceCategory()),PmsTerminal::getDeviceCategory,baseParam.getDeviceCategory());
                if(StrUtil.isNotBlank(baseParam.getSearchValue())) {
                    lambdaQueryWrapper.and(i -> i.like(PmsTerminal::getName, baseParam.getSearchValue())
                            .or()
                            .like(PmsTerminal::getOrgName, baseParam.getSearchValue())
                            .or()
                            .like(PmsTerminal::getPowerrName, baseParam.getSearchValue()));
                }
        lambdaQueryWrapper.orderByAsc(PmsTerminal::getOrgName,PmsTerminal::getName);
        //初始化分页数据
        return this.page(new Page<>(PageFactory.getPageNum(baseParam), PageFactory.getPageSize(baseParam)), lambdaQueryWrapper);
    }

    @Override
    public List<PmsTerminal> getTerminalSelectList(PmsBaseParam pmsBaseParam) {
        LambdaQueryWrapper<PmsTerminal> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.select(PmsTerminal::getName,PmsTerminal::getOrgId,PmsTerminal::getOrgName,PmsTerminal::getId,PmsTerminal::getPowerrName);
        lambdaQueryWrapper.eq(PmsTerminal::getStatus,DataStateEnum.ENABLE.getCode())
                .orderByDesc(PmsTerminal::getCreateTime);
        if(StrUtil.isNotBlank(pmsBaseParam.getDeptId())){
            List<String> deptCodes = deptFeignClient.getDepSonSelfCodetByDeptId(pmsBaseParam.getDeptId()).getData();
            lambdaQueryWrapper.in(PmsTerminal::getOrgId,deptCodes);
        }

        if(StrUtil.isNotBlank(pmsBaseParam.getDeptCode())){
            List<String> deptCodes = deptFeignClient.getDepSonSelfCodetByCode(pmsBaseParam.getDeptCode()).getData();
            lambdaQueryWrapper.in(PmsTerminal::getOrgId,deptCodes);
        }

        if(StrUtil.isNotBlank(pmsBaseParam.getStationId())){
            lambdaQueryWrapper.eq(PmsTerminal::getPowerStationId,pmsBaseParam.getStationId());
        }
        return this.list(lambdaQueryWrapper);
    }

    @Override
    public List<PmsTerminal> getTerminalSelectByIds(List<String> ids) {
        return this.list(new LambdaQueryWrapper<PmsTerminal>()
                .in(CollUtil.isNotEmpty(ids),PmsTerminal::getId,ids)
                .eq(PmsTerminal::getStatus,DataStateEnum.ENABLE.getCode())
        );
    }

    /**
     * 根据id查询
     * @author hany
     * @date 2022/10/27
     */
    @Override
    public PmsTerminal getTerminalById(String id) {
        return this.getById(id);
    }

    /**
     * 新增监测终端台账
     * @author hany
     * @date 2022/10/27
     */
    @Override
    public boolean add(PmsTerminalParam terminalParam) {
        checkName(terminalParam,true);

        Dept dept = deptFeignClient.getDeptByCode(terminalParam.getOrgId()).getData();
        if(Objects.isNull(dept)){
            throw new BusinessException(PmsDeviceResponseEnum.ORG_ITEM_EMPTY);
        }

        Dept opDept = deptFeignClient.getDeptByCode(terminalParam.getOperationId()).getData();
        if(Objects.isNull(opDept)){
            throw new BusinessException(PmsDeviceResponseEnum.Operation_ITEM_EMPTY);
        }

        StatationStat statationStat = iStatationStatService.getStatationStatById(terminalParam.getPowerStationId());
        if(Objects.isNull(statationStat)){
            throw new BusinessException(PmsDeviceResponseEnum.NO_STATION);
        }


        PmsTerminal pmsTerminal = new PmsTerminal();
        BeanUtils.copyProperties(terminalParam, pmsTerminal);

        pmsTerminal.setOrgName(dept.getName());
        pmsTerminal.setOperationName(opDept.getName());
        pmsTerminal.setPowerrName(statationStat.getPowerName());
        //设为正常状态
        pmsTerminal.setStatus(DataStateEnum.ENABLE.getCode());
        pmsTerminal.setVerificationDate(LocalDate.parse(terminalParam.getVerificationDate()));
        pmsTerminal.setUseDate(LocalDate.parse(terminalParam.getUseDate()));
        pmsTerminal.setUpdateTime(LocalDateTime.now());
        return this.save(pmsTerminal);
    }

    /**
     * 修改监测终端台账
     * @author hany
     * @date 2022/10/27
     */
    @Override
    public boolean update(PmsTerminalParam updateParam) {
        checkName(updateParam,false);
        PmsTerminal pmsTerminal = new PmsTerminal();
        BeanUtils.copyProperties(updateParam, pmsTerminal);
        pmsTerminal.setVerificationDate(LocalDate.parse(updateParam.getVerificationDate()));
        pmsTerminal.setUseDate(LocalDate.parse(updateParam.getUseDate()));
        return this.updateById(pmsTerminal);
    }

    /**
     * 删除
     * @param ids
     */
    @Override
    public boolean delete(List<String> ids) {
        //删除前需要判断依赖终端的监测点是否存在
        LambdaQueryWrapper<Monitor> monitorLambdaQueryWrapper = new LambdaQueryWrapper<>();
        monitorLambdaQueryWrapper.in(Monitor::getTerminalId,ids).eq(Monitor::getStatus,DataStateEnum.ENABLE.getCode());
        int mCount = iMonitorService.count(monitorLambdaQueryWrapper);
        if(mCount>0){
            throw new BusinessException(PmsDeviceResponseEnum.MONITOR_BIND_FIND);
        }

        LambdaQueryWrapper<DistributionMonitor> distributionMonitorLambdaQueryWrapper = new LambdaQueryWrapper<>();
        distributionMonitorLambdaQueryWrapper.in(DistributionMonitor::getTerminalId,ids).eq(DistributionMonitor::getStatus,DataStateEnum.ENABLE.getCode());
        int dCount = iDistributionMonitorService.count(distributionMonitorLambdaQueryWrapper);
        if(dCount>0){
            throw new BusinessException(PmsDeviceResponseEnum.DIS_MONITOR_BIND_FIND);
        }

        return this.lambdaUpdate().set(PmsTerminal::getStatus, DataStateEnum.DELETED.getCode()).in(PmsTerminal::getId, ids).update();
    }

    /**
     * 名称重复校验
     */
    private void checkName(PmsTerminalParam terminalParam, boolean flag){
        LambdaQueryWrapper<PmsTerminal> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(PmsTerminal::getName,terminalParam.getName()).eq(PmsTerminal::getPowerStationId,terminalParam.getPowerStationId());
        //修改
        if(!flag){
            lambdaQueryWrapper.ne(PmsTerminal::getId,terminalParam.getId());
        }else {
            //新增添加索引校验
            LambdaQueryWrapper<PmsTerminal> lamb = new LambdaQueryWrapper<>();
            lamb.eq(PmsTerminal::getId,terminalParam.getId());
            int result = this.count(lamb);
            //大于等于1个则表示重复
            if (result >= 1) {
                throw new BusinessException(PmsDeviceResponseEnum.TERMINAL_ID_REPEAT);
            }
        }
        int result = this.count(lambdaQueryWrapper);
        //大于等于1个则表示重复
        if (result >= 1) {
            throw new BusinessException(PmsDeviceResponseEnum.MODEL_NAME_REPEAT);
        }

    }
}
