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

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
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.InspectSaveReq;
import com.mortals.xhx.busiz.h5.req.PerformReq;
import com.mortals.xhx.busiz.h5.rsp.InspectStatInfo;
import com.mortals.xhx.busiz.h5.rsp.PerformDetailInfo;
import com.mortals.xhx.busiz.h5.rsp.PerformInfo;
import com.mortals.xhx.common.code.*;
import com.mortals.xhx.common.utils.BeanUtil;
import com.mortals.xhx.module.attendance.model.*;
import com.mortals.xhx.module.attendance.service.AttendanceClassDetailService;
import com.mortals.xhx.module.attendance.service.AttendanceClassService;
import com.mortals.xhx.module.attendance.service.AttendanceGroupFixedworkService;
import com.mortals.xhx.module.attendance.service.AttendanceGroupService;
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.*;
import com.mortals.xhx.module.perform.service.*;
import com.mortals.xhx.module.staff.model.StaffEntity;
import com.mortals.xhx.module.staff.service.StaffPerformStatService;
import com.mortals.xhx.module.staff.service.StaffService;
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 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/inspect")
public class InspectApiController extends AbstractBaseController<PerformReq> {

    @Autowired
    private PerformAttendRecordService attendRecordService;
    @Autowired
    private PerformReviewRecordService reviewRecordService;
    @Autowired
    private PerformComplainRecordService complainRecordService;
    @Autowired
    private PerformGoworkRecordService performGoworkRecordService;
    @Autowired
    private PerformEffectRecordService effectRecordService;
    @Autowired
    private PerformOtherRecordService otherRecordService;
    @Autowired
    private PerformRulesService rulesService;
    @Autowired
    private StaffService staffService;
    @Autowired
    private CheckAllRecordService checkAllRecordService;
    @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 AttendanceGroupService groupService;
    @Autowired
    private AttendanceClassService classService;
    @Autowired
    private AttendanceClassDetailService classDetailService;
    @Autowired
    private AttendanceGroupFixedworkService fixedworkService;

    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());
        this.addDict(model, "irregularOtherType", IrregularOtherTypeEnum.getEnumMap());

    }

    /**
     * 个人巡查效统计
     */
    @PostMapping(value = "stat")
    public Rest<InspectStatInfo> inspectStat() {
        String busiDesc = "H5 个人巡查统计";
        Rest<InspectStatInfo> 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 {
            Integer totalTimes = 0;
            Integer todayTimes = 0;
            CheckAllRecordQuery checkAllRecordQuery = new CheckAllRecordQuery();
            checkAllRecordQuery.setSubMethod(SubMethodEnum.大厅巡查.getValue());
            checkAllRecordQuery.setCreateUserId(context.getUser().getId());
            totalTimes = checkAllRecordDao.getCount(checkAllRecordQuery);

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

            InspectStatInfo performStatInfo = new InspectStatInfo();
            performStatInfo.setTotalTimes(totalTimes);
            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());
            }
            CheckAllRecordQuery query = new CheckAllRecordQuery();
            query.setCreateTimeStart(performReq.getPerformStartDate());
            query.setCreateTimeEnd(performReq.getPerformEndDate());
            query.setCreateUserId(context.getUser().getId());
            query.setSubMethod(SubMethodEnum.大厅巡查.getValue());
            query.setOrderColList(Arrays.asList(new OrderCol("createTime",OrderCol.DESCENDING)));

            log.info("inspect query:{}",JSONObject.toJSONString(query));

            PageInfo pageInfo = buildPageInfo(performReq);

            if (PerformTypeEnum.全部.getValue().equals(performReq.getPerformType())) {
                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));

                    if (CheckStatusEnum.未处理.getValue() == item.getCheckStatus()) {
                        performInfo.setResult("待处理");
                    } else {
                        performInfo.setResult(item.getCheckResult());
                    }
                    return performInfo;
                }).collect(Collectors.toList());
                model.put(KEY_RESULT_DATA, collect);
                model.put(PAGEINFO_KEY, result.getPageInfo());
                parsePageInfo(model, result.getPageInfo());

            }
            if (!ObjectUtils.isEmpty(performReq.getProcessStatus())) {
                query.setCheckStatus(performReq.getProcessStatus());
                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));

                    if (CheckStatusEnum.未处理.getValue() == item.getCheckStatus()) {
                        performInfo.setResult("待处理");
                    } else {
                        performInfo.setResult(item.getCheckResult());
                    }
                    return performInfo;
                }).collect(Collectors.toList());
                model.put(KEY_RESULT_DATA, collect);
                model.put(PAGEINFO_KEY, result.getPageInfo());
                parsePageInfo(model, result.getPageInfo());
            }
            if (!ObjectUtils.isEmpty(performReq.getScoreType())) {
                query.setSubAddType(performReq.getScoreType());
                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));

                    if (CheckStatusEnum.未处理.getValue() == item.getCheckStatus()) {
                        performInfo.setResult("待处理");
                    } else {
                        performInfo.setResult(item.getCheckResult());
                    }
                    return performInfo;
                }).collect(Collectors.toList());
                model.put(KEY_RESULT_DATA, collect);
                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 = "save")
    public Rest<PerformAttendAppealEntity> appealSave(@RequestBody InspectSaveReq req) {
        String busiDesc = "个人巡查记录新增";
        log.info("【{}】【请求体】--> {}", busiDesc, JSONObject.toJSONString(req));
        Rest<PerformAttendAppealEntity> rest = Rest.ok(busiDesc + " 【成功】");
        Context context = this.getContext();
        // req.setStaffId(context.getUser().getCustomerId());
        try {
            //根据状态 查询 当前是否已经存在正在进行的申诉
            if (ObjectUtils.isEmpty(context) || ObjectUtils.isEmpty(context.getUser())) {
                throw new AppException(ERROR_TOKEN_EXPIRED, ERROR_TOKEN_EXPIRED_CONTENT);
            }
            if (ObjectUtils.isEmpty(req.getPerformType())) throw new AppException("绩效类型不能为空！");

            if (PerformTypeEnum.考勤绩效.getValue().equals(req.getPerformType())) {
                boolean bool = attend(req, context);
                if (bool) throw new AppException(busiDesc + "失败！");
            } else if (PerformTypeEnum.评价差评绩效.getValue().equals(req.getPerformType())) {
                boolean bool = review(req, context);
                if (bool) throw new AppException(busiDesc + "失败！");
            } else if (PerformTypeEnum.评价投诉绩效.getValue().equals(req.getPerformType())) {
                boolean bool = complain(req, context);
                if (bool) throw new AppException(busiDesc + "失败！");
            } else if (PerformTypeEnum.办件绩效.getValue().equals(req.getPerformType())) {
                boolean bool = gowork(req, context);
                if (bool) throw new AppException(busiDesc + "失败！");
            } else if (PerformTypeEnum.效能绩效.getValue().equals(req.getPerformType())) {
                boolean bool = effect(req, context);
                if (bool) throw new AppException(busiDesc + "失败！");
            } else if (PerformTypeEnum.其它绩效.getValue().equals(req.getPerformType())) {
                boolean bool = other(req, context);
                if (bool) throw new AppException(busiDesc + "失败！");
            } else {
                throw new AppException("不支持当前绩效类型");
            }
            recordSysLog(request, busiDesc + " 【成功】");
        } catch (Exception e) {
            log.error(busiDesc, e);
            rest = Rest.fail(super.convertException(e));
        }
        log.info("【{}】【响应体】--> {}", busiDesc, JSONObject.toJSONString(req));
        return rest;
    }


    private boolean attend(InspectSaveReq req, Context context) throws AppException {
        //考勤保存
        PerformRulesEntity rule = getRule(req.getRuleId().toString());
        StaffEntity staffEntity = getStaff(req.getStaffId().toString());

        PerformAttendRecordEntity recordEntity = new PerformAttendRecordEntity();
        recordEntity.initAttrValue();
        BeanUtils.copyProperties(req, recordEntity);
        recordEntity.setStaffId(staffEntity.getId());
        recordEntity.setStaffName(staffEntity.getName());

        recordEntity.setDeptId(staffEntity.getDeptId());
        recordEntity.setDeptName(staffEntity.getDeptName());

        recordEntity.setDeductTime(new Date());
        StaffEntity custStaff = getStaff(context.getUser().getCustomerId().toString());
        recordEntity.setDeductPerson(custStaff==null?"系统管理员":custStaff.getName());

        recordEntity.setSubAddType(rule.getSubAddType());
        recordEntity.setScore(rule.getScore());
        recordEntity.setRuleId(rule.getId());
        recordEntity.setRuleName(rule.getName());
        recordEntity.setCategoryId(rule.getCategoryId());
        recordEntity.setCategoryName(rule.getCategoryName());
        recordEntity.setSubMethod(SubMethodEnum.大厅巡查.getValue());
        recordEntity.setErrorTime(new Date());

        //根据考勤组查询 上下班
        buildGoOffWork(req, context, recordEntity);

        recordEntity.setCreateUserId(context.getUser().getId());
        recordEntity.setCreateTime(new Date());
        PerformAttendRecordEntity save = attendRecordService.save(recordEntity);

        return save.newEntity();

    }

    private void buildGoOffWork(InspectSaveReq req, Context context, PerformAttendRecordEntity recordEntity) {
        if(!ObjectUtils.isEmpty(req.getAttendanceGroupId())&&!ObjectUtils.isEmpty(req.getAttendanceDate())){
            AttendanceGroupEntity attendanceGroupEntity = groupService.get(req.getAttendanceGroupId(), context);
            if (!ObjectUtils.isEmpty(attendanceGroupEntity)) {
                //判断上下班时间
                if (TypeEnum.固定班制.getValue() == attendanceGroupEntity.getType()) {
                    AttendanceGroupFixedworkEntity fixedworkEntity = fixedworkService.selectOne(new AttendanceGroupFixedworkQuery().groupId(attendanceGroupEntity.getId()));
                    if (!ObjectUtils.isEmpty(fixedworkEntity)) {
                        //查看当前时间是星期几
                        int dayOfWeek = DateUtil.dayOfWeek(req.getAttendanceDate());
                        switch (dayOfWeek) {
                            case 1:
                                String goOffWorkStr = getGoOffWorkStr(fixedworkEntity.getSundayClassId());
                                recordEntity.setGoOffTimeStr(goOffWorkStr);
                                break;
                            case 2:
                                goOffWorkStr = getGoOffWorkStr(fixedworkEntity.getMondayClassId());
                                recordEntity.setGoOffTimeStr(goOffWorkStr);
                                break;
                            case 3:
                                goOffWorkStr = getGoOffWorkStr(fixedworkEntity.getTuesdayClassId());
                                recordEntity.setGoOffTimeStr(goOffWorkStr);
                                break;
                            case 4:
                                goOffWorkStr = getGoOffWorkStr(fixedworkEntity.getWednesdayClassId());
                                recordEntity.setGoOffTimeStr(goOffWorkStr);
                                break;
                            case 5:
                                goOffWorkStr = getGoOffWorkStr(fixedworkEntity.getTuesdayClassId());
                                recordEntity.setGoOffTimeStr(goOffWorkStr);
                                break;
                            case 6:
                                goOffWorkStr = getGoOffWorkStr(fixedworkEntity.getFridayClassId());
                                recordEntity.setGoOffTimeStr(goOffWorkStr);
                                break;
                            case 7:
                                goOffWorkStr = getGoOffWorkStr(fixedworkEntity.getSundayClassId());
                                recordEntity.setGoOffTimeStr(goOffWorkStr);
                                break;
                            default:
                                recordEntity.setGoOffTimeStr("");
                        }
                    }
                }
                else if (TypeEnum.自由工时.getValue() == attendanceGroupEntity.getType()) {

                } else if (TypeEnum.排班制.getValue() == attendanceGroupEntity.getType()) {

                } else {

                }
            }
        }
    }


    private String getGoOffWorkStr(Long sundayClassId) {
        if (ObjectUtils.isEmpty(sundayClassId)) return "";

        StringBuilder goOffWorkSb = new StringBuilder();
        List<AttendanceClassDetailEntity> classDetailEntities = classDetailService.find(new AttendanceClassDetailQuery().classId(sundayClassId));
        if (!ObjectUtils.isEmpty(classDetailEntities)) {
            for (AttendanceClassDetailEntity classDetailEntity : classDetailEntities) {
                String goWorkStr = "";
                String offWorkStr = "";
                if (!ObjectUtils.isEmpty(classDetailEntity.getGoWorkDate())) {
                    goWorkStr = DateUtil.format(classDetailEntity.getGoWorkDate(),"HH:mm");
                }
                if (!ObjectUtils.isEmpty(classDetailEntity.getOffWorkDate())) {
                    offWorkStr = DateUtil.format(classDetailEntity.getOffWorkDate(),"HH:mm");
                }
                goOffWorkSb.append(goWorkStr);
                goOffWorkSb.append("~");
                goOffWorkSb.append(offWorkStr);
                goOffWorkSb.append(" \n");
            }
        }
        return goOffWorkSb.toString();
    }


    private boolean review(InspectSaveReq req, Context context) throws AppException {
        //评价保存
        StaffEntity staffEntity = getStaff(req.getStaffId().toString());
        PerformRulesEntity rule = getRule(req.getRuleId().toString());

        PerformReviewRecordEntity recordEntity = new PerformReviewRecordEntity();

        recordEntity.initAttrValue();
        BeanUtils.copyProperties(req, recordEntity);
        //  recordEntity.setStaffId(staffEntity.getId());
        recordEntity.setStaffName(staffEntity.getName());
        recordEntity.setWorkNum(staffEntity.getWorkNum());
        recordEntity.setDeductTime(new Date());
        StaffEntity custStaff = getStaff(context.getUser().getCustomerId().toString());
        recordEntity.setDeductPerson(custStaff==null?"系统管理员":custStaff.getName());

        recordEntity.setDeptId(staffEntity.getDeptId());
        recordEntity.setDeptName(staffEntity.getDeptName());
        recordEntity.setSubAddType(rule.getSubAddType());
        recordEntity.setScore(rule.getScore());
        recordEntity.setRuleId(rule.getId());
        recordEntity.setRuleName(rule.getName());
        recordEntity.setCategoryId(rule.getCategoryId());
        recordEntity.setCategoryName(rule.getCategoryName());
        recordEntity.setSubMethod(SubMethodEnum.大厅巡查.getValue());
        recordEntity.setCreateUserId(context.getUser().getId());
        recordEntity.setCreateTime(new Date());
        PerformReviewRecordEntity save = reviewRecordService.save(recordEntity);
        return save.newEntity();

    }

    private boolean complain(InspectSaveReq req, Context context) throws AppException {
        //投诉保存
        StaffEntity staffEntity = getStaff(req.getStaffId().toString());
        PerformRulesEntity rule = getRule(req.getRuleId().toString());

        PerformComplainRecordEntity recordEntity = new PerformComplainRecordEntity();

        recordEntity.initAttrValue();
        BeanUtils.copyProperties(req, recordEntity);
        // recordEntity.setStaffId(staffEntity.getId());
        recordEntity.setStaffName(staffEntity.getName());
        recordEntity.setWorkNum(staffEntity.getWorkNum());
        recordEntity.setDeptId(staffEntity.getDeptId());
        recordEntity.setDeptName(staffEntity.getDeptName());

        recordEntity.setDeductTime(new Date());
        StaffEntity custStaff = getStaff(context.getUser().getCustomerId().toString());
        recordEntity.setDeductPerson(custStaff==null?"系统管理员":custStaff.getName());

        recordEntity.setSubAddType(rule.getSubAddType());
        recordEntity.setScore(rule.getScore());
        recordEntity.setRuleId(rule.getId());
        recordEntity.setRuleName(rule.getName());
        recordEntity.setCategoryId(rule.getCategoryId());
        recordEntity.setCategoryName(rule.getCategoryName());
        recordEntity.setSubMethod(SubMethodEnum.大厅巡查.getValue());

        recordEntity.setCreateUserId(context.getUser().getId());
        recordEntity.setCreateTime(new Date());
        PerformComplainRecordEntity save = complainRecordService.save(recordEntity);
        return save.newEntity();

    }

    private boolean gowork(InspectSaveReq req, Context context) throws AppException {
        //办件保存
        StaffEntity staffEntity = getStaff(req.getStaffId().toString());
        PerformRulesEntity rule = getRule(req.getRuleId().toString());

        PerformGoworkRecordEntity recordEntity = new PerformGoworkRecordEntity();

        recordEntity.initAttrValue();
        BeanUtils.copyProperties(req, recordEntity);
        // recordEntity.setStaffId(staffEntity.getId());
        recordEntity.setStaffName(staffEntity.getName());
        recordEntity.setWorkNum(staffEntity.getWorkNum());
        recordEntity.setDeductTime(new Date());
        StaffEntity custStaff = getStaff(context.getUser().getCustomerId().toString());
        recordEntity.setDeductPerson(custStaff==null?"系统管理员":custStaff.getName());

        recordEntity.setDeptId(staffEntity.getDeptId());
        recordEntity.setDeptName(staffEntity.getDeptName());
        recordEntity.setSubAddType(rule.getSubAddType());
        recordEntity.setScore(rule.getScore());
        recordEntity.setRuleId(rule.getId());
        recordEntity.setRuleName(rule.getName());
        recordEntity.setCategoryId(rule.getCategoryId());
        recordEntity.setCategoryName(rule.getCategoryName());
        recordEntity.setSubMethod(SubMethodEnum.大厅巡查.getValue());
        recordEntity.setCreateUserId(context.getUser().getId());
        recordEntity.setCreateTime(new Date());
        PerformGoworkRecordEntity save = performGoworkRecordService.save(recordEntity);
        return save.newEntity();

    }

    private boolean effect(InspectSaveReq req, Context context) throws AppException {
        //效能保存
        StaffEntity staffEntity = getStaff(req.getStaffId().toString());
        PerformRulesEntity rule = getRule(req.getRuleId().toString());

        PerformEffectRecordEntity recordEntity = new PerformEffectRecordEntity();

        recordEntity.initAttrValue();
        BeanUtils.copyProperties(req, recordEntity);
        //recordEntity.setStaffId(staffEntity.getId());
        recordEntity.setStaffName(staffEntity.getName());

        recordEntity.setWorkNum(staffEntity.getWorkNum());

        recordEntity.setDeductTime(new Date());
        StaffEntity custStaff = getStaff(context.getUser().getCustomerId().toString());
        recordEntity.setDeductPerson(custStaff==null?"系统管理员":custStaff.getName());

        recordEntity.setDeptId(staffEntity.getDeptId());
        recordEntity.setDeptName(staffEntity.getDeptName());
        recordEntity.setSubAddType(rule.getSubAddType());
        recordEntity.setScore(rule.getScore());
        recordEntity.setRuleId(rule.getId());
        recordEntity.setRuleName(rule.getName());
        recordEntity.setCategoryId(rule.getCategoryId());
        recordEntity.setCategoryName(rule.getCategoryName());
        recordEntity.setSubMethod(SubMethodEnum.大厅巡查.getValue());
        recordEntity.setCreateUserId(context.getUser().getId());
        recordEntity.setCreateTime(new Date());
        PerformEffectRecordEntity save = effectRecordService.save(recordEntity);
        return save.newEntity();
    }

    private boolean other(InspectSaveReq req, Context context) throws AppException {
        //其它保存

        StaffEntity staffEntity = getStaff(req.getStaffId().toString());
        PerformRulesEntity rule = getRule(req.getRuleId().toString());

        PerformOtherRecordEntity recordEntity = new PerformOtherRecordEntity();

        recordEntity.initAttrValue();
        BeanUtils.copyProperties(req, recordEntity);
        //recordEntity.setStaffId(staffEntity.getId());
        recordEntity.setStaffName(staffEntity.getName());
        recordEntity.setWorkNum(staffEntity.getWorkNum());
        recordEntity.setDeductTime(new Date());
        StaffEntity custStaff = getStaff(context.getUser().getCustomerId().toString());
        recordEntity.setDeductPerson(custStaff==null?"系统管理员":custStaff.getName());


        recordEntity.setDeptId(staffEntity.getDeptId());
        recordEntity.setDeptName(staffEntity.getDeptName());
        recordEntity.setSubAddType(rule.getSubAddType());
        recordEntity.setScore(rule.getScore());
        recordEntity.setRuleId(rule.getId());
        recordEntity.setRuleName(rule.getName());
        recordEntity.setCategoryId(rule.getCategoryId());
        recordEntity.setCategoryName(rule.getCategoryName());
        recordEntity.setSubMethod(SubMethodEnum.大厅巡查.getValue());
        recordEntity.setCreateUserId(context.getUser().getId());
        recordEntity.setCreateTime(new Date());
        PerformOtherRecordEntity save = otherRecordService.save(recordEntity);
        return save.newEntity();
    }

    /**
     * 详细
     */
    @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不能为空!");
            }
            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("不支持当前绩效类型");
            }

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

        rest.setDict(model.get("dict"));

        return rest;
    }

    private PerformRulesEntity getRule(String ruleId) {
        PerformRulesEntity rule = rulesService.getCache(ruleId);
        if (ObjectUtils.isEmpty(rule))
            throw new AppException(String.format("当前手机号码未找到匹配的员工！rule:%s", ruleId));

        return rule;
    }


    private StaffEntity getStaff(String staffId) {
        StaffEntity staffEntity = staffService.getCache(staffId);
        if (ObjectUtils.isEmpty(staffEntity))
            throw new AppException(String.format("当前id未找到匹配的员工！staffId:%s", staffId));

        return staffEntity;
    }


    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) {

    }

}
