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

import java.math.BigDecimal;


import cn.hutool.core.date.DateUtil;
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.OrderCol;
import com.mortals.framework.model.PageInfo;
import com.mortals.framework.model.Result;
import com.mortals.xhx.busiz.h5.req.AppealReq;
import com.mortals.xhx.busiz.h5.req.PerformReq;
import com.mortals.xhx.busiz.h5.rsp.AppealStatInfo;
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.service.*;
import com.mortals.xhx.module.perform.model.PerformAttendAppealEntity;
import com.mortals.xhx.module.perform.model.PerformAttendAppealQuery;
import com.mortals.xhx.module.perform.service.PerformAttendAppealService;
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.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

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 15:08
 */
@RestController
@Slf4j
@RequestMapping("/api/v1/appeal")
public class AppealApiController 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 CheckAllRecordDao checkAllRecordDao;
    @Autowired
    private StaffPerformStatService staffPerformStatService;

    @Autowired
    private PerformAttendAppealService appealService;

    protected void init(Map<String, Object> model, Context context) {
        this.addDict(model, "checkStatus", CheckStatusEnum.getEnumMap());
        this.addDict(model, "checkResult", CheckResultEnum.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<AppealStatInfo> appealStat() {
        String busiDesc = "H5个人申诉绩效统计";
        Rest<AppealStatInfo> 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();
            }

            AppealStatInfo appealStatInfo = new AppealStatInfo();
            appealStatInfo.setTotalScore(totalScore.setScale(1, BigDecimal.ROUND_HALF_UP));
            appealStatInfo.setTotalTimes(totalTimes);
            appealStatInfo.setTodayScore(todayScore.setScale(1, BigDecimal.ROUND_HALF_UP));
            appealStatInfo.setTodayTimes(todayTimes);
            rest.setData(appealStatInfo);


            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 AppealReq appealReq) {
        String busiDesc = "个人申诉列表";
        log.info("【{}】【请求体】--> {}", busiDesc, JSONObject.toJSONString(appealReq));
        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(appealReq.getApperalStartDate())) {
                //未设置时间的情况，默认为当月
                appealReq.setApperalStartDate(DateUtil.beginOfMonth(new Date()).toDateStr());
                appealReq.setAppealEndDate(DateUtil.today());
            } else {
                //格式化到指定日期的当月
                appealReq.setApperalStartDate(DateUtil.beginOfMonth(DateUtil.parse(appealReq.getApperalStartDate()).toJdkDate()).toDateStr());
                appealReq.setAppealEndDate(DateUtil.endOfMonth(DateUtil.parse(appealReq.getApperalStartDate()).toJdkDate()).toDateStr());
            }
            PageInfo pageInfo = buildPageInfo(appealReq);
            PerformAttendAppealQuery query = new PerformAttendAppealQuery();
            query.setCreateTimeStart(appealReq.getApperalStartDate());
            query.setCreateTimeEnd(appealReq.getAppealEndDate());
            query.setStaffId(context.getUser().getCustomerId());
            query.setOrderColList(Arrays.asList(new OrderCol("createTime",OrderCol.DESCENDING)));

            Result<PerformAttendAppealEntity> result = appealService.find(query, pageInfo, context);
            model.put(KEY_RESULT_DATA, result.getList());
            model.put(PAGEINFO_KEY, result.getPageInfo());
            parsePageInfo(model, result.getPageInfo());

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


    /**
     * 申诉详细
     */
    @PostMapping(value = "info")
    public Rest<PerformAttendAppealEntity> appealInfo(@RequestBody AppealReq appealReq) {
        String busiDesc = "个人申诉详细";
        log.info("【{}】【请求体】--> {}", busiDesc, JSONObject.toJSONString(appealReq));
        Rest<PerformAttendAppealEntity> rest = Rest.ok(busiDesc + " 【成功】");
        Context context = this.getContext();
        Map<String, Object> model = new HashMap<>();
        try {
            if (ObjectUtils.isEmpty(appealReq.getId())) {
                throw new AppException("详细查询id不能为空!");
            }
            PerformAttendAppealEntity performAttendAppealEntity = appealService.get(appealReq.getId(), context);
            rest.setData(performAttendAppealEntity);
            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;
    }


    /**
     * 申诉新增
     */
    @PostMapping(value = "save")
    public Rest<PerformAttendAppealEntity> appealSave(@RequestBody AppealReq req) {
        String busiDesc = "个人申诉新增";
        log.info("【{}】【请求体】--> {}", busiDesc, JSONObject.toJSONString(req));
        Rest<PerformAttendAppealEntity> rest = Rest.ok(busiDesc + " 【成功】");
        Context context = this.getContext();
        try {
            if (ObjectUtils.isEmpty(context) || ObjectUtils.isEmpty(context.getUser())) {
                throw new AppException(ERROR_TOKEN_EXPIRED, ERROR_TOKEN_EXPIRED_CONTENT);
            }
            //根据状态 查询 当前是否已经存在正在进行的申诉
            if (ObjectUtils.isEmpty(req.getId())) throw new AppException("核查记录Id不能为空！");
            if (ObjectUtils.isEmpty(req.getPerformType())) throw new AppException("绩效类型不能为空！");
            //查询当前核查是否已存在进行中的申诉记录
            PerformAttendAppealEntity appealEntity = appealService.selectOne(new PerformAttendAppealQuery().checkRecordId(req.getId()).performType(req.getPerformType()));
            if (!ObjectUtils.isEmpty(appealEntity) && appealEntity.getProcessStatus() == ProcessStatusEnum.未处理.getValue()) {
                throw new AppException("当前绩效核查已经存在正在进行中的申诉记录！");
            }
            PerformAttendAppealEntity entity = new PerformAttendAppealEntity();
            entity.initAttrValue();

            if (PerformTypeEnum.考勤绩效.getValue().equals(req.getPerformType())) {
                CheckAttendRecordEntity checkEntity = checkAttendRecordService.get(req.getId(), context);
                BeanUtils.copyProperties(checkEntity, entity, BeanUtil.getNullPropertyNames(checkEntity));

            } else if (PerformTypeEnum.评价差评绩效.getValue().equals(req.getPerformType())) {
                CheckReviewRecordEntity checkEntity = checkReviewRecordService.get(req.getId(), context);
                BeanUtils.copyProperties(checkEntity, entity, BeanUtil.getNullPropertyNames(checkEntity));

            } else if (PerformTypeEnum.评价投诉绩效.getValue().equals(req.getPerformType())) {
                CheckComplainRecordEntity checkEntity = checkComplainRecordService.get(req.getId(), context);
                BeanUtils.copyProperties(checkEntity, entity, BeanUtil.getNullPropertyNames(checkEntity));

            } else if (PerformTypeEnum.办件绩效.getValue().equals(req.getPerformType())) {
                CheckGoworkRecordEntity checkEntity = checkGoworkRecordService.get(req.getId(), context);
                BeanUtils.copyProperties(checkEntity, entity, BeanUtil.getNullPropertyNames(checkEntity));

            } else if (PerformTypeEnum.效能绩效.getValue().equals(req.getPerformType())) {
                CheckEffectRecordEntity checkEntity = checkEffectRecordService.get(req.getId(), context);
                BeanUtils.copyProperties(checkEntity, entity, BeanUtil.getNullPropertyNames(checkEntity));

            } else if (PerformTypeEnum.其它绩效.getValue().equals(req.getPerformType())) {
                CheckOtherRecordEntity checkEntity = checkOtherRecordService.get(req.getId(), context);
                BeanUtils.copyProperties(checkEntity, entity, BeanUtil.getNullPropertyNames(checkEntity));

            } else {
                throw new AppException("不支持当前绩效类型");
            }
            entity.setPerformType(req.getPerformType());
            entity.setPerformAttendAppealFilesList(req.getPerformAttendAppealFilesList());
            entity.setProcessStatus(1);
            entity.setAppealDesc(req.getAppealDesc());
            entity.setStaffId(context.getUser().getCustomerId());
            entity.setCreateUserId(context.getUser().getId());
            entity.setCheckRecordId(req.getId());
            entity.setAppealTime(new Date());

            PerformAttendAppealEntity saveEntity = appealService.save(entity, context);
            rest.setData(saveEntity);
            recordSysLog(request, busiDesc + " 【成功】");
        } catch (Exception e) {
            log.error(busiDesc, e);
            rest = Rest.fail(super.convertException(e));
        }
        log.info("【{}】【响应体】--> {}", busiDesc, JSONObject.toJSONString(req));
        return rest;
    }


    protected PageInfo buildPageInfo(AppealReq query) {
        PageInfo pageInfo = new PageInfo();
        if (!ObjectUtils.isEmpty(query) && !ObjectUtils.isEmpty(query.getPage())) {
            pageInfo.setCurrPage(query.getPage());
        }

        if (!ObjectUtils.isEmpty(query) && !ObjectUtils.isEmpty(query.getSize())) {
            pageInfo.setPrePageResult(query.getSize());
        }

        return pageInfo;
    }


    protected void parsePageInfo(Map<String, Object> model, PageInfo pageInfo) {
        model.put(TOTAL, pageInfo.getTotalResult());
        model.put(PER_PAGE, pageInfo.getPrePageResult());
        model.put(CURRENT_PAGE, pageInfo.getCurrPage());
        model.put(LAST_PAGE, pageInfo.getTotalPage());
        model.put(PAGEINFO_KEY, pageInfo);
    }


    public static void main(String[] args) {
        System.out.println(new BigDecimal(15.52).setScale(1,BigDecimal.ROUND_HALF_UP).toString());
    }

}
