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.common.code.*;
import com.mortals.xhx.common.utils.BeanUtil;
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 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.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

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 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 {
            //todo 查询当前登录人的绩效分数
            AppealStatInfo appealStatInfo = new AppealStatInfo();
            appealStatInfo.setTotalScore(new BigDecimal("10.52").setScale(1,BigDecimal.ROUND_HALF_UP));
            appealStatInfo.setTotalTimes(12);
            appealStatInfo.setTodayScore(new BigDecimal("2.5").setScale(1,BigDecimal.ROUND_HALF_UP));
            appealStatInfo.setTodayTimes(3);
            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());
    }

}
