package com.njcn.process.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.jeffreyning.mybatisplus.service.MppServiceImpl;
import com.njcn.device.pms.api.PmsPowerDistributionareaClient;
import com.njcn.device.pms.pojo.param.PowerDistributionareaParam;
import com.njcn.device.pms.pojo.po.PowerDistributionarea;
import com.njcn.prepare.harmonic.pojo.dto.OverLimitFlagDTO;
import com.njcn.process.mapper.RStatDistributionProblemMapper;
import com.njcn.process.mapper.RStatWorkOrderDetailMapper;
import com.njcn.process.pojo.param.RStatProblemAndWorkOrderParam;
import com.njcn.process.pojo.po.RStatDistributionProblemPO;
import com.njcn.process.pojo.po.RStatWorkOrderDetailPO;
import com.njcn.process.pojo.vo.IssueesAndOrderVO;
import com.njcn.process.pojo.vo.OrderCountVO;
import com.njcn.process.pojo.vo.RStatDistributionProblemVO;
import com.njcn.process.pojo.vo.RStatWorkOrderDetailVO;
import com.njcn.process.service.RStatDistributionProblemService;
import com.njcn.system.enums.DicDataEnum;
import com.njcn.user.api.DeptFeignClient;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Description:
 * 接口文档访问地址：http://serverIP:port/swagger-ui.html
 * Date: 2023/2/1  14:17【需求编号】
 *
 * @author clam
 * @version V1.0.0
 */
@Service
@AllArgsConstructor
public class RStatDistributionProblemServiceImpl extends MppServiceImpl<RStatDistributionProblemMapper, RStatDistributionProblemPO> implements RStatDistributionProblemService {


    private final DeptFeignClient deptFeignClient;
    private final PmsPowerDistributionareaClient pmsPowerDistributionareaClient;

    private final RStatDistributionProblemMapper rStatDistributionProblemMapper;

    private final RStatWorkOrderDetailMapper rStatWorkOrderDetailMapper;

    /**
     * @param orgNo
     * @Description: 查询问题及工单（当前部门下）
     * @Param: [orgNo]
     * @return: com.njcn.process.pojo.vo.IssueesAndOrderVO
     * @Author: clam
     * @Date: 2023/2/2
     */
    @Override
    public IssueesAndOrderVO queryIssuesAndOrder(String orgNo) {
        IssueesAndOrderVO issueesAndOrderVO = new IssueesAndOrderVO ( );

        List<String> deptIds = deptFeignClient.getDepSonIdtByDeptId (orgNo).getData ( );
        /*问题个数*/
        QueryWrapper<RStatDistributionProblemPO> problemPOQueryWrapper = new QueryWrapper<> ( );
        problemPOQueryWrapper.select ("problem_no").
                in ("org_no", deptIds);
        List<RStatDistributionProblemPO> rStatDistributionProblemPOS = rStatDistributionProblemMapper.selectList (problemPOQueryWrapper);
        issueesAndOrderVO.setId (orgNo);
        issueesAndOrderVO.setIssueesCount (rStatDistributionProblemPOS.size ( ));
        List<String> problemNoList = rStatDistributionProblemPOS.stream ( ).map (RStatDistributionProblemPO::getProblemNo).collect (Collectors.toList ( ));
        if(CollectionUtils.isEmpty (problemNoList)){
            issueesAndOrderVO.setRelatedOrderCount (0);
        }else{
            /*已关联工单数量*/
            QueryWrapper<RStatWorkOrderDetailPO> workOrderDetailPOQueryWrapper = new QueryWrapper<> ( );
            workOrderDetailPOQueryWrapper.select ("1").
                    in ("problem_no", problemNoList).
                    in ("org_no", deptIds);
            Integer relatedOrderCount = rStatWorkOrderDetailMapper.selectCount (workOrderDetailPOQueryWrapper);
            issueesAndOrderVO.setRelatedOrderCount (relatedOrderCount);
        }

        return issueesAndOrderVO;
    }

    /**
     * @param orgNo
     * @Description: 查询工单及工单总数及完成工单数量（当前部门下）
     * @Param: [orgNo]
     * @return: com.njcn.process.pojo.vo.OrderCountVO
     * @Author: clam
     * @Date: 2023/2/2
     */
    @Override
    public OrderCountVO queryOrderCount(String orgNo) {
        OrderCountVO orderCountVO = new OrderCountVO ( );
        List<String> deptIds = deptFeignClient.getDepSonIdtByDeptId (orgNo).getData ( );
        /*工单数量*/
        QueryWrapper<RStatWorkOrderDetailPO> workOrderDetailPOQueryWrapper = new QueryWrapper<> ( );
        workOrderDetailPOQueryWrapper.
                in ("org_no", deptIds);
        List<RStatWorkOrderDetailPO> rStatWorkOrderDetailPOS = rStatWorkOrderDetailMapper.selectList (workOrderDetailPOQueryWrapper);
        orderCountVO.setId (orgNo);
        orderCountVO.setOrderCount (rStatWorkOrderDetailPOS.size ( ));
        /*已完成工单数量*/
        long count = rStatWorkOrderDetailPOS.stream ( ).filter (t -> Objects.equals (t.getWorkOrderStatus ( ), DicDataEnum.CLOSED.getCode ( ))).count ( );
        orderCountVO.setCompelteOrderCount (Integer.valueOf (count + ""));
        return orderCountVO;
    }

    /**
     * @param overLimitFlagDTOList
     * @Description: 创建问题接口
     * @Param: [overLimitFlagDTOList]
     * @return: java.lang.Boolean
     * @Author: clam
     * @Date: 2023/2/15
     */
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public Boolean createProblem(List<OverLimitFlagDTO> overLimitFlagDTOList) {
        List<RStatDistributionProblemPO> rStatDistributionProblemPOList = new ArrayList<> ( );
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyyMMdd");
        PowerDistributionareaParam powerDistributionareaParam = new PowerDistributionareaParam();
        List<PowerDistributionarea> data = pmsPowerDistributionareaClient.getPowerDistributionList (powerDistributionareaParam).getData ( );
        Map<String, PowerDistributionarea> collect = data.stream ( ).collect (Collectors.
                toMap (PowerDistributionarea::getId,
                        powerDistributionarea->powerDistributionarea));
        overLimitFlagDTOList.forEach (overLimitFlagDTO -> {
                    RStatDistributionProblemPO rStatDistributionProblemPO = new RStatDistributionProblemPO ( );
                    rStatDistributionProblemPO.setProblemNo (createproblemNo(overLimitFlagDTO.getOverLimtType (),overLimitFlagDTO.getStartTime ().format(fmt)));
                    rStatDistributionProblemPO.setOrgNo (collect.get(overLimitFlagDTO.getLineId ()).getOrgId ());
                    rStatDistributionProblemPO.setOrgName (collect.get(overLimitFlagDTO.getLineId ()).getOrgName ());
                    rStatDistributionProblemPO.setProblemType (overLimitFlagDTO.getOverLimtType ());
                    rStatDistributionProblemPO.setOccurTime (Date.from(overLimitFlagDTO.getStartTime ().atZone(ZoneId.systemDefault()).toInstant()));
                    rStatDistributionProblemPO.setLastTime (Date.from(overLimitFlagDTO.getEndTime ().atZone(ZoneId.systemDefault()).toInstant()));
                    rStatDistributionProblemPO.setCheckStatus (DicDataEnum.REVIEW.getCode ());
                    rStatDistributionProblemPO.setDistributionId (overLimitFlagDTO.getLineId ( ));
                    rStatDistributionProblemPO.setDistributionName (collect.get(overLimitFlagDTO.getLineId ()).getName ());
                    rStatDistributionProblemPO.setMeasurementPointId (overLimitFlagDTO.getLineId ( ));
                    rStatDistributionProblemPO.setProblemDescribe ("......");
            rStatDistributionProblemPOList.add (rStatDistributionProblemPO);
                }
        );
        boolean b = this.saveBatch (rStatDistributionProblemPOList);
        return b;
    }

    /**
     * @param rStatProblemAndWorkOrderParam
     * @Description: 查询问题接口
     * @Param: [rStatProblemAndWorkOrderParam]
     * @return: com.baomidou.mybatisplus.core.metadata.IPage<com.njcn.process.pojo.vo.RStatDistributionProblemVO>
     * @Author: clam
     * @Date: 2023/2/16
     */
    @Override
    public IPage<RStatDistributionProblemVO> queryProblem(RStatProblemAndWorkOrderParam rStatProblemAndWorkOrderParam) {
        IPage<RStatDistributionProblemPO> page = new Page<> (rStatProblemAndWorkOrderParam.getCurrentPage(), rStatProblemAndWorkOrderParam.getPageSize());
        IPage<RStatDistributionProblemVO> returnpage = new Page<> (rStatProblemAndWorkOrderParam.getCurrentPage(), rStatProblemAndWorkOrderParam.getPageSize());
        QueryWrapper<RStatDistributionProblemPO> queryWrapper = new QueryWrapper<> ();
        queryWrapper.eq (StrUtil.isNotBlank(rStatProblemAndWorkOrderParam.getProblemType ()),"problem_type",rStatProblemAndWorkOrderParam.getProblemType ()).
                eq (StrUtil.isNotBlank (rStatProblemAndWorkOrderParam.getCheckStatus ()),"check_status",rStatProblemAndWorkOrderParam.getCheckStatus ()).
                eq (StrUtil.isNotBlank (rStatProblemAndWorkOrderParam.getOccurTime ()),"DATE_FORMAT( occur_time ,'%Y-%m-%d')",rStatProblemAndWorkOrderParam.getOccurTime ()).
                like (StrUtil.isNotBlank (rStatProblemAndWorkOrderParam.getDistributionName ()), "distribution_name",rStatProblemAndWorkOrderParam.getDistributionName ());
        List<RStatDistributionProblemPO> records = rStatDistributionProblemMapper.selectPage (page, queryWrapper).getRecords ( );
        if(CollectionUtils.isEmpty (records)){
            return   returnpage;
        }
        List<RStatDistributionProblemVO> list = new ArrayList<> ();
        records.forEach (temp->{
            RStatDistributionProblemVO rStatDistributionProblemVO = new RStatDistributionProblemVO();
            BeanUtils.copyProperties (temp, rStatDistributionProblemVO);
            list.add (rStatDistributionProblemVO);
        });
        returnpage.setRecords (list);

        return returnpage;
    }

    /**
     * @param rStatDistributionProblemVO
     * @Description: 审核处理(更新问题表,生成工单表)
     * @Param: [rStatDistributionProblemVO]
     * @return: java.lang.Boolean
     * @Author: clam
     * @Date: 2023/2/17
     */
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public Boolean checkProblem(RStatDistributionProblemVO rStatDistributionProblemVO) {
        Boolean flag = true;
        RStatDistributionProblemPO rStatDistributionProblemPO = new RStatDistributionProblemPO();
        BeanUtils.copyProperties (rStatDistributionProblemVO, rStatDistributionProblemPO);
        flag = this.updateByMultiId (rStatDistributionProblemPO);
        if(!flag){
            return flag;
        }
        /*生成工单表*/
        if(Objects.equals (DicDataEnum.GENERATE.getCode (),rStatDistributionProblemPO.getCheckResult ())){
            /*处理台区信息*/
            PowerDistributionareaParam powerDistributionareaParam = new PowerDistributionareaParam();

            List<PowerDistributionarea> data = pmsPowerDistributionareaClient.getPowerDistributionList (powerDistributionareaParam).getData ( );
            Map<String, PowerDistributionarea> collect = data.stream ( ).collect (Collectors.
                    toMap (PowerDistributionarea::getId,
                            powerDistributionarea->powerDistributionarea));
            RStatWorkOrderDetailPO po = new RStatWorkOrderDetailPO();
            BeanUtils.copyProperties (rStatDistributionProblemVO, po);
            po.setProblemNo (rStatDistributionProblemVO.getProblemNo ());
            po.setWorkOrderStatus (DicDataEnum.PEND_DISPATCH.getCode ());
            po.setWorkOrderType (DicDataEnum.RECT_ORDER.getCode ());
            po.setPrimaryBusinessType (DicDataEnum.TRANS_BUSINESS.getCode ());
            po.setTwoBusinessType (rStatDistributionProblemVO.getProblemType ());
            po.setPowerSupplyStation (collect.get (rStatDistributionProblemVO.getDistributionId ()).getPowerStationId ());
            po.setWorkOrderProcess (DicDataEnum.GENERATED.getCode ());
            int insert = rStatWorkOrderDetailMapper.insert (po);
            if(!(insert==1)){
                flag=false;
            }
        }

        return flag;
    }

    /**
     * @param rStatProblemAndWorkOrderParam
     * @Description: queryWorkOrder
     * @Param: [rStatProblemAndWorkOrderParam]
     * @return: com.baomidou.mybatisplus.core.metadata.IPage<com.njcn.process.pojo.vo.RStatWorkOrderDetailVO>
     * @Author: clam
     * @Date: 2023/2/17
     */
    @Override
    public IPage<RStatWorkOrderDetailVO> queryWorkOrder(RStatProblemAndWorkOrderParam rStatProblemAndWorkOrderParam) {

//        IPage<RStatWorkOrderDetailPO> page = new Page<> (rStatProblemAndWorkOrderParam.getCurrentPage(), rStatProblemAndWorkOrderParam.getPageSize());
        Page<RStatWorkOrderDetailVO> returnpage = new Page<> (rStatProblemAndWorkOrderParam.getCurrentPage(), rStatProblemAndWorkOrderParam.getPageSize());
//        QueryWrapper<RStatWorkOrderDetailPO> queryWrapper = new QueryWrapper<> ();
//        queryWrapper.eq (StrUtil.isNotBlank(rStatProblemAndWorkOrderParam.getProblemType ()),"problem_type",rStatProblemAndWorkOrderParam.getProblemType ()).
//                eq (StrUtil.isNotBlank (rStatProblemAndWorkOrderParam.getOccurTime ()),"DATE_FORMAT( occur_time ,'%Y-%m-%d')",rStatProblemAndWorkOrderParam.getOccurTime ()).
//                eq (StrUtil.isNotBlank (rStatProblemAndWorkOrderParam.getWorkOrderStatus ()),"work_order_status",rStatProblemAndWorkOrderParam.getWorkOrderStatus ()).
//                eq (StrUtil.isNotBlank (rStatProblemAndWorkOrderParam.getProblemNo ()), "problem_no",rStatProblemAndWorkOrderParam.getProblemNo ());
         returnpage = rStatWorkOrderDetailMapper.getPageVo (returnpage ,rStatProblemAndWorkOrderParam);


//        List<RStatWorkOrderDetailVO> list = new ArrayList<> ();
//        records.forEach (temp->{
//            RStatWorkOrderDetailVO rStatWorkOrderDetailVO = new RStatWorkOrderDetailVO();
//            BeanUtils.copyProperties (temp, rStatWorkOrderDetailVO);
//            list.add (rStatWorkOrderDetailVO);
//        });
//        returnpage.setRecords (list);

        return returnpage;

    }

    /**
     * @param rStatWorkOrderDetailVO
     * @Description: 更新工单进度
     * @Param: [rStatWorkOrderDetailVO]
     * @return: java.lang.Boolean
     * @Author: clam
     * @Date: 2023/2/17
     */
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public Boolean updateWorkOrderStatus(RStatWorkOrderDetailVO rStatWorkOrderDetailVO) {
        Boolean flag= true;
        RStatWorkOrderDetailPO rStatWorkOrderDetailPO = new RStatWorkOrderDetailPO();
        BeanUtils.copyProperties (rStatWorkOrderDetailVO, rStatWorkOrderDetailPO);
        int i = rStatWorkOrderDetailMapper.updateByMultiId (rStatWorkOrderDetailPO);
        if(!(i==1)){
            flag=false;
        }
        return flag;
    }

    /**
    * @Description: 系统根据规则生成：
     * 县公司首字母缩写+“-”+问题首字母缩写+问题上报日期+5位随机数
     * 例如：萧山公司2022年9月1日的谐波电压越限问题，编号为：XS-DY2022090200001
     * 修改需求：问题首字母缩写+问题上报日期+8位随机数
    * @Param: [OrgName, problemShortName, date] 
    * @return: java.lang.String 
    * @Author: clam
    * @Date: 2023/2/15 
    */ 
    public String createproblemNo(String problemType,String date){

        /*生成8位随机数*/
        int i = (int) ((Math.random ( ) * 9 + 1) * 10000000);
        String problemShortName = "";
        if(Objects.equals (problemType,DicDataEnum.VOLTAGE_LIMIT.getCode ())){
            problemShortName = "DY";
        }else if(Objects.equals (problemType,DicDataEnum.CURRENT_LIMIT.getCode ())){
            problemShortName = "DL";
        }
        return problemShortName+date+i;
    }


}
