package com.mortals.xhx.busiz.h5.web;

import java.math.BigDecimal;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.common.Rest;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.Context;
import com.mortals.framework.model.PageInfo;
import com.mortals.framework.model.Result;
import com.mortals.xhx.busiz.h5.req.PerformReq;
import com.mortals.xhx.busiz.h5.rsp.PerformDetailInfo;
import com.mortals.xhx.busiz.h5.rsp.PerformInfo;
import com.mortals.xhx.busiz.h5.rsp.PerformStatInfo;
import com.mortals.xhx.common.code.*;
import com.mortals.xhx.common.utils.BeanUtil;
import com.mortals.xhx.module.check.dao.CheckAllRecordDao;
import com.mortals.xhx.module.check.model.*;
import com.mortals.xhx.module.check.model.vo.CheckAllRecordVo;
import com.mortals.xhx.module.check.service.*;
import com.mortals.xhx.module.perform.model.PerformAttendAppealEntity;
import com.mortals.xhx.module.perform.model.PerformAttendAppealQuery;
import com.mortals.xhx.module.perform.model.PerformRulesEntity;
import com.mortals.xhx.module.perform.service.PerformAttendAppealService;
import com.mortals.xhx.module.perform.service.PerformRulesService;
import com.mortals.xhx.module.staff.model.StaffPerformStatEntity;
import com.mortals.xhx.module.staff.model.StaffPerformStatQuery;
import com.mortals.xhx.module.staff.service.StaffPerformStatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.mortals.framework.ap.SysConstains.*;
import static com.mortals.xhx.common.key.ErrorCode.ERROR_TOKEN_EXPIRED;
import static com.mortals.xhx.common.key.ErrorCode.ERROR_TOKEN_EXPIRED_CONTENT;

/**
 * h5 绩效
 *
 * @author: zxfei
 * @date: 2023/7/7 13:20
 */
@RestController
@Slf4j
@RequestMapping("/api/v1/perform")
public class PerformApiController extends AbstractBaseController<PerformReq> {


    @Autowired
    private CheckAttendRecordService checkAttendRecordService;
    @Autowired
    private CheckReviewRecordService checkReviewRecordService;
    @Autowired
    private CheckComplainRecordService checkComplainRecordService;
    @Autowired
    private CheckEffectRecordService checkEffectRecordService;
    @Autowired
    private CheckGoworkRecordService checkGoworkRecordService;
    @Autowired
    private CheckOtherRecordService checkOtherRecordService;
    @Autowired
    private CheckAllRecordService checkAllRecordService;

    @Autowired
    private PerformAttendAppealService appealService;

    @Autowired
    private CheckAllRecordDao checkAllRecordDao;
    @Autowired
    private StaffPerformStatService staffPerformStatService;
    @Autowired
    private PerformRulesService rulesService;


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

    /**
     * 个人当天绩效统计
     */
    @PostMapping(value = "stat")
    public Rest<PerformStatInfo> performStat() {
        String busiDesc = "H5 个人绩效统计";
        Rest<PerformStatInfo> rest = Rest.ok(busiDesc + " 【成功】");
        Context context = this.getContext();

        if (ObjectUtils.isEmpty(context) || ObjectUtils.isEmpty(context.getUser())) {
            throw new AppException(ERROR_TOKEN_EXPIRED, ERROR_TOKEN_EXPIRED_CONTENT);
        }
        log.info("【{}】【请求体】--> 用户:{}", busiDesc, context.getUser().getRealName());
        try {
            CheckAllRecordQuery checkAllRecordQuery = new CheckAllRecordQuery();
            checkAllRecordQuery.setSubAddType(SubAddTypeEnum.扣除.getValue());
            checkAllRecordQuery.setStaffId(context.getUser().getCustomerId());
            int totalTimes = checkAllRecordDao.getCount(checkAllRecordQuery);

            checkAllRecordQuery.setCheckTimeStart(DateUtil.today());
            checkAllRecordQuery.setCheckTimeEnd(DateUtil.today());
            int todayTimes = checkAllRecordDao.getCount(checkAllRecordQuery);

            StaffPerformStatQuery staffPerformStatQuery = new StaffPerformStatQuery();
            staffPerformStatQuery.setStaffId(context.getUser().getCustomerId());
            staffPerformStatQuery.setYear(DateUtil.year(new Date()));
            staffPerformStatQuery.setMonth(DateUtil.month(new Date())+1);

            List<StaffPerformStatEntity> staffPerformStatEntities = staffPerformStatService.find(staffPerformStatQuery);
            BigDecimal totalScore=new BigDecimal(0.0);
            if(ObjectUtils.isEmpty(staffPerformStatEntities)){
                totalScore = staffPerformStatEntities.stream().map(item -> item.getTotalSubScore()).reduce(BigDecimal.ZERO, BigDecimal::add);
            }

            staffPerformStatQuery.setDay(DateUtil.dayOfMonth(new Date()));
            //今日得分
            StaffPerformStatEntity staffPerformStatEntity = staffPerformStatService.selectOne(staffPerformStatQuery);

            BigDecimal todayScore=new BigDecimal(0.0);
            if(!ObjectUtils.isEmpty(staffPerformStatEntity)){
             todayScore=staffPerformStatEntity.getTotalSubScore();
            }

            PerformStatInfo performStatInfo = new PerformStatInfo();
            performStatInfo.setTotalScore(totalScore.setScale(1, BigDecimal.ROUND_HALF_UP));
            performStatInfo.setTotalTimes(totalTimes);
            performStatInfo.setTodayScore(todayScore.setScale(1, BigDecimal.ROUND_HALF_UP));
            performStatInfo.setTodayTimes(todayTimes);
            rest.setData(performStatInfo);
            recordSysLog(request, busiDesc + " 【成功】");
        } catch (Exception e) {
            log.error(busiDesc, e);
            rest = Rest.fail(super.convertException(e));
        }
        return rest;
    }


    /**
     * 个人当月绩效加分扣分列表
     */
    @PostMapping(value = "list")
    public Rest<Object> performList(@RequestBody PerformReq performReq) {
        String busiDesc = "个人绩效列表";
        log.info("【{}】【请求体】--> {}", busiDesc, JSONObject.toJSONString(performReq));
        Rest<Object> rest = Rest.ok();
        Map<String, Object> model = new HashMap<>();
        Context context = this.getContext();

        if (ObjectUtils.isEmpty(context) || ObjectUtils.isEmpty(context.getUser())) {
            throw new AppException(ERROR_TOKEN_EXPIRED, ERROR_TOKEN_EXPIRED_CONTENT);
        }
        try {
            if (ObjectUtils.isEmpty(performReq.getPerformStartDate())) {
                //未设置时间的情况，默认为当月
                performReq.setPerformStartDate(DateUtil.beginOfMonth(new Date()).toDateStr());
                performReq.setPerformEndDate(DateUtil.today());
            } else {
                performReq.setPerformStartDate(DateUtil.beginOfMonth(DateUtil.parse(performReq.getPerformStartDate()).toJdkDate()).toDateStr());
                performReq.setPerformEndDate(DateUtil.endOfMonth(DateUtil.parse(performReq.getPerformStartDate()).toJdkDate()).toDateStr());
            }
            PageInfo pageInfo = buildPageInfo(performReq);
            //todo 查询全部扣分绩效
            if (PerformTypeEnum.全部.getValue().equals(performReq.getPerformType())) {
                CheckAllRecordQuery query = new CheckAllRecordQuery();
                query.setCheckTimeStart(performReq.getPerformStartDate());
                query.setCheckTimeEnd(performReq.getPerformEndDate());
                query.setStaffId(context.getUser().getCustomerId());

                Result<CheckAllRecordVo> result = checkAllRecordService.getAllCheckRecord(query, pageInfo);
                List<CheckAllRecordVo> allCheckRecord = result.getList();
                List<PerformInfo> collect = allCheckRecord.stream().map(item -> {
                    PerformInfo performInfo = new PerformInfo();
                    BeanUtils.copyProperties(item, performInfo, BeanUtil.getNullPropertyNames(item));
                    return performInfo;
                }).collect(Collectors.toList());
                model.put(KEY_RESULT_DATA, collect);
                model.put(PAGEINFO_KEY, result.getPageInfo());
                parsePageInfo(model, result.getPageInfo());

            } else if (PerformTypeEnum.考勤绩效.getValue().equals(performReq.getPerformType())) {
                CheckAttendRecordQuery query = new CheckAttendRecordQuery();
                query.setCheckTimeStart(performReq.getPerformStartDate());
                query.setCheckTimeEnd(performReq.getPerformEndDate());
                query.setStaffId(context.getUser().getCustomerId());

                Result<CheckAttendRecordEntity> result = checkAttendRecordService.find(query, pageInfo, context);
                List<PerformInfo> collect = result.getList().stream().map(item -> {
                    PerformInfo performInfo = new PerformInfo();
                    BeanUtils.copyProperties(item, performInfo, BeanUtil.getNullPropertyNames(item));
                    performInfo.setPerformType(PerformTypeEnum.考勤绩效.getValue());
                    //判断是否存在申诉
                    PerformAttendAppealEntity entity = appealService.selectOne(new PerformAttendAppealQuery().checkRecordId(item.getId()));
                    if (!ObjectUtils.isEmpty(entity)) {
                        Boolean bool = entity.newEntity();
                        updateAppealStatus(performInfo, bool, entity.getProcessStatus(), entity.getAppealResult());
                    } else {
                        performInfo.setAppealStatus(AppealStatusEnum.未申诉.getValue());
                    }
                    return performInfo;
                }).collect(Collectors.toList());

                model.put(KEY_RESULT_DATA, collect);
                model.put(PAGEINFO_KEY, result.getPageInfo());
                parsePageInfo(model, result.getPageInfo());
            } else if (PerformTypeEnum.评价差评绩效.getValue().equals(performReq.getPerformType())) {
                CheckReviewRecordQuery query = new CheckReviewRecordQuery();
                query.setCheckTimeStart(performReq.getPerformStartDate());
                query.setCheckTimeEnd(performReq.getPerformEndDate());
                query.setStaffId(context.getUser().getCustomerId());

                Result<CheckReviewRecordEntity> result = checkReviewRecordService.find(query, pageInfo, context);
                List<PerformInfo> collect = result.getList().stream().map(item -> {
                    PerformInfo performInfo = new PerformInfo();
                    BeanUtils.copyProperties(item, performInfo, BeanUtil.getNullPropertyNames(item));
                    performInfo.setPerformType(PerformTypeEnum.评价差评绩效.getValue());
                    //判断是否存在申诉
                    PerformAttendAppealEntity entity = appealService.selectOne(new PerformAttendAppealQuery().checkRecordId(item.getId()));

                    if (!ObjectUtils.isEmpty(entity)) {
                        Boolean bool = entity.newEntity();
                        updateAppealStatus(performInfo, bool, entity.getProcessStatus(), entity.getAppealResult());
                    } else {
                        performInfo.setAppealStatus(AppealStatusEnum.未申诉.getValue());
                    }
                    return performInfo;
                }).collect(Collectors.toList());
                model.put(KEY_RESULT_DATA, collect);
                model.put(PAGEINFO_KEY, result.getPageInfo());
                parsePageInfo(model, result.getPageInfo());
            } else if (PerformTypeEnum.评价投诉绩效.getValue().equals(performReq.getPerformType())) {
                CheckComplainRecordQuery query = new CheckComplainRecordQuery();
                query.setCheckTimeStart(performReq.getPerformStartDate());
                query.setCheckTimeEnd(performReq.getPerformEndDate());
                query.setStaffId(context.getUser().getCustomerId());

                Result<CheckComplainRecordEntity> result = checkComplainRecordService.find(query, pageInfo, context);
                List<PerformInfo> collect = result.getList().stream().map(item -> {
                    PerformInfo performInfo = new PerformInfo();
                    BeanUtils.copyProperties(item, performInfo, BeanUtil.getNullPropertyNames(item));
                    performInfo.setPerformType(PerformTypeEnum.评价投诉绩效.getValue());

                    //判断是否存在申诉
                    PerformAttendAppealEntity entity = appealService.selectOne(new PerformAttendAppealQuery().checkRecordId(item.getId()));
                    if (!ObjectUtils.isEmpty(entity)) {
                        Boolean bool = entity.newEntity();
                        updateAppealStatus(performInfo, bool, entity.getProcessStatus(), entity.getAppealResult());
                    } else {
                        performInfo.setAppealStatus(AppealStatusEnum.未申诉.getValue());
                    }
                    return performInfo;
                }).collect(Collectors.toList());
                model.put(KEY_RESULT_DATA, collect);
                model.put(PAGEINFO_KEY, result.getPageInfo());
                parsePageInfo(model, result.getPageInfo());
            } else if (PerformTypeEnum.办件绩效.getValue().equals(performReq.getPerformType())) {
                CheckGoworkRecordQuery query = new CheckGoworkRecordQuery();
                query.setCheckTimeStart(performReq.getPerformStartDate());
                query.setCheckTimeEnd(performReq.getPerformEndDate());
                query.setStaffId(context.getUser().getCustomerId());

                Result<CheckGoworkRecordEntity> result = checkGoworkRecordService.find(query, pageInfo, context);
                List<PerformInfo> collect = result.getList().stream().map(item -> {
                    PerformInfo performInfo = new PerformInfo();
                    BeanUtils.copyProperties(item, performInfo, BeanUtil.getNullPropertyNames(item));
                    performInfo.setPerformType(PerformTypeEnum.办件绩效.getValue());
                    //判断是否存在申诉
                    PerformAttendAppealEntity entity = appealService.selectOne(new PerformAttendAppealQuery().checkRecordId(item.getId()));

                    if (!ObjectUtils.isEmpty(entity)) {
                        Boolean bool = entity.newEntity();
                        updateAppealStatus(performInfo, bool, entity.getProcessStatus(), entity.getAppealResult());
                    } else {
                        performInfo.setAppealStatus(AppealStatusEnum.未申诉.getValue());
                    }

                    return performInfo;
                }).collect(Collectors.toList());
                model.put(KEY_RESULT_DATA, collect);
                model.put(PAGEINFO_KEY, result.getPageInfo());
                parsePageInfo(model, result.getPageInfo());
            } else if (PerformTypeEnum.效能绩效.getValue().equals(performReq.getPerformType())) {
                CheckEffectRecordQuery query = new CheckEffectRecordQuery();
                query.setCheckTimeStart(performReq.getPerformStartDate());
                query.setCheckTimeEnd(performReq.getPerformEndDate());
                query.setStaffId(context.getUser().getCustomerId());

                Result<CheckEffectRecordEntity> result = checkEffectRecordService.find(query, pageInfo, context);
                List<PerformInfo> collect = result.getList().stream().map(item -> {
                    PerformInfo performInfo = new PerformInfo();
                    BeanUtils.copyProperties(item, performInfo, BeanUtil.getNullPropertyNames(item));
                    performInfo.setPerformType(PerformTypeEnum.效能绩效.getValue());
                    //判断是否存在申诉
                    PerformAttendAppealEntity entity = appealService.selectOne(new PerformAttendAppealQuery().checkRecordId(item.getId()));
                    if (!ObjectUtils.isEmpty(entity)) {
                        Boolean bool = entity.newEntity();
                        updateAppealStatus(performInfo, bool, entity.getProcessStatus(), entity.getAppealResult());
                    } else {
                        performInfo.setAppealStatus(AppealStatusEnum.未申诉.getValue());
                    }
                    return performInfo;
                }).collect(Collectors.toList());
                model.put(KEY_RESULT_DATA, collect);
                model.put(PAGEINFO_KEY, result.getPageInfo());
                parsePageInfo(model, result.getPageInfo());
            } else if (PerformTypeEnum.其它绩效.getValue().equals(performReq.getPerformType())) {
                CheckOtherRecordQuery query = new CheckOtherRecordQuery();
                query.setCheckTimeStart(performReq.getPerformStartDate());
                query.setCheckTimeEnd(performReq.getPerformEndDate());
                query.setStaffId(context.getUser().getCustomerId());

                Result<CheckOtherRecordEntity> result = checkOtherRecordService.find(query, pageInfo, context);
                List<PerformInfo> collect = result.getList().stream().map(item -> {
                    PerformInfo performInfo = new PerformInfo();
                    BeanUtils.copyProperties(item, performInfo, BeanUtil.getNullPropertyNames(item));
                    performInfo.setPerformType(PerformTypeEnum.其它绩效.getValue());
                    //判断是否存在申诉
                    PerformAttendAppealEntity entity = appealService.selectOne(new PerformAttendAppealQuery().checkRecordId(item.getId()));

                    if (!ObjectUtils.isEmpty(entity)) {
                        Boolean bool = entity.newEntity();
                        updateAppealStatus(performInfo, bool, entity.getProcessStatus(), entity.getAppealResult());
                    } else {
                        performInfo.setAppealStatus(AppealStatusEnum.未申诉.getValue());
                    }
                    return performInfo;
                }).collect(Collectors.toList());
                model.put(KEY_RESULT_DATA, collect);
                model.put(PAGEINFO_KEY, result.getPageInfo());
                parsePageInfo(model, result.getPageInfo());
            } else {
                throw new AppException("不支持当前绩效类型");
            }

            rest.setData(model);
            recordSysLog(request, busiDesc + " 【成功】");
        } catch (Exception e) {
            log.error(busiDesc, e);
            rest = Rest.fail(super.convertException(e));
        }

        this.init(model, context);
        return rest;
    }

    private void updateAppealStatus(PerformInfo performInfo, Boolean bool, Integer processStatus, Integer appealResult) {
        if (!bool) {
            performInfo.setAppealStatus(AppealStatusEnum.未申诉.getValue());
        } else {
            if (ProcessStatusEnum.未处理.getValue() == processStatus) {
                performInfo.setAppealStatus(AppealStatusEnum.申诉中.getValue());
            } else {
                if (AppealResultEnum.通过.getValue() == appealResult) {
                    performInfo.setAppealStatus(AppealStatusEnum.申诉通过.getValue());
                } else if (AppealResultEnum.不通过.getValue() == appealResult) {
                    performInfo.setAppealStatus(AppealStatusEnum.申诉拒绝.getValue());
                }
            }
        }
    }


    /**
     * 详细
     */
    @PostMapping(value = "info")
    public Rest<PerformDetailInfo> performInfo(@RequestBody PerformReq performReq) {
        Context context = this.getContext();
        Map<String, Object> model = new HashMap<>();
        String busiDesc = "个人绩效增减详细";
        log.info("【{}】【请求体】--> {}", busiDesc, JSONObject.toJSONString(performReq));
        Rest<PerformDetailInfo> rest = Rest.ok(busiDesc + " 【成功】");
        try {
            if (ObjectUtils.isEmpty(performReq.getId())) {
                throw new AppException("详细查询id不能为空!");
            }
            //todo 查询全部扣分绩效详细
            PerformDetailInfo performDetailInfo = new PerformDetailInfo();
            if (PerformTypeEnum.考勤绩效.getValue().equals(performReq.getPerformType())) {
                CheckAttendRecordEntity checkEntity = checkAttendRecordService.get(performReq.getId(), context);
                BeanUtils.copyProperties(checkEntity, performDetailInfo, BeanUtil.getNullPropertyNames(checkEntity));
            } else if (PerformTypeEnum.评价差评绩效.getValue().equals(performReq.getPerformType())) {
                CheckReviewRecordEntity checkEntity = checkReviewRecordService.get(performReq.getId(), context);
                BeanUtils.copyProperties(checkEntity, performDetailInfo, BeanUtil.getNullPropertyNames(checkEntity));
            } else if (PerformTypeEnum.评价投诉绩效.getValue().equals(performReq.getPerformType())) {
                CheckComplainRecordEntity checkEntity = checkComplainRecordService.get(performReq.getId(), context);
                BeanUtils.copyProperties(checkEntity, performDetailInfo, BeanUtil.getNullPropertyNames(checkEntity));
            } else if (PerformTypeEnum.办件绩效.getValue().equals(performReq.getPerformType())) {
                CheckGoworkRecordEntity checkEntity = checkGoworkRecordService.get(performReq.getId(), context);
                BeanUtils.copyProperties(checkEntity, performDetailInfo, BeanUtil.getNullPropertyNames(checkEntity));
            } else if (PerformTypeEnum.效能绩效.getValue().equals(performReq.getPerformType())) {
                CheckEffectRecordEntity checkEntity = checkEffectRecordService.get(performReq.getId(), context);
                BeanUtils.copyProperties(checkEntity, performDetailInfo, BeanUtil.getNullPropertyNames(checkEntity));
            } else if (PerformTypeEnum.其它绩效.getValue().equals(performReq.getPerformType())) {
                CheckOtherRecordEntity checkEntity = checkOtherRecordService.get(performReq.getId(), context);
                BeanUtils.copyProperties(checkEntity, performDetailInfo, BeanUtil.getNullPropertyNames(checkEntity));
            } else {
                throw new AppException("不支持当前绩效类型");
            }

            PerformAttendAppealEntity appealEntity = appealService.selectOne(new PerformAttendAppealQuery().checkRecordId(performDetailInfo.getId()));
            if (ObjectUtils.isEmpty(appealEntity)) {
                performDetailInfo.setAppealStatus(AppealStatusEnum.未申诉.getValue());
            } else {
                if (ProcessStatusEnum.未处理.getValue() == appealEntity.getProcessStatus()) {
                    performDetailInfo.setAppealStatus(AppealStatusEnum.申诉中.getValue());
                } else {
                    if (AppealResultEnum.通过.getValue() == appealEntity.getProcessStatus()) {
                        performDetailInfo.setAppealStatus(AppealStatusEnum.申诉通过.getValue());
                    } else if (AppealResultEnum.不通过.getValue() == appealEntity.getProcessStatus()) {
                        performDetailInfo.setAppealStatus(AppealStatusEnum.申诉拒绝.getValue());
                    }
                }
            }

            PerformRulesEntity rulesEntity = rulesService.getCache(performDetailInfo.getRuleId().toString());

            performDetailInfo.setRuleDesc(rulesEntity.getContent());

            rest.setData(performDetailInfo);
            log.info("rspperformDetailInfo:{}", JSON.toJSONString(performDetailInfo));

            this.init(model, context);
            rest.setDict(model.get("dict"));

            recordSysLog(request, busiDesc + " 【成功】");
        } catch (Exception e) {
            log.error(busiDesc, e);
            rest = Rest.fail(super.convertException(e));
        }
        return rest;
    }


    public static void main(String[] args) {

    }


}
