package com.mortals.xhx.busiz.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.PageInfo;
import com.mortals.framework.model.Result;
import com.mortals.framework.web.BaseJsonBodyController;
import com.mortals.xhx.busiz.req.AppealReq;
import com.mortals.xhx.busiz.req.PerformReq;
import com.mortals.xhx.busiz.rsp.AppealStatInfo;
import com.mortals.xhx.busiz.rsp.PerformDetailInfo;
import com.mortals.xhx.busiz.rsp.PerformInfo;
import com.mortals.xhx.busiz.rsp.PerformStatInfo;
import com.mortals.xhx.common.code.PerformTypeEnum;
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.checkerframework.checker.units.qual.A;
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.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 15:08
 */
@RestController
@Slf4j
@RequestMapping("/api/v1/appeal")
public class AppealApiController extends AbstractBaseController<PerformReq> {

    @Autowired
    private PerformAttendAppealService attendAppealService;

    /**
     * 个人申诉绩效统计
     */
    @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"));
            appealStatInfo.setTotalTimes(12);
            appealStatInfo.setTodayScore(new BigDecimal("2.5"));
            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());
            }
            PageInfo pageInfo = buildPageInfo(appealReq);
            PerformAttendAppealQuery query = new PerformAttendAppealQuery();
            query.setAppealTimeStart(appealReq.getApperalStartDate());
            query.setAppealTimeEnd(appealReq.getAppealEndDate());
            query.setStaffId(context.getUser().getCustomerId());

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

            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();
        try {
            if (ObjectUtils.isEmpty(appealReq.getId())) {
                throw new AppException("详细查询id不能为空!");
            }
            PerformAttendAppealEntity performAttendAppealEntity = attendAppealService.get(appealReq.getId(), context);
            rest.setData(performAttendAppealEntity);

            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 PerformAttendAppealEntity appealEntity) {
        String busiDesc = "个人申诉新增";
        log.info("【{}】【请求体】--> {}", busiDesc, JSONObject.toJSONString(appealEntity));
        Rest<PerformAttendAppealEntity> rest = Rest.ok(busiDesc + " 【成功】");
        Context context = this.getContext();
        try {
            //校验 去重
            PerformAttendAppealEntity saveEntity = attendAppealService.save(appealEntity, 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(appealEntity));
        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) {

    }

}
