package com.yeejoin.amos.boot.module.jxiop.biz.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.biz.common.controller.BaseController;
import com.yeejoin.amos.boot.module.jxiop.api.Enum.QrcodeColorEnum;
import com.yeejoin.amos.boot.module.jxiop.api.entity.StationBasic;
import com.yeejoin.amos.boot.module.jxiop.api.feign.IdxFeign;
import com.yeejoin.amos.boot.module.jxiop.api.feign.McbWarningFeign;
import com.yeejoin.amos.boot.module.jxiop.api.mapper.PersonBasicMapper;
import com.yeejoin.amos.boot.module.jxiop.api.mapper.StationBasicMapper;
import com.yeejoin.amos.boot.module.jxiop.api.mapper.StationQrCodeStatisticsMapper;
import com.yeejoin.amos.boot.module.jxiop.biz.mapper2.SjglZsjZsbtzMapper;
import com.yeejoin.amos.boot.module.jxiop.biz.service.impl.PersonBasicServiceImpl;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import org.typroject.tyboot.core.restful.utils.ResponseHelper;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@Api(tags = "人员人员赋码基本信息 评估大屏Api")
@RequestMapping(value = "/person-qrcode")
public class PersonQrCodeController extends BaseController {

    @Autowired
    PersonBasicServiceImpl personBasicServiceImpl;

    @Autowired
    McbWarningFeign mcbWarningFeign;


    @Autowired
    PersonBasicMapper personBasicMapper;

    @Autowired
    private StationQrCodeStatisticsMapper stationQrCodeStatisticsMapper;

    @Autowired
    private SjglZsjZsbtzMapper sjglZsjZsbtzMapper;

    @Autowired
    private IdxFeign idxFeign;

    @Autowired
    private StationBasicMapper stationBasicMapper;


    /**
     * 评估大屏 - 人员赋码环形图查询
     *
     * @param parentCode 父级code
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @GetMapping(value = "/getPersonYardStatistics")
    @ApiOperation(httpMethod = "GET", value = "评估大屏 - 人员赋码环形图查询", notes = "评估大屏 - 人员赋码环形图查询")
    public ResponseModel<List<Map<String, Object>>> getPersonYardStatistics(@RequestParam(required = false, value = "parentCode") String parentCode,
                                                                            @RequestParam(required = false, value = "dataType") String dataType) {

        List<Map<String, Object>> resultList = new ArrayList<>();

        if (StringUtils.isNotEmpty(dataType) && dataType.equals("person")) {
            resultList = personBasicMapper.getPersonYardStatistics(parentCode);
        } else if (StringUtils.isNotEmpty(dataType) && dataType.equals("equip")) {
            resultList = sjglZsjZsbtzMapper.getEquipYardStatistics(parentCode);
        } else if (StringUtils.isNotEmpty(dataType) && dataType.equals("job")) {
            resultList = sjglZsjZsbtzMapper.getJobYardStatistics(parentCode);
        }
        Map<Object, Object> collect = resultList.stream().collect(Collectors.toMap(t -> t.get("qrCodeColor"), t -> t.get("value")));
        List<Map<String, Object>> maps = new ArrayList<>();
        Arrays.stream(QrcodeColorEnum.values()).forEach(item -> {
            HashMap<String, Object> map = new HashMap<>();
            map.put("qrCodeColor", item.getCode());
            map.put("name", item.getName());
            map.put("value", Integer.parseInt(collect.getOrDefault(item.getCode(), 0).toString()));
            maps.add(map);
        });
        return ResponseHelper.buildResponse(maps);
    }

    /**
     * 评估大屏 - 人员赋码列表查询
     *
     * @param parentCode 父级code
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @GetMapping(value = "/getPersonYardByPage")
    @ApiOperation(httpMethod = "GET", value = "评估大屏 - 人员赋码列表查询", notes = "评估大屏 - 人员赋码列表查询")
    public ResponseModel<Page<Map<String, Object>>> getPersonYardByPage(@RequestParam(required = false, value = "parentCode") String parentCode,
                                                                        @RequestParam(value = "current") Integer current,
                                                                        @RequestParam(value = "size") Integer size,
                                                                        @RequestParam(required = false, value = "dataType") String dataType,
                                                                        @RequestParam(required = false) String date,
                                                                        @RequestParam(required = false) String qrCodeColor) {
        Page<Map<String, Object>> resultList = new Page<>();

        if ("person".equals(dataType)) {
            resultList = personBasicServiceImpl.getPersonYardByPage(parentCode, current, size, date, qrCodeColor, null, null);
        } else if ("equip".equals(dataType)) {
            List<Map<String, Object>> equipYardByPage = sjglZsjZsbtzMapper.getEquipYardByPage((current - 1) * size, size, parentCode, date, qrCodeColor, null);
            Integer equipYardByPageCount = sjglZsjZsbtzMapper.getEquipYardByPageCount(parentCode, date, qrCodeColor, null);
            equipYardByPage.forEach(item -> {
                String name = QrcodeColorEnum.getName(String.valueOf(item.get("qrCodeColor")));
                item.put("name", name);
            });
            resultList.setRecords(equipYardByPage);
            resultList.setCurrent(current);
            resultList.setSize(size);
            resultList.setTotal(equipYardByPageCount);
        } else if ("job".equals(dataType)) {
            List<Map<String, Object>> jobYardByPage = sjglZsjZsbtzMapper.getJobYardByPage((current - 1) * size, size, parentCode, date, qrCodeColor, null);
            Integer jobYardByPageCount = sjglZsjZsbtzMapper.getJobYardByPageCount(parentCode, date, qrCodeColor, null);
            jobYardByPage.forEach(item -> {
                String name = QrcodeColorEnum.getName(String.valueOf(item.get("qrCodeColor")));
                item.put("name", name);
            });
            resultList.setRecords(jobYardByPage);
            resultList.setCurrent(current);
            resultList.setSize(size);
            resultList.setTotal(jobYardByPageCount);
        }
        return ResponseHelper.buildResponse(resultList);
    }

    /**
     * 评估大屏 - 人员赋码数量等统计
     *
     * @param parentCode 父级code
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @GetMapping(value = "/getQrCodeCount")
    @ApiOperation(httpMethod = "GET", value = "评估大屏 - 人员赋码数量等统计", notes = "评估大屏 - 人员赋码数量等统计")
    public ResponseModel<Map<String, Object>> getQrCodeCount(@RequestParam(required = false, value = "parentCode") String parentCode,
                                                             @RequestParam(required = false, value = "dataType") String dataType) {

        FeignClientResult<Map<String, Object>> sevenEntity = null;
        try {
            sevenEntity = mcbWarningFeign.getQrCodeCount(parentCode, dataType);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (sevenEntity != null && 200 == sevenEntity.getStatus()) {
            Map<String, Object> result = sevenEntity.getResult();
            String red = result.get("red").toString();
            String yellow = result.get("yellow").toString();
            String redToGreen = result.get("redToGreen").toString();
            String yellowToGreen = result.get("yellowToGreen").toString();
            Integer countAll = 0;
            if ("RYFM".equals(dataType) || "person".equals(dataType)) {
                countAll = personBasicMapper.getPersonYardByPageCount(parentCode, null, null, null);
            } else if ("equip".equals(dataType)) {
                countAll = sjglZsjZsbtzMapper.getEquipYardByPageCount(parentCode, null, null, null);
            } else if ("job".equals(dataType)) {
                countAll = sjglZsjZsbtzMapper.getJobYardByPageCount(parentCode, null, null, null);
            }
            result.put("redToGreenPercent", getPercent(new BigDecimal(red), new BigDecimal(countAll)));
            result.put("redPercent", getPercent(new BigDecimal(redToGreen), new BigDecimal(countAll)));
            result.put("yellowToGreenPercent", getPercent(new BigDecimal(yellow), new BigDecimal(countAll)));
            result.put("yellowPercent", getPercent(new BigDecimal(yellowToGreen), new BigDecimal(countAll)));
            return ResponseHelper.buildResponse(result);
        }
        return ResponseHelper.buildResponse(null);
    }


    /**
     * 评估大屏 - 场站 人员赋码数量等统计 【折线图】
     *
     * @param parentCode 父级code
     * @param dataType 类型 - 人员、任务、设备等
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @GetMapping(value = "/getQrCodeCountByStation")
    @ApiOperation(httpMethod = "GET", value = "评估大屏 - 场站 人员赋码数量等统计 【折线图】", notes = "评估大屏 - 场站 人员赋码数量等统计 【折线图】")
    public ResponseModel<Map<String, Object>> getQrCodeCountByStation(@RequestParam(required = false, value = "parentCode") String parentCode,
                                                                            @RequestParam(required = false, value = "dataType") String dataType) {
        List<Map<String, Object>> qrCodeCountByStation = stationQrCodeStatisticsMapper.getQrCodeCountByStation(parentCode, dataType);

        List<Object> redNum = qrCodeCountByStation.stream().map(t -> t.get("redNum")).collect(Collectors.toList());
        List<Object> yellowNum = qrCodeCountByStation.stream().map(t -> t.get("yellowNum")).collect(Collectors.toList());
        List<Object> date = qrCodeCountByStation.stream().map(t -> t.get("date")).collect(Collectors.toList());
        ArrayList<Map<String, Object>> maps = new ArrayList<>();
        HashMap<String, Object> map = new HashMap<>();
        map.put("data", redNum);
        map.put("name", "红码");
        maps.add(map);

        HashMap<String, Object> map1 = new HashMap<>();
        map1.put("data", yellowNum);
        map1.put("name", "黄码");
        maps.add(map1);

        HashMap<String, Object> resultMap = new HashMap<>();
        resultMap.put("seriesData", maps);
        resultMap.put("axisData", date);
        return ResponseHelper.buildResponse(resultMap);
    }


    /**
     * 百分比
     *
     * @param numerator   分子
     * @param denominator 分母
     * @return 百分比
     */
    private double getPercent(BigDecimal numerator, BigDecimal denominator) {
        BigDecimal multiply = numerator.divide(denominator.compareTo(BigDecimal.ZERO) != 0 ? denominator : new BigDecimal(1), 4, BigDecimal.ROUND_DOWN).multiply(new BigDecimal(100));
        return Math.abs(multiply.doubleValue());
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @GetMapping(value = "/getStationDetailInfo")
    @ApiOperation(httpMethod = "GET", value = "评估大屏 - 场站信息查询", notes = "评估大屏 - 场站信息查询")
    public ResponseModel<Map<String, Object>> getStationDetailInfo(@RequestParam(required = true, value = "parentCode") String parentCode) {
        FeignClientResult<Map<String, Object>> sevenEntity = null;
        try {
            sevenEntity = idxFeign.healthIndexData(parentCode, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        FeignClientResult<Integer> sevenEntityMcb = null;
        try {
            sevenEntityMcb = mcbWarningFeign.getWarningInfoCountByObjectId(parentCode);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String score = "100";
        String gradeColor = "green";
        Integer warningCount = 0;
        if (sevenEntity != null && 200 == sevenEntity.getStatus()) {
            Map<String, Object> result = sevenEntity.getResult();
            score = result.get("score").toString();
            gradeColor = result.get("gradeColor").toString();
        }
        if (sevenEntityMcb != null && 200 == sevenEntityMcb.getStatus()) {
            warningCount = sevenEntityMcb.getResult();
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("score", score);
        map.put("gradeColor", gradeColor);
        map.put("warningCount", warningCount);
        LambdaQueryWrapper<StationBasic> stationBasicLambdaQueryWrapper = new LambdaQueryWrapper<>();
        stationBasicLambdaQueryWrapper.eq(StationBasic::getProjectOrgCode, parentCode);
        stationBasicLambdaQueryWrapper.last("limit 1");
        StationBasic stationBasic = stationBasicMapper.selectOne(stationBasicLambdaQueryWrapper);
        map.put("stationMasterName", stationBasic.getStationMasterName());
        map.put("mobilePhone", stationBasic.getMobilePhone());
        map.put("recDate", stationBasic.getRecDate());
        return ResponseHelper.buildResponse(map);
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @GetMapping(value = "/getStationEquipInfo")
    @ApiOperation(httpMethod = "GET", value = "评估大屏 - 场站二级弹窗API", notes = "评估大屏 - 场站二级弹窗API")
    public ResponseModel<Page<Map<String, Object>>> getStationEquipInfo(@RequestParam(value = "parentCode") String parentCode,
                                                                        @RequestParam(required = false, value = "column") String column,
                                                                        @RequestParam(required = false, value = "score") BigDecimal score,
                                                                        @RequestParam(value = "current") Integer current,
                                                                        @RequestParam(value = "size") Integer size,
                                                                        @RequestParam(required = false, value = "date") String date) {
        Page<Map<String, Object>> resultList = new Page<>();
        if ("V1".equals(column)) {
            resultList = personBasicServiceImpl.getPersonYardByPage(parentCode, current, size, date, null, "green", score);
        } else if ("S1".equals(column)) {
            List<Map<String, Object>> equipYardByPage = sjglZsjZsbtzMapper.getEquipYardByPage((current - 1) * size, size, parentCode, date, null, "green");
            Integer equipYardByPageCount = sjglZsjZsbtzMapper.getEquipYardByPageCount(parentCode, date, null, "green");
            equipYardByPage.forEach(item -> {
                String name = QrcodeColorEnum.getName(String.valueOf(item.get("qrCodeColor")));
                item.put("name", name);
                item.put("faultInfo", "该存在缺陷或者告警");
                item.put("faultLevel", "严重");
                if (!Objects.isNull(score)) {
                    item.put("mark", new BigDecimal(100).subtract(score));
                }
            });
            resultList.setRecords(equipYardByPage);
            resultList.setCurrent(current);
            resultList.setSize(size);
            resultList.setTotal(equipYardByPageCount);
        } else if ("P1".equals(column)) {
            List<Map<String, Object>> jobYardByPage = sjglZsjZsbtzMapper.getJobYardByPage((current - 1) * size, size, parentCode, date, null, "green");
            Integer jobYardByPageCount = sjglZsjZsbtzMapper.getJobYardByPageCount(parentCode, date, null, "green");
            jobYardByPage.forEach(item -> {
                String name = QrcodeColorEnum.getName(String.valueOf(item.get("qrCodeColor")));
                item.put("name", name);
                item.put("faultInfo", "该任务超时");
                item.put("faultLevel", "严重");
                if (!Objects.isNull(score)) {
                    item.put("mark", new BigDecimal(100).subtract(score));
                }
            });
            resultList.setRecords(jobYardByPage);
            resultList.setCurrent(current);
            resultList.setSize(size);
            resultList.setTotal(jobYardByPageCount);
        }
        return ResponseHelper.buildResponse(resultList);
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @GetMapping(value = "/getDetailInfoByObjectId")
    @ApiOperation(httpMethod = "GET", value = "评估大屏 - 三级弹窗左侧信息API", notes = "评估大屏 - 三级弹窗左侧信息API")
    public ResponseModel<Map<String, Object>> getDetailInfoByObjectId(@RequestParam(value = "objectId") String objectId,
                                                                      @RequestParam(value = "column") String column,
                                                                      @RequestParam(required = false, value = "jobId") String jobId) {
        Map<String, Object> resultMap = new HashMap<>();
        if ("V1".equals(column)) {
            resultMap = personBasicServiceImpl.getPersonDetailInfoByObjectId(objectId);
        } else if ("S1".equals(column)) {
            resultMap = sjglZsjZsbtzMapper.getEquipDetailInfoByObjectId(objectId);
        } else if ("P1".equals(column)) {
            resultMap = sjglZsjZsbtzMapper.getJobDetailInfoByObjectId(jobId);
        }
        return ResponseHelper.buildResponse(resultMap);
    }
}
