package com.ruoyi.postCheck.controller;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.constant.PostPlanEnum;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.Arith;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.postCheck.domain.PostAssessmentRating;
import com.ruoyi.postCheck.domain.PostPlanInfo;
import com.ruoyi.postCheck.domain.homePage.*;
import com.ruoyi.postCheck.service.IPostAssessmentRatingService;
import com.ruoyi.postCheck.service.IPostCheckedProblemService;
import com.ruoyi.postCheck.service.IPostPlanInfoService;
import com.ruoyi.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

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


/**
 * 岗检问题表Controller
 *
 * @author csg
 * @date 2023-12-23
 */
@Api(tags = "7.1.1-首页统计查询")
@RestController
@RequestMapping("/postCheck/homePage")
public class PostCheckedHomePageController extends BaseController {
    @Autowired
    private IPostCheckedProblemService postCheckedProblemService;
    @Autowired
    private IPostAssessmentRatingService postAssessmentRatingService;

    @Autowired
    private IPostPlanInfoService postPlanInfoService;

    @Autowired
    private ISysUserService sysUserService;


    /**
     * 1、责任制清单：post_list表
     * 2、检查出的问题：post_checked_problem表
     * 3、岗检数量-已查：post_plan t1 inner join post_plan_info t2 两张表连接，t2.status(岗检状态：1-未检；2-已检；)
     * 4、岗检数量-未查：post_plan t1 inner join post_plan_info t2 两张表连接，t2.status(岗检状态：1-未检；2-已检；)
     */
    @ApiOperation("1-总览：统计岗位责任制清单、岗检问题、岗检计划")
  /*  @ApiImplicitParams({
            @ApiImplicitParam(name = "listCount", value = "责任制清单数量", dataType = "Integer", dataTypeClass = Integer.class),
            @ApiImplicitParam(name = "problemCount", value = "检查出的问题数量", dataType = "Integer", dataTypeClass = Integer.class),
            @ApiImplicitParam(name = "checkedPostCount", value = "岗检数量-已查", dataType = "Integer", dataTypeClass = Integer.class),
            @ApiImplicitParam(name = "uncheckedPostCount", value = "岗检数量-未查", dataType = "Integer", dataTypeClass = Integer.class),
    })*/
    @GetMapping("/totalView")
    public AjaxResult totalView() {
        return success(postCheckedProblemService.totalView());
    }



    @ApiOperation("2-岗检问题属性分布")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "problemTotal", value = "总数量", dataType = "Integer", dataTypeClass = Integer.class),
            @ApiImplicitParam(name = "problemComplete", value = "完整性数量", dataType = "Integer", dataTypeClass = Integer.class),
            @ApiImplicitParam(name = "problemSuitable", value = "适宜性数量", dataType = "Integer", dataTypeClass = Integer.class),
            @ApiImplicitParam(name = "problemEffective", value = "有效性数量", dataType = "Integer", dataTypeClass = Integer.class),

    })
    @GetMapping("/checkedProblem")
    public AjaxResult checkedProblem() {
//        检查出的问题：post_checked_problem表 按 problem_attribute-问题属性（1-完整问题；2-有效性问题；3-适宜性问题；） 分组 count(id)
        return success(postCheckedProblemService.checkedProblem());
    }


    /**
     * 3-人员数量V2->岗位：data.postShouldCheckedCount；人员：data.userShouldCheckedCount
     * @return
     */
    @ApiOperation("3-应检岗位数量、应检岗位人数")
    @GetMapping("/userTotal")
    public AjaxResult userTotal() {
        //查询待检查的岗位
        String year = DateUtils.parseDateToStr(DateUtils.YYYY, new Date());
        Map<String, Object> params = new HashMap<>();
        params.put("beginTime", year + "-01-01");
        params.put("endTime", year + "-12-31");
        PostPlanInfo shouldCheckedParam = new PostPlanInfo();
        shouldCheckedParam.setPlanStatus(PostPlanEnum.STATUS_PASS.getValue());
        shouldCheckedParam.setParams(params);
        List<PostPlanInfo> postPlanInfoList = postPlanInfoService.selectShouldCheckedList(shouldCheckedParam);
        Set<Long> cheeckedPostIdSet = postPlanInfoList.stream().map(PostPlanInfo::getCheckedPostId).collect(Collectors.toSet());

        //查询岗位下人员：待检查的人员
        List<SysUser> sysUserList = sysUserService.postUserList(null, null, null, null, null, null, new ArrayList<>(cheeckedPostIdSet));
        List<SysUser> userPostList = sysUserList.stream().filter(element -> element.getPostId() != null).collect(Collectors.toList());
        int userPostCount = userPostList.size();
        JSONObject data = new JSONObject();
        data.put("postShouldCheckedCount", cheeckedPostIdSet.size());
        data.put("userShouldCheckedCount", userPostCount);

//        return success(postCheckedProblemService.userTotal());
        return success(data);
    }


    /**
     * 中间饼图-20240305岗检计划完成率：主要体现“率”百分比（岗检计划中的 已检岗位数量 和 应检岗位数量）
     * @return
     */
    @ApiOperation("4-岗检完成率统计")
    @GetMapping("/planCompletionRate")
    public AjaxResult planCompletionRate() {

        //查询待检查的岗位
        String year = DateUtils.parseDateToStr(DateUtils.YYYY, new Date());
        Map<String, Object> params = new HashMap<>();
        params.put("beginTime", year + "-01-01");
        params.put("endTime", year + "-12-31");
        PostPlanInfo shouldCheckedParam = new PostPlanInfo();
        shouldCheckedParam.setPlanStatus(PostPlanEnum.STATUS_PASS.getValue());
        shouldCheckedParam.setParams(params);
        List<PostPlanInfo> postPlanInfoList = postPlanInfoService.selectShouldCheckedList(shouldCheckedParam);

        Map<Integer, List<PostPlanInfo>> planInfoStatusMap = postPlanInfoList.stream().collect(Collectors.groupingBy(PostPlanInfo::getStatus));
        //岗检状态：1-未检；2-已检；
        Integer no = PostPlanEnum.INFO_STATUS_NO.getValue();
        Integer yes = PostPlanEnum.INFO_STATUS_YES.getValue();
        List<PostPlanInfo> noPostPlanInfoList = planInfoStatusMap.get(no);
        List<PostPlanInfo> yesPostPlanInfoList = planInfoStatusMap.get(yes);


        Map<Integer, Object> planCompletionRateMap = new HashMap<>();
        planCompletionRateMap.put(no, noPostPlanInfoList.size());
        planCompletionRateMap.put(yes, yesPostPlanInfoList.size());
        planCompletionRateMap.put(yes + 1, Arith.div(yesPostPlanInfoList.size(), noPostPlanInfoList.size() + yesPostPlanInfoList.size(), 2));

        return success(planCompletionRateMap);
    }


    @ApiOperation("5-岗检问题整改一览-岗检问题整改率")
    @GetMapping("/problemRectification")
    public AjaxResult problemRectification() {
        return success(postCheckedProblemService.problemRectification());
    }

    @ApiOperation("6-岗检问题整改一览-岗检部门整改率")
    @GetMapping("/deptProblemRectification")
    public AjaxResult deptProblemRectification() {
//        查询问题表：post_checked_problem
//        group by checked_dept_id 整改责任部门ID（被检查部门ID）
//        最好给前端定义一个对象，用Map也可以
        return success(postCheckedProblemService.deptProblemRectification());
    }


//    @ApiOperation("7.1-岗检已查")
    @ApiOperation("7.1-岗检计划完成一览-应检已检岗位")
    @GetMapping("/postChecked")
    public AjaxResult postChecked() {
//        SELECT
//           t2."checked_dept_id" ,
//           t2.checked_post_id,
//           MIN(t2."status")  AS "status" ,
//           MAX (t2."status")  AS aa
//        FROM "post_plan" t1
//        INNER JOIN "post_plan_info" t2 ON t2."post_plan_id" = t1."id"
//        WHEN t1.status = 3 -- 状态：1-待审核；2-审核中；3-通过；4-驳回；
//        AND t2."status" = ? -- 岗检状态：1-未检；2-已检；
//        GROUP BY t2."checked_dept_id", t2."checked_post_id"
//        ORDER BY t2."checked_dept_id"

//        最后一列人数 left join “用户表”+“用户岗位中间表” on t2."checked_post_id" =  sys_user_post.post_id 进行 count(sys_users.id) as 人数
//        select * from "public"."sys_users";
//        select * from "public"."sys_user_post";

        return success(postCheckedProblemService.postChecked(PostPlanEnum.INFO_STATUS_YES.getValue()));
    }


//    @ApiOperation("7.2-岗检未查")
    @ApiOperation("7.2-岗检计划完成一览-应检未检岗位")
    @GetMapping("/postUnChecked")
    public AjaxResult postUnChecked() {
//        SELECT
//           t2."checked_dept_id" ,
//           t2.checked_post_id,
//           MIN(t2."status")  AS "status" ,
//           MAX (t2."status")  AS aa
//        FROM "post_plan" t1
//        INNER JOIN "post_plan_info" t2 ON t2."post_plan_id" = t1."id"
//        WHEN t1.status = 3 -- 状态：1-待审核；2-审核中；3-通过；4-驳回；
//        AND t2."status" = ? -- 岗检状态：1-未检；2-已检；
//        GROUP BY t2."checked_dept_id", t2."checked_post_id"
//        ORDER BY t2."checked_dept_id"

//        最后一列人数 left join “用户表”+“用户岗位中间表” on t2."checked_post_id" =  sys_user_post.post_id 进行 count(sys_users.id) as 人数
//        select * from "public"."sys_users";
//        select * from "public"."sys_user_post";

        return success(postCheckedProblemService.postChecked(PostPlanEnum.INFO_STATUS_NO.getValue()));
    }


//    @ApiOperation("8-评比排名-废弃")
//    @GetMapping("/assessmentRating")
    public AjaxResult assessmentRating() {
//        岗位问题表结合岗检规则实时计算岗检扣分情况
//        select * from "public"."post_checked_problem";

//        互评表（职能互评得分/生产日常得分）
//        select * from "public"."post_assessment_rating_other";
//        select * from "public"."post_assessment_rating_other_info";

//      部门得分 = （岗检分数 * 0.5 + 互评分数 * 0.5  ）
//      根据部门得分进行排名计算
        PostAssessmentRating postAssessmentRating1 = new PostAssessmentRating();
        postAssessmentRating1.setType(1);//"类型：1-职能；2-生产；
        List<PostAssessmentRating> postAssessmentRatings1 = postAssessmentRatingService.selectPostAssessmentRatingList(postAssessmentRating1);

        PostAssessmentRating postAssessmentRating2 = new PostAssessmentRating();
        postAssessmentRating2.setType(2);//"类型：1-职能；2-生产；
        List<PostAssessmentRating> postAssessmentRatings2 = postAssessmentRatingService.selectPostAssessmentRatingList(postAssessmentRating2);

        postAssessmentRatings1.addAll(postAssessmentRatings2);
        List<AssessmentRatingView> dataList = new ArrayList<>();
        postAssessmentRatings1.forEach(x -> {
            AssessmentRatingView data1 = new AssessmentRatingView();
            data1.setDeptId(x.getDeptId());
            data1.setDeptName(x.getDeptName());
//            data1.setPostCount(postCheckedProblemService.getPostCountByDeptId(x.getDeptId()));
            data1.setScore(x.getDepartmentScore().setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
            dataList.add(data1);
        });
        List<AssessmentRatingView> collect = dataList.stream().sorted(Comparator.comparing(AssessmentRatingView::getScore).reversed()).collect(Collectors.toList());
        Integer i = 1;
        for (AssessmentRatingView x : collect) {
            x.setRating(i);
            i++;
        }
        return success(collect);
    }


    @ApiOperation("8.1-评比排名-职能管理部门维度")
    @GetMapping({"/assessmentRatingZN", "/assessmentRatingZN/{year}"})
    @ApiImplicitParam(name = "year", value = "路径参数选填（不传时后台默认设置为当前年），值为4位数年，例如：2023、2024", dataType = "String", dataTypeClass = String.class)
    public AjaxResult assessmentRatingZN(@PathVariable(value = "year", required = false) String year) {

        if (StringUtils.isBlank(year)) {
            year = DateUtils.parseDateToStr(DateUtils.YYYY, new Date());
        }

        String beginTime = year + "-01-01";
        String endTime = year + "-12-31";
        List<PostAssessmentRating> postAssessmentRatings = postAssessmentRatingService.statisticsPostAssessmentRatingZN(beginTime, endTime);

        List<AssessmentRatingView> dataList = new ArrayList<>();

        Integer rating = 0;
        BigDecimal lastScore = new BigDecimal("0.00");

        for (int i = 0; i < postAssessmentRatings.size(); i++) {
            PostAssessmentRating postAssessmentRating = postAssessmentRatings.get(i);

            BigDecimal departmentScore = postAssessmentRating.getDepartmentScore();//得分

            AssessmentRatingView data = new AssessmentRatingView();
            data.setDeptId(postAssessmentRating.getDeptId());
            data.setDeptName(postAssessmentRating.getDeptName());



//            BigDecimal positionScore = postAssessmentRating.getPositionScore();
//            System.out.println();
//            System.out.println("positionScore = " + positionScore);
//            BigDecimal bigDecimal = positionScore.setScale(2, BigDecimal.ROUND_HALF_UP);
//            System.out.println("bigDecimal = " + bigDecimal);
//            double doubleValue = bigDecimal.doubleValue();
//            System.out.println("doubleValue = " + doubleValue);
//            System.out.println();

            data.setPostScore(postAssessmentRating.getPositionScore().setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());//岗检得分
            data.setDeptScore(postAssessmentRating.getPeerEvaluationScore().setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());//互评/日常得分
            data.setScore(departmentScore.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());

            //分数相等排名不增加
            if (departmentScore.compareTo(lastScore) == 0) {
                if (rating == 0) {
                    rating++;
                }
                data.setRating(rating);
            }
            //增加排名
            else {
                rating++;
                data.setRating(rating);
            }
            lastScore = departmentScore;


            dataList.add(data);//总分
        }

        return success(dataList);
    }


    @ApiOperation("8.2-评比排名-生产运行部门维度")
    @GetMapping({"/assessmentRatingSC", "/assessmentRatingSC/{year}"})
    @ApiImplicitParam(name = "year", value = "路径参数选填（不传时后台默认设置为当前年），值为4位数年，例如：2023、2024", dataType = "String", dataTypeClass = String.class)
    public AjaxResult assessmentRatingSC(@PathVariable(value = "year", required = false) String year) {

        if (StringUtils.isBlank(year)) {
            year = DateUtils.parseDateToStr(DateUtils.YYYY, new Date());
        }

        String beginTime = year + "-01-01";
        String endTime = year + "-12-31";
        List<PostAssessmentRating> postAssessmentRatings = postAssessmentRatingService.statisticsPostAssessmentRatingSC(beginTime, endTime);

        List<AssessmentRatingView> dataList = new ArrayList<>();

        Integer rating = 0;
        BigDecimal lastScore = new BigDecimal("0.00");

        for (int i = 0; i < postAssessmentRatings.size(); i++) {
            PostAssessmentRating postAssessmentRating = postAssessmentRatings.get(i);

            BigDecimal departmentScore = postAssessmentRating.getDepartmentScore();//得分

            AssessmentRatingView data = new AssessmentRatingView();
            data.setDeptId(postAssessmentRating.getDeptId());
            data.setDeptName(postAssessmentRating.getDeptName());


//            postAssessmentRating.getPositionScore().setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue()
            BigDecimal positionScore = postAssessmentRating.getPositionScore();
//            System.out.println();
//            System.out.println("positionScore = " + positionScore);
            BigDecimal bigDecimal = positionScore.setScale(2, BigDecimal.ROUND_HALF_UP);
//            System.out.println("bigDecimal = " + bigDecimal);
            double doubleValue = bigDecimal.doubleValue();
//            System.out.println("doubleValue = " + doubleValue);
//            System.out.println();

            data.setPostScore(postAssessmentRating.getPositionScore().setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());//岗检得分
            data.setDeptScore(postAssessmentRating.getPeerEvaluationScore().setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());//互评/日常得分
            data.setScore(departmentScore.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());

            //分数相等排名不增加
            if (departmentScore.compareTo(lastScore) == 0) {
                if (rating == 0) {
                    rating++;
                }
                data.setRating(rating);
            }
            //增加排名
            else {
                rating++;
                data.setRating(rating);
            }
            lastScore = departmentScore;


            dataList.add(data);//总分
        }

        return success(dataList);
    }


}
