package com.njcn.device.pms.controller.ledgerManger;


import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.njcn.common.pojo.annotation.OperateInfo;
import com.njcn.common.pojo.constant.OperateType;
import com.njcn.common.pojo.enums.common.DataStateEnum;
import com.njcn.common.pojo.enums.common.LogEnum;
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.pojo.response.HttpResult;
import com.njcn.common.utils.HttpResultUtil;
import com.njcn.device.pms.annotation.TerminalOperationLogDesc;
import com.njcn.device.pms.pojo.dto.PmsDistributionMonitorDTO;
import com.njcn.device.pms.pojo.dto.PwPmsMonitorDTO;
import com.njcn.device.pms.pojo.param.DistributionMonitorParam;
import com.njcn.device.pms.pojo.param.MonitorStatus;
import com.njcn.device.pms.pojo.param.TaiZhangDelParam;
import com.njcn.device.pms.pojo.param.pwUser.PwUserMonitorParam;
import com.njcn.device.pms.pojo.po.DistributionMonitor;
import com.njcn.device.pms.pojo.po.TerminalLog;
import com.njcn.device.pms.pojo.vo.DoubleUserVO;
import com.njcn.device.pms.pojo.vo.pwUser.PwUserMonitorDataVO;
import com.njcn.device.pms.service.majornetwork.IDistributionMonitorService;
import com.njcn.device.pms.service.majornetwork.ITerminalLogService;
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.web.utils.RequestUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import com.njcn.web.controller.BaseController;

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

/**
 * <p>
 *  配网监测点台账
 * </p>
 *
 * @author hongawen
 * @since 2022-10-14
 */
@RestController
@RequestMapping("/pms/distributionMonitor")
@Slf4j
@RequiredArgsConstructor
@Api(tags = "台账-配网监测点")
public class PmsDistributionMonitorController extends BaseController {

    private final IDistributionMonitorService iDistributionMonitorService;

    private final ITerminalLogService iTerminalLogService;


    /**
     * 新增配网监测点表
     * @author cdf
     * @date 2022/10/26
     */
    @PostMapping("addDistributionMonitor")
    @ApiImplicitParam(name = "distributionMonitorParam",value = "配网监测点实体",required = true)
    @OperateInfo(info = LogEnum.BUSINESS_COMMON,operateType = OperateType.ADD)
    @ApiOperation("新增配网监测点")
    @TerminalOperationLogDesc(value = "新增配网监测点",module = 7)
    public HttpResult<Boolean> addDistributionMonitor(@RequestBody @Validated DistributionMonitorParam distributionMonitorParam){
        String methodDescribe = getMethodDescribe("addDistributionMonitor");
        boolean res= iDistributionMonitorService.addDistributionMonitor(distributionMonitorParam);
        if(res){
            return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
        }else {
            return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.FAIL, null, methodDescribe);
        }
    }


    /**
     * 修改配网监测点表
     * @author cdf
     * @date 2022/10/26
     */
    @PostMapping("updateDistributionMonitor")
    @ApiImplicitParam(name = "distributionMonitorParam",value = "配网监测点实体",required = true)
    @OperateInfo(info = LogEnum.BUSINESS_COMMON,operateType = OperateType.UPDATE)
    @ApiOperation("修改配网监测点")
    @TerminalOperationLogDesc(value = "修改配网监测点",module = 7)
    public HttpResult<Boolean> updateDistributionMonitor(@RequestBody @Validated DistributionMonitorParam distributionMonitorParam){
        String methodDescribe = getMethodDescribe("updateDistributionMonitor");
        boolean res= iDistributionMonitorService.updateDistributionMonitor(distributionMonitorParam);
        if(res){
            return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
        }else {
            return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.FAIL, null, methodDescribe);
        }
    }

    /**
     * 根据监测点id获取配网监测点
     * @author cdf
     * @date 2023/2/20
     */
    @PostMapping("getDistributionMonitorById")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "monitorSort",value = "配网类别",required = true),
            @ApiImplicitParam(name = "id",value = "配网监测点编号",required = true)
    })
    @OperateInfo(info = LogEnum.BUSINESS_COMMON)
    @ApiOperation("根据监测点id获取配网监测点")
    public HttpResult<DistributionMonitor> getDistributionMonitorById(@RequestParam("monitorSort") String monitorSort,@RequestParam("id") String id){
        String methodDescribe = getMethodDescribe("getDistributionMonitorById");
        DistributionMonitor res = iDistributionMonitorService.getDistributionMonitorById(monitorSort,id);
        if(Objects.isNull(res)){
            return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.FAIL, null, methodDescribe);
        }else {
            return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, res, methodDescribe);
        }
    }


    /**
     * 获取配网监测点
     * @author cdf
     * @date 2022/11/29
     */
    @PostMapping("distributionMonitorList")
    @ApiImplicitParam(name = "disMonitorIds",value = "配网监测点编号",required = true)
    @OperateInfo(info = LogEnum.BUSINESS_COMMON)
    @ApiOperation("获取配网监测点")
    public HttpResult<List<DistributionMonitor>> distributionMonitorList(@RequestBody List<String> disMonitorIds){
        String methodDescribe = getMethodDescribe("distributionMonitorList");
        List<DistributionMonitor> res = iDistributionMonitorService.distributionMonitorList(disMonitorIds);
        return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, res, methodDescribe);
    }

    /**
     * 按部门获取旗下配网所有监测点(分一类，二类，三类)
     * @author clam
     * @date 2022/11/29
     */
    @PostMapping("distributionMonitorListByCondition")
    @OperateInfo(info = LogEnum.BUSINESS_COMMON)
    @ApiOperation("按部门获取旗下配网所有监测点(分一类，二类，三类)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orgId", value = "机构编号", required = true),
            @ApiImplicitParam(name = "monitorSort", value = "监测点分类",required = true),

    })
    public HttpResult<List<DistributionMonitor>> distributionMonitorListByCondition(@RequestParam("orgId")String orgId,@RequestParam("monitorSort")String monitorSort){
        String methodDescribe = getMethodDescribe("distributionMonitorList");
        List<DistributionMonitor> res = iDistributionMonitorService.distributionMonitorListByCondition(orgId,monitorSort);
        return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, res, methodDescribe);
    }


    /**
     * 获取指定组织下的发电用电用户
     * @author cdf
     * @date 2022/11/15
     */
    @OperateInfo(info = LogEnum.BUSINESS_COMMON)
    @PostMapping("/getDoubleUserByDept")
    @ApiOperation("获取指定组织下的发电用电用户")
    @ApiImplicitParam(name = "orgId", value = "组装机构编号", required = true)
    public HttpResult<List<DoubleUserVO>> getDoubleUserByDept(@RequestParam("orgId")String orgId) {
        String methodDescribe = getMethodDescribe("getDoubleUserByDept");
        List<DoubleUserVO> infos = iDistributionMonitorService.getDoubleUserByDept(orgId);
        if (CollectionUtil.isEmpty(infos)) {
            return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.NO_DATA, null, methodDescribe);
        } else {
            return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, infos, methodDescribe);
        }
    }



    /**
     * 删除配网监测点
     * @author cdf
     * @date 2022/12/5
     */

    @PostMapping("delDistributionMonitor")
    @ApiImplicitParam(name = "taiZhangDelParam",value = "配网监测点实体",required = true)
    @OperateInfo(info = LogEnum.BUSINESS_COMMON,operateType = OperateType.DELETE)
    @ApiOperation("删除配网监测点")
    public HttpResult<Boolean> delDistributionMonitor(@RequestBody @Validated TaiZhangDelParam taiZhangDelParam){
        String methodDescribe = getMethodDescribe("delDistributionMonitor");

        List<TerminalLog> terminalLogList = new ArrayList<>();
       for(String item : taiZhangDelParam.getIds()){
           LambdaQueryWrapper<DistributionMonitor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
           lambdaQueryWrapper.eq(DistributionMonitor::getMonitorId,item);
            DistributionMonitor distributionMonitor = iDistributionMonitorService.getOne(lambdaQueryWrapper);
            if (Objects.nonNull(distributionMonitor)) {
                PmsDistributionMonitorDTO pmsDistributionMonitorDTO = iDistributionMonitorService.distributionMonitorDetail(distributionMonitor.getMonitorId(), distributionMonitor.getMonitorSort(), distributionMonitor.getIfPowerUser());
                if (Objects.nonNull(pmsDistributionMonitorDTO)) {
                    String mubiao = "";
                    if (pmsDistributionMonitorDTO.getMonitorSort() == 1) {
                        mubiao = pmsDistributionMonitorDTO.getOrgName() + "_" + pmsDistributionMonitorDTO.getPowerStationName() + "_" + pmsDistributionMonitorDTO.getLineName() + "_" + pmsDistributionMonitorDTO.getName();
                    } else if (pmsDistributionMonitorDTO.getMonitorSort() == 2) {
                        mubiao = pmsDistributionMonitorDTO.getOrgName() + "_" + pmsDistributionMonitorDTO.getPowerStationName() + "_" + pmsDistributionMonitorDTO.getLineName() + "_" + pmsDistributionMonitorDTO.getName();
                    } else {
                        mubiao = pmsDistributionMonitorDTO.getOrgName() +"_"+ pmsDistributionMonitorDTO.getPlatformName() + "_" + pmsDistributionMonitorDTO.getName();
                    }
                    TerminalLog terminalLog = assTerminalLog(7, "删除配网监测点", mubiao);
                    terminalLog.setResults(1);
                    terminalLogList.add(terminalLog);
                }
            }
        };
        boolean res= iDistributionMonitorService.delDistributionMonitor(taiZhangDelParam);



        if(res){
            iTerminalLogService.saveBatch(terminalLogList);
            return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
        }else {
            terminalLogList = terminalLogList.stream().peek(item->item.setResults(0)).collect(Collectors.toList());
            iTerminalLogService.saveBatch(terminalLogList);
            return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.FAIL, null, methodDescribe);
        }
    }

    private TerminalLog assTerminalLog(Integer type, String top, String mubiao) {
        TerminalLog operationLog = new TerminalLog();
        operationLog.setStatus(DataStateEnum.ENABLE.getCode());
        operationLog.setOperationStatus(true);
        operationLog.setCreateBy(RequestUtil.getUserIndex());
        operationLog.setUpdateBy(RequestUtil.getUserIndex());
        operationLog.setCreateTime(LocalDateTime.now());
        operationLog.setUpdateTime(LocalDateTime.now());
        operationLog.setType(type);
        operationLog.setOperatorDescribe(RequestUtil.getUsername() + "进行" + top + "操作,目标：" + mubiao);
        return operationLog;
    }

    @OperateInfo(info = LogEnum.BUSINESS_COMMON,operateType = OperateType.UPDATE)
    @PostMapping("/updateStatus")
    @ApiOperation("修改配网监测点数据状态")
    @ApiImplicitParam(name = "monitorParam", value = "配网监测点实体", required = true)
    public HttpResult<Boolean> updateStatus(@RequestBody @Validated MonitorStatus.PwMonitorStatus monitorParam) {
        String methodDescribe = getMethodDescribe("updateStatus");
        boolean result = iDistributionMonitorService.updateStatus(monitorParam);
        if(result){
            return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
        }
        return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.FAIL, null, methodDescribe);

    }


    /**
     * 根据监测点获取配网监测点的详细信息
     * @author cdf
     * @date 2023/5/17
     */
    @OperateInfo(info = LogEnum.BUSINESS_COMMON)
    @PostMapping("/pwMonitorAreaDetailInfo")
    @ApiOperation("根据监测点获取配网监测点的详细信息")
    @ApiImplicitParam(name = "monitorIds", value = "配网监测点实体", required = true)
    public HttpResult<List<PwPmsMonitorDTO>> pwMonitorAreaDetailInfo(@RequestBody List<String> monitorIds) {
        String methodDescribe = getMethodDescribe("pwMonitorAreaDetailInfo");
        List<PwPmsMonitorDTO> pwPmsMonitorDTOS = iDistributionMonitorService.pwMonitorAreaDetailInfo(monitorIds);
        if(CollectionUtil.isNotEmpty(pwPmsMonitorDTOS)){
            return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, pwPmsMonitorDTOS, methodDescribe);
        }
        return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.FAIL, null, methodDescribe);

    }


    @ApiOperation(value = "将用户数据导入到配网表中")
    @PostMapping("/savePmsDistributionUser")
    public HttpResult<Boolean> savePmsDistributionUser()  {
        String methodDescribe = getMethodDescribe("savePmsDistributionUser");
        boolean result = iDistributionMonitorService.savePmsDistributionUser();
        if(result){
            return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
        }
        return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.FAIL, null, methodDescribe);
    }

    @ApiOperation(value = "将台区数据导入到配网表中")
    @PostMapping("/savePmsDistributionArea")
    public HttpResult<Boolean> savePmsDistributionArea()  {
        String methodDescribe = getMethodDescribe("savePmsDistributionArea");
        boolean result = iDistributionMonitorService.savePmsDistributionArea();
        if(result){
            return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
        }
        return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.FAIL, null, methodDescribe);
    }


    /**
     * 获取配网用户数据
     */
    @OperateInfo(info = LogEnum.BUSINESS_COMMON)
    @PostMapping("/getPwUserIds")
    @ApiOperation("获取配网用户数据")
    public HttpResult<List<PwUserMonitorDataVO>> getPwUserIds(@RequestBody @Validated PwUserMonitorParam pwUserMonitorParam) {
        String methodDescribe = getMethodDescribe("getPwUserIds");
        List<PwUserMonitorDataVO> pwUserMonitorDataVOList = iDistributionMonitorService.getPwUserIds(pwUserMonitorParam);
        return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, pwUserMonitorDataVOList, methodDescribe);
    }



}

