package com.mortals.xhx.module.check.web;

import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.annotation.UnAuth;
import com.mortals.framework.common.Rest;
import com.mortals.framework.model.Context;
import com.mortals.framework.model.PageInfo;
import com.mortals.framework.model.Result;
import com.mortals.framework.util.DataUtil;
import com.mortals.framework.util.DateUtils;
import com.mortals.framework.util.StringUtils;
import com.mortals.framework.web.BaseJsonBodyController;
import com.mortals.xhx.common.code.*;
import com.mortals.xhx.module.check.model.CheckAllRecordQuery;
import com.mortals.xhx.module.check.model.vo.CheckAllRecordVo;
import com.mortals.xhx.module.check.model.vo.CheckAllScoreSummaryVo;
import com.mortals.xhx.module.check.model.vo.StaffCheckSummaryQuery;
import com.mortals.xhx.module.check.service.CheckAllRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.*;

/**
 * 全部类型核查信息Dao
 */
@RestController
@RequestMapping("check/all/record")
public class CheckAllRecordController extends BaseJsonBodyController {

    @Autowired
    private CheckAllRecordService checkAllRecordService;

    protected void init(Map<String, Object> model, Context context) {
        this.addDict(model, "checkStatus", CheckStatusEnum.getEnumMap());
        this.addDict(model, "subMethod", SubMethodEnum.getEnumMap());
        this.addDict(model, "subAddType", SubAddTypeEnum.getEnumMap());
        this.addDict(model, "checkType", CheckTypeEnum.getEnumMap());
        this.addDict(model, "checkResult", CheckResultEnum.getEnumMap());
    }

    @PostMapping({"list"})
    @UnAuth
    public Rest<Object> list(@RequestBody CheckAllRecordQuery query) {
        Rest<Object> ret = new Rest();
        Map<String, Object> model = new HashMap();
        Context context = this.getContext();
        String busiDesc = "查询所有类型绩效核查信息";

        int code = 1;
        try {
            PageInfo pageInfo = new PageInfo(-1);
            if (StringUtils.isEmpty(query.getCheckTimeStart()) || StringUtils.isEmpty(query.getCheckTimeStart())) {
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                Calendar calendar = Calendar.getInstance();
                calendar.set(Calendar.DAY_OF_MONTH, 1);
                String startTime = format.format(calendar.getTime());
                calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
                String endTime = format.format(calendar.getTime());
                query.setCheckTimeStart(startTime);
                query.setCheckTimeEnd(endTime);
            }
            Result<CheckAllRecordVo> result = checkAllRecordService.getAllCheckRecord(query, pageInfo);

            model.put("data", result.getList());

            model.put("message_info", busiDesc + "成功");
            if (!ObjectUtils.isEmpty(context) && !ObjectUtils.isEmpty(context.getUser())) {
                this.recordSysLog(this.request, busiDesc + " 【成功】");
            }
        } catch (Exception var9) {
            code = -1;
            this.doException(this.request, busiDesc, model, var9);
        }

        this.init(model, context);
        ret.setCode(code);
        ret.setData(model);
        ret.setDict(model.get("dict"));
        ret.setMsg(model.get("message_info") == null ? "" : model.remove("message_info").toString());
        return ret;
    }

    /**
     * 绩效核查分数情况汇总
     *
     * @param query
     * @return
     */
    @PostMapping({"score/summary"})
    @UnAuth
    public Rest<Object> getScoreSummary(@RequestBody StaffCheckSummaryQuery query) {
        Rest<Object> ret = new Rest();
        Map<String, Object> model = new HashMap();
        Context context = this.getContext();
        String busiDesc = "查询绩效核查分数情况汇总";
        int code = 1;
        try {
            StaffCheckSummaryQuery lastQuery = new StaffCheckSummaryQuery();
            Date now = new Date();
            LocalDate localDate = LocalDate.now();
            if (query.getSummaryType() == SummaryTopTypeEnum.年.getValue()) {
                query.setCheckTimeStart(DateUtils.getCurrDateTime("yyyy") + "-01-01");
                query.setCheckTimeEnd(DateUtils.getCurrDateTime("yyyy") + "-12-31");
                lastQuery.setCheckTimeStart((localDate.getYear() - 1) + "-01-01");
                lastQuery.setCheckTimeEnd((localDate.getYear() - 1) + "-12-31");
            }
            if (query.getSummaryType() == SummaryTopTypeEnum.月.getValue()) {
                query.setCheckTimeStart(DateUtils.getCurrDateTime("yyyy-MM") + "-01");
                query.setCheckTimeEnd(DateUtils.getDateTime(DateUtils.getMonthLastDate(now, "yyyy-MM-dd"), "yyyy-MM-dd"));
                lastQuery.setCheckTimeStart(DateUtils.getDateTime(DateUtils.getLastMonthFirstDate(now, "yyyy-MM-dd"), "yyyy-MM-dd"));
                lastQuery.setCheckTimeEnd(DateUtils.getDateTime(DateUtils.getLastMonthLastDate(now, "yyyy-MM-dd"), "yyyy-MM-dd"));
            }
            if (query.getSummaryType() == SummaryTopTypeEnum.日.getValue()) {
                query.setCheckTimeStart(DateUtils.getCurrStrDate());
                query.setCheckTimeEnd(DateUtils.getCurrStrDate());
                lastQuery.setCheckTimeStart(DateUtils.getDateTime(DateUtils.addDate(now, -1), "yyyy-MM-dd"));
                lastQuery.setCheckTimeEnd(DateUtils.getDateTime(DateUtils.addDate(now, -1), "yyyy-MM-dd"));
            }
            model.put("initScore", 0);
            model.put("checkScore", 0);
            model.put("checkPercent", "0%");
            model.put("appealPercent", "0%");
            model.put("appealScore", 0);
            model.put("total", 0);
            model.put("huanbi", "暂无环比");
            model.put("tongbi", "暂无同比");
            CheckAllScoreSummaryVo current = checkAllRecordService.getScoreSummary(query);
            NumberFormat numberFormat = NumberFormat.getPercentInstance();
            numberFormat.setMaximumFractionDigits(2);
            if (current != null) {
                model.put("initScore", current.getInitScore());
                model.put("checkScore", current.getCheckScore());
                model.put("appealScore", current.getAppealScore());
                model.put("total", current.getTotal());
                BigDecimal checkPercent = current.getCheckScore().divide(current.getInitScore(), 6, BigDecimal.ROUND_HALF_UP);
                model.put("checkPercent", numberFormat.format(checkPercent));
                BigDecimal appealPercent = current.getAppealScore().divide(current.getInitScore(), 6, BigDecimal.ROUND_HALF_UP);
                model.put("appealPercent", numberFormat.format(appealPercent));

                CheckAllScoreSummaryVo last = checkAllRecordService.getScoreSummary(lastQuery);
                if (last != null) {
                    BigDecimal huanbi = current.getTotal().subtract(last.getTotal());
                    huanbi = huanbi.divide(last.getTotal(), 6, BigDecimal.ROUND_HALF_UP);
                    model.put("huanbi", numberFormat.format(huanbi));
                }
                if (query.getSummaryType() == SummaryTopTypeEnum.年.getValue()) {
                    if (last != null) {
                        model.put("tongbi", model.get("huanbi"));
                    }
                } else {
                    String yyyy = query.getCheckTimeStart().substring(0, 4);
                    int lastyear = DataUtil.converStr2Int(yyyy, 0);
                    lastyear--;
                    if (query.getCheckTimeStart().substring(4).equals("-02-29")) {
                        lastQuery.setCheckTimeStart(lastyear + "-02-28");
                    } else {
                        lastQuery.setCheckTimeStart(lastyear + query.getCheckTimeStart().substring(4));
                    }
                    if (query.getCheckTimeEnd().substring(4).equals("-02-29")) {
                        lastQuery.setCheckTimeEnd(lastyear + "-02-28");
                    } else {
                        lastQuery.setCheckTimeEnd(lastyear + query.getCheckTimeEnd().substring(4));
                    }
                    CheckAllScoreSummaryVo tb = checkAllRecordService.getScoreSummary(lastQuery);
                    if (tb != null) {
                        BigDecimal tongbi = current.getTotal().subtract(tb.getTotal());
                        tongbi = tongbi.divide(last.getTotal(), 6, BigDecimal.ROUND_HALF_UP);
                        model.put("tongbi", numberFormat.format(tongbi));
                    }
                }
            }

            model.put("message_info", busiDesc + "成功");
            if (!ObjectUtils.isEmpty(context) && !ObjectUtils.isEmpty(context.getUser())) {
                this.recordSysLog(this.request, busiDesc + " 【成功】");
            }
        } catch (Exception var9) {
            code = -1;
            this.doException(this.request, busiDesc, model, var9);
        }

        ret.setCode(code);
        ret.setData(model);
        ret.setDict(model.get("dict"));
        ret.setMsg(model.get("message_info") == null ? "" : model.remove("message_info").toString());
        return ret;
    }

    public static void main(String[] args) {
        StaffCheckSummaryQuery query = new StaffCheckSummaryQuery();
        query.setCheckTimeStart("2023-02-01");
        query.setCheckTimeEnd("2023-02-29");
        StaffCheckSummaryQuery lastQuery = new StaffCheckSummaryQuery();
        String yyyy = query.getCheckTimeStart().substring(0, 4);
        String mmdd = query.getCheckTimeStart().substring(4);
        int lastyear = DataUtil.converStr2Int(yyyy, 0);
        lastyear--;
        if (query.getCheckTimeStart().substring(4).equals("-02-29")) {
            lastQuery.setCheckTimeStart(lastyear + "-02-28");
        } else {
            lastQuery.setCheckTimeStart(lastyear + query.getCheckTimeStart().substring(4));
        }
        if (query.getCheckTimeEnd().substring(4).equals("-02-29")) {
            lastQuery.setCheckTimeEnd(lastyear + "-02-28");
        } else {
            lastQuery.setCheckTimeEnd(lastyear + query.getCheckTimeEnd().substring(4));
        }
        System.out.println(JSONObject.toJSON(lastQuery).toString());
    }
}
