package com.lz.modules.app.controller;

import com.lz.common.emun.WorkMsgTypeEnum;
import com.lz.common.utils.*;
import com.lz.modules.app.dto.ApprovalDto;
import com.lz.modules.app.dto.DepartmentsDto;
import com.lz.modules.app.dto.RecordListDto;
import com.lz.modules.app.dto.StaffDepartmentDto;
import com.lz.modules.app.entity.DepartmentsStaffRelateEntity;
import com.lz.modules.app.entity.StaffEntity;
import com.lz.modules.app.req.ResultRecordReq;
import com.lz.modules.app.resp.ResultDetailResp;
import com.lz.modules.app.resp.Step;
import com.lz.modules.app.service.DepartmentsService;
import com.lz.modules.app.service.DepartmentsStaffRelateService;
import com.lz.modules.app.service.StaffService;
import com.lz.modules.flow.entity.FlowRecord;
import com.lz.modules.flow.entity.RecordAuth;
import com.lz.modules.flow.entity.RecordFile;
import com.lz.modules.flow.entity.StaffRole;
import com.lz.modules.flow.model.Auth;
import com.lz.modules.flow.model.ResultRecordDto;
import com.lz.modules.flow.req.ResultDetailReq;
import com.lz.modules.flow.service.FlowRecordService;
import com.lz.modules.flow.service.RecordAuthService;
import com.lz.modules.flow.service.RecordFileService;
import com.lz.modules.flow.service.StaffRoleService;
import com.lz.modules.sys.controller.AbstractController;
import com.lz.modules.sys.entity.SysUserEntity;
import com.lz.modules.sys.entity.app.ResultComment;
import com.lz.modules.sys.entity.app.ResultDetail;
import com.lz.modules.sys.entity.app.ResultRecord;
import com.lz.modules.sys.service.app.ResultCommentService;
import com.lz.modules.sys.service.app.ResultDetailService;
import com.lz.modules.sys.service.app.ResultRecordService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 业绩记录表
 *
 * @author zgh
 * @email zgh@ldxinyong.com
 * @date 2020-08-10 17:19:22
 */
@RestController
@RequestMapping("user/lzresultrecord")
@Slf4j
public class ResultRecordController extends AbstractController {
    @Autowired
    private ResultRecordService lzResultRecordService;
    @Autowired
    private DepartmentsService departmentsService;
    @Autowired
    private ResultDetailService resultDetailService;
    @Autowired
    private ResultRecordService resultRecordService;
    @Autowired
    private StaffService staffService;
    @Autowired
    private DepartmentsStaffRelateService departmentsStaffRelateService;
    @Autowired
    private RecordAuthService recordAuthService;
    @Autowired
    private ResultCommentService resultCommentService;

    @Autowired
    private FlowRecordService flowRecordService;

    @Autowired
    private RecordFileService  recordFileService;




    @Autowired
    private   StaffRoleService staffRoleService;

    @Autowired
    private RedisCacheUtil redisCacheUtil;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("user:lzresultrecord:list")
    public R list(ResultRecordReq req) {
        List<DepartmentsDto> departmentList2 = new ArrayList<>();
        List<DepartmentsDto> departmentList3 = new ArrayList<>();
        List<DepartmentsDto> departmentList1 = departmentsService.selectByParentDepartmentId("1");
        String department1 = req.getDepartment1();
        String department2 = req.getDepartment2();
        String department3 = req.getDepartment3();
        SysUserEntity user = getUser();
        if (req.getIsSelf() == 1) {
            req.setStaffId(user.getUserId());
        } else {
            StaffRole staffRole = staffRoleService.selectByStaffId(getUserId());
            if (staffRole == null && req.getIsChangeDepartmentrtment() == 0) {
                DepartmentsStaffRelateEntity relateEntity = departmentsStaffRelateService.selectLastDepartmentByStaffId(getUserId());
                Map<String, String> map = departmentsService.selectUserAllDepartmentInFo(relateEntity.getDepartmentId());
                int i = 0;
                for (Map.Entry<String, String> entry : map.entrySet()) {
                    i++;
                }
                i = i / 2;
                if (i == 3) { // 表示有三级部门
                    departmentList2 = departmentsService.selectByParentDepartmentId(map.get("dd3"));
                    departmentList3 = departmentsService.selectByParentDepartmentId(map.get("dd2"));
                    department1 = map.get("dd3");
                    department2 = map.get("dd2");
                    department3 = map.get("dd1");
                    req.setDepartment3(map.get("dd1"));
                } else if (i == 2) {
                    departmentList2 = departmentsService.selectByParentDepartmentId(map.get("dd2"));
                    department2 = map.get("dd1");
                    department1 = map.get("dd2");
                    req.setDepartment2(map.get("dd1"));
                } else if (i == 1) {
                    department1 = map.get("dd1");
                    req.setDepartment1(map.get("dd1"));
                }
            }
        }
        R r = lzResultRecordService.queryPage(req, user);
        r .put("departmentList1", departmentList1)
                .put("departmentList2", departmentList2)
                .put("departmentList3", departmentList3)
                .put("department1", department1)
                .put("department2", department2)
                .put("department3", department3);
        return r ;

    }


    @RequestMapping("/departmentQuery")
    public R departmentQuery(ResultRecordReq req) {
        List<DepartmentsDto> departmentList1 = departmentsService.selectByParentDepartmentId(req.getDepartmentId());
        return R.ok()
                .put("departmentList", departmentList1);
    }

    @RequestMapping("/getStaffResultDetail")
    public R getStaffResultDetail(ResultRecordReq req) {
        int yeJiCheckNum = 0;
        int wenHuaJiaZhiGuanNum = 1;
        int lastResultNum = 2;
        int commentNum = 0;
        int recordType = req.getRecordType();
        ResultRecord resultRecord = resultRecordService.selectResultRecordById(req.getRecordResultId());
        StaffEntity staffEntity = staffService.getById(resultRecord != null ? resultRecord.getStaffId() : getUserId());
        List<DepartmentsStaffRelateEntity> departmentsStaffRelateEntities = departmentsStaffRelateService.selectByStaffIds(Arrays.asList(staffEntity.getId()));
        DepartmentsStaffRelateEntity departmentsStaffRelateEntity = departmentsStaffRelateEntities.get(0);
        StaffDepartmentDto departmentDto = departmentsService.selectStaffAllDepartments(departmentsStaffRelateEntity.getDepartmentId());
        SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy-MM");
        List<ResultDetailResp> list = new ArrayList<>();
        // 获取权限
        Auth auth = new Auth();
        List<RecordAuth> listAuth = new ArrayList<>();
        if (req.getRecordType() == 1 && resultRecord == null) { //新增目标
            listAuth = recordAuthService.selectAuthInfo(7l);
            auth = recordAuthService.getAuth(listAuth);
            resultRecord = resultRecordService.createResultRecord(getUserId(), req.getRecordType(), 7l);
            flowRecordService.initFlowRecord(resultRecord, 7l, req.getRecordType(), "月初目标");
            recordType = 3;
        } else if (req.getRecordType() == 2 && resultRecord == null) { //新增业绩
            listAuth = recordAuthService.selectAuthInfo(8l);
            auth = recordAuthService.getAuth(listAuth);
            auth.setWenHuaEdit(1);
            resultRecord = resultRecordService.initResult(getUserId(), req.getRecordType(), 8l);
            recordType = 3;
        } else if (resultRecord != null) {
            Map<Long, Long> staffRoleMap = recordAuthService.selectRoleIdByStaffRoleInfo(resultRecord.getFlowStaffIdRole());
            listAuth = recordAuthService.selectAuthInfo(staffRoleMap.get(getUserId()));
            auth = recordAuthService.getAuth(listAuth);
        }
        List<ResultDetail> resultDetails = resultDetailService.selectByRecordId(resultRecord.getId());
        List<Step> stepList = resultDetailService.getStepList(resultRecord);
        BigDecimal sumWenHuaJiaZhiGuan = BigDecimal.ZERO;
        BigDecimal sumYeJi = BigDecimal.ZERO;
        if (CollectionUtils.isNotEmpty(resultDetails)) {
            Map<Integer, Long> details = resultDetails.stream().collect(Collectors.groupingBy(ResultDetail::getType, Collectors.counting()));
            int tempType1 = NumberUtil.objToIntDefault(details.get(new Integer(1)), 0);
            int tempType2 = NumberUtil.objToIntDefault(details.get(new Integer(2)), 0);
            yeJiCheckNum = tempType1;
            wenHuaJiaZhiGuanNum = tempType2;
            if (tempType1 == 0) {
                yeJiCheckNum = 1;
                list.add(resultDetailService.getYeJi());
                list.add(resultDetailService.getYeJiKaoHe(BigDecimal.ZERO));
            }
            int count = 0;
            for (ResultDetail resultDetail : resultDetails) {
                count++;
                ResultDetailResp resp = new ResultDetailResp();
                BeanUtils.copyProperties(resultDetail, resp);
                if (resultDetail.getType() == 1) {
                    resp.setCheckRange("绩效");
                } else if (resultDetail.getType() == 2) {
                    resp.setCheckRange("文化价值观");
                }
                if (count == yeJiCheckNum) {
                    resp.setIsAdd(1);
                }
                resp.setIsEdit(1);
                BigDecimal checkWeight = NumberUtil.objToBigDecimalDefault(resultDetail.getCheckWeight(), BigDecimal.ZERO);
                BigDecimal acquireScore = NumberUtil.objToBigDecimalDefault(resultDetail.getAcquireScore(), BigDecimal.ZERO);
                BigDecimal tempSum = checkWeight.multiply(acquireScore);
                if (resultDetail.getType().equals(1)) {
                    sumYeJi = sumYeJi.add(tempSum);
                } else {
                    sumWenHuaJiaZhiGuan = sumWenHuaJiaZhiGuan.add(tempSum);
                }
                if (count == yeJiCheckNum + 1 && tempType1 != 0) {
                    list.add(resultDetailService.getYeJiKaoHe(BigDecimalUtil.setScale(sumYeJi, 3)));
                }
                list.add(resp);
            }
            if (tempType2 == 0) {
                list.add(resultDetailService.getYeJiKaoHe(BigDecimal.ZERO));
                list.add(resultDetailService.getWenHuaJiaZhiGua1(auth));
            }
        } else {
            yeJiCheckNum = 1;
            list.add(resultDetailService.getYeJi());
            list.add(resultDetailService.getYeJiKaoHe(BigDecimal.ZERO));
            list.add(resultDetailService.getWenHuaJiaZhiGua1(auth));
        }
        list.add(resultDetailService.getWenHuaJiaZhiGuaResult1(sumWenHuaJiaZhiGuan));
        list.add(resultDetailService.getWenHuaJiaZhiGuaResult2());
        list.add(resultDetailService.getLastResult(resultRecord.getLastScore()));
        List<ResultComment> comments = resultCommentService.selectByRecordId(resultRecord.getId());
        if (CollectionUtils.isNotEmpty(comments)) {
            ResultDetailResp header = new ResultDetailResp();
            header.setCheckRange("领导");
            header.setTarget("状态");
            header.setKeyResult("意见");
            list.add(header);
            commentNum = comments.size();
            for (ResultComment resultComment : comments) {
                ResultDetailResp comment = new ResultDetailResp();
                comment.setCheckRange(resultComment.getStaffName());
                String target = "审批通过";
                if (resultComment.getStatus() == 5) {
                    target = "驳回";
                }else if (resultComment.getStatus() == 6){
                    target = "申述";
                }
                comment.setTarget(target);
                comment.setKeyResult(resultComment.getComment());
                list.add(comment);
            }
        }
        String superStaff = recordAuthService.selectByStaffId(resultRecord.getStaffId());
        int fileCount = recordFileService.selectRecordFileCountByRecordId(resultRecord.getId());
        //表示是自己查看详情
        if(resultRecord.getStaffId().equals(getUserId())){
            List<FlowRecord> flowRecords = flowRecordService.selectFlowRecordByResultRecordIdTypeStatus(req.getRecordResultId(), resultRecord.getType(), 0);
            if (flowRecords != null && flowRecords.size() == 2) {       // 表示可以撤回
                auth.setCancel(1);
            }
            // 审批人是自己，不提供催办按钮,流程结束不显示
            if (flowRecords != null && flowRecords.size() >= 2 &&
                    !getUserId().equals(resultRecord.getCurrentApprovalStaffId()) &&
                    resultRecord.getCurrentApprovalStaffId() != null) {
                auth.setSubmited(1);
            }
        }

        return R.ok()
                .put("staffName", staffEntity.getName())
                .put("department1", departmentDto.getDepartment1())
                .put("department2", departmentDto.getDepartment2())
                .put("department3", departmentDto.getDepartment3())
                .put("checkMonth", sdf3.format(resultRecord == null ? new Date() : resultRecord.getMonthTime()))
                .put("list", list)
                .put("auth", auth)
                .put("recordType", recordType)
                .put("recordResultId", resultRecord.getId())
                .put("yeJiCheckNum", yeJiCheckNum)
                .put("wenHuaJiaZhiGuanNum", wenHuaJiaZhiGuanNum)
                .put("lastResultNum", lastResultNum)
                .put("commentNum", commentNum)
                .put("superStaff", superStaff)
                .put("fileCount",fileCount)
                .put("stepList",stepList)
        ;
    }

    @RequestMapping("/commitApproval")
    public R commitApproval(ResultRecordReq req) {
        return resultRecordService.commitApproval(req, getUserId());
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("user:lzresultrecord:info")
    public R info(@PathVariable("id") Long id) {
        ResultRecord lzResultRecord = lzResultRecordService.selectResultRecordById(id);
        return R.ok().put("lzResultRecord", lzResultRecord);
    }

    /**
     * 信息
     */
    @RequestMapping("/detail/{id}")
    public R detail(@PathVariable("id") Long id) {
        ResultDetail detail = resultDetailService.selectResultDetailById(id);
        return R.ok().put("detailInfo", detail);
    }

    /**
     * 信息
     */
    @RequestMapping("/getResultComment/{recordId}")
    public R getResultComment(@PathVariable("recordId") Long recordId) {
        ResultComment resultComment = resultCommentService.selectLastComment(recordId);
        FlowRecord flowRecordLast = flowRecordService.selectLastFlowRecordByRecordId(recordId);
        if (resultComment ==null || !resultComment.getFlowRecordId().equals(flowRecordLast.getId())) {
            resultComment = new ResultComment();
        }

        List<FlowRecord> flowRecords = flowRecordService.selectFlowRecordByResultRecordIdFlowId(recordId);
        if (flowRecords != null && flowRecords.size() > 0) {
            FlowRecord flowRecord = flowRecords.get(flowRecords.size()-1);
            if(flowRecord.getApprovalStaffId().equals(getUserId())){
                flowRecords.remove(flowRecord);
            }
        }
        return R.ok().put("resultComment", resultComment)
                .put("list", flowRecords);
    }

    /**
     * 信息
     */
    @RequestMapping("/recorddetailDelete/{id}")
    public R recorddetailDelete(@PathVariable("id") Long id) {
        resultDetailService.deleteResultDetailById(id);
        return R.ok("删除成功");
    }

    /**
     * 信息
     */
    @RequestMapping("/recordIdsSubmit")
    public R recordIdsSubmit(String recordIds,Integer batchOpt) {
        if (StringUtil.isBlank(recordIds)) {
            return R.error("请勾选需要批量操作业绩！");
        }
        List<Long> records = new ArrayList<>();
        String ids[] = recordIds.split(",");
        if (ids != null && ids.length > 0) {
            for (String id : ids) {
                if (StringUtil.isNotBlank(id)) {
                    records.add(NumberUtil.objToLongDefault(id, 0));
                }
            }
        }
        R r = null;
        List<ResultRecord> resultRecords = resultRecordService.selectResultRecordByIds(records);
        if(batchOpt == 1){                          //提交审批
            for (ResultRecord resultRecord : resultRecords) {
                if (!StringUtil.in(resultRecord.getStatus(),1,2,3,5)) {
                    return R.error("您的提交记录中有状态不正确，请重新选择");
                }
            }
            for (ResultRecord resultRecord : resultRecords) {
                r = resultRecordService.approval(resultRecord.getId(), resultRecord.getCurrentApprovalStaffId(),null,false);
                if (!r.isSuccess()) {
                    return r;
                }
            }
        } else if (batchOpt == 2) {                                //终止流程
            for (ResultRecord resultRecord : resultRecords) {
                if (!StringUtil.in(resultRecord.getStatus(),1,2,3,5,6)) {
                    return R.error("您的提交记录中有状态不正确，请重新选择");
                }
            }
            for (ResultRecord resultRecord : resultRecords) {
                r = resultRecordService.approval(resultRecord.getId(), resultRecord.getCurrentApprovalStaffId(), 7, true);
                if (!r.isSuccess()) {
                    return r;
                }
            }
        } else if (batchOpt == 3 || batchOpt == 4 ) {   // 3 申述无效,直接驳回 ,4 领导重新打分
            for (ResultRecord resultRecord : resultRecords) {
                if (!StringUtil.in(resultRecord.getStatus(),6)) {
                    return R.error("您的提交记录中有状态不正确，请重新选择");
                }
            }
            if(batchOpt == 3 ){
                for (ResultRecord resultRecord : resultRecords) {
                    r = resultRecordService.approval(resultRecord.getId(), resultRecord.getCurrentApprovalStaffId(),null,false);
                    if (!r.isSuccess()) {
                        return r;
                    }
                }
            } else if(batchOpt == 4 ){
                for (ResultRecord resultRecord : resultRecords) {
                    List<FlowRecord> list = flowRecordService.selectFlowRecordByResultRecordIdType(resultRecord.getId(), 2);
                    for (int i = list.size() - 1; i >= 0; i--) {
                        FlowRecord flowRecord = list.get(i);
                        Long roleId = recordAuthService.getRoleIdByStaffRoleInfo(flowRecord.getFlowStaffIdRole(), flowRecord.getApprovalStaffId());
                        List<RecordAuth> listAuth = recordAuthService.selectAuthInfo(roleId);
                        Auth auth = recordAuthService.getAuth(listAuth);
                        if (auth.getEditScore() > 0) {//表示是评分
                            resultRecord.setFlowStaffIdRole(flowRecord.getFlowStaffIdRole());
                            resultRecord.setCurrentApprovalStaffId(flowRecord.getApprovalStaffId());
                            resultRecord.setCurrentApprovalStaffName(flowRecord.getApprovalStaffName());
                            resultRecord.setStatus(1);
                            // 直接还原权限
                            resultRecordService.updateResultRecordById(resultRecord);
                            break;
                        } else {
                            flowRecord.setStatus(1);//如果不是领导打分的话，直接删除掉
                            flowRecordService.updateFlowRecordById(flowRecord);
                        }
                    }
                }
            }
        }
        if (r != null && r.isSuccess()) {//批量提交
            StaffEntity mySelf = (StaffEntity) r.get("from");
            StaffEntity toSelf = (StaffEntity) r.get("to");
            WorkMsgTypeEnum workMsgTypeEnum = (WorkMsgTypeEnum) r.get("type");
            resultRecordService.sendWorkMSG(mySelf, toSelf, workMsgTypeEnum, 0L, 2);
        }

        return R.ok("批量提交成功");
    }

    /**
     * 信息
     */
    @RequestMapping("/weightCheck")
    public R weightCheck(ResultRecordReq req) {
        List<ResultDetail> resultDetails = resultDetailService.selectByRecordIdType(req.getRecordResultId(), req.getType());
        double compare = 0.3; //如果类型是文化价值观
        if (req.getType() == 1) { //类型是业绩
            compare = 0.7;
        }
        if (CollectionUtils.isEmpty(resultDetails)) {
            if (req.getId() > 0) { // 编辑验证
                if (req.getWeight().setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() > compare) {
                    return R.error("权重不能大于" + compare);
                }
            } else { // 添加验证
                if (req.getWeight().setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() > compare) {
                    return R.error("权重不能大于" + compare);
                }
            }
        } else {
            double sum = resultDetails.stream()
                    .filter(p -> !p.getId().equals(req.getId()))
                    .mapToDouble(n -> NumberUtil.objToDoubleWithDefault(n.getCheckWeight(), 0d)).summaryStatistics().getSum();
            if (req.getId() > 0) { //编辑验证
                if (new BigDecimal(sum).add(req.getWeight()).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() > compare) {
                    return R.error("权重之和不能大于" + compare);
                }
            } else { //添加验证
                if (new BigDecimal(sum).add(req.getWeight()).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() > compare) {
                    return R.error("权重之和不能大于" + compare);
                }
            }
        }
        return R.ok("验证成功");
    }

    /**
     * 信息
     */
    @RequestMapping("/preWeightCheck")
    public R preWeightCheck(ResultRecordReq req) {
        List<ResultDetail> resultDetails = resultDetailService.selectByRecordIdType(req.getRecordResultId(), req.getType());
        double compare = 0.3; //如果类型是文化价值观
        if (req.getType() == 1) { //类型是业绩
            compare = 0.7;
        }
        if (CollectionUtils.isEmpty(resultDetails)) {
            if (req.getId() > 0) { // 编辑验证
                if (req.getWeight().setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() > compare) {
                    return R.error("权重不能大于" + compare);
                }
            } else { // 添加验证
                if (req.getWeight().setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() >= compare) {
                    return R.error("权重不能大于" + compare);
                }
            }
        } else {
            double sum = resultDetails.stream()
                    .filter(p -> !p.getId().equals(req.getId()))
                    .mapToDouble(n -> NumberUtil.objToDoubleWithDefault(n.getCheckWeight(), 0d)).summaryStatistics().getSum();
            if (req.getId() > 0) { //编辑验证
                if (new BigDecimal(sum).add(req.getWeight()).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() > compare) {
                    return R.error("权重之和不能大于" + compare);
                }
            } else { //添加验证
                if (new BigDecimal(sum).add(req.getWeight()).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() >= compare) {
                    return R.error("权重之和不能大于" + compare);
                }
            }
        }
        return R.ok("验证成功");
    }

    /**
     * 信息
     */
    @RequestMapping("/detailAddOrUpdate")
    public R detailAddOrUpdate(ResultDetailReq req) {
        ResultRecord resultRecord = resultRecordService.selectResultRecordById(req.getRecordId());
        req.setKeyResult(StringUtil.decodeBase64(req.getKeyResult()));
        req.setKeyResult35(StringUtil.decodeBase64(req.getKeyResult35()));
        req.setKeyResult37(StringUtil.decodeBase64(req.getKeyResult37()));
        req.setCheckResult(StringUtil.decodeBase64(req.getCheckResult()));
        req.setScoreComment(StringUtil.decodeBase64(req.getScoreComment()));
        ResultDetail old = resultDetailService.selectResultDetailById(req.getId());
        if (old != null) {
            com.lz.modules.app.utils.BeanUtils.copyProperty(old, req, false);
            if(old.getType().equals(2)){
                old.setTarget(Constant.WENHUAJIAZHIGUAN);
            }
            resultDetailService.updateResultDetailById(old);
        } else {
            ResultDetail resultDetail = new ResultDetail();
            BeanUtils.copyProperties(req, resultDetail);
            resultDetail.setRecordId(resultRecord.getId());
            resultDetail.setStaffId(resultRecord.getStaffId());
            if(req.getType().equals(2)){
                resultDetail.setTarget(Constant.WENHUAJIAZHIGUAN);
            }
            resultDetailService.insertResultDetail(resultDetail);
        }
        List<ResultDetail> resultDetails = resultDetailService.selectByRecordId(resultRecord.getId());
        if (CollectionUtils.isNotEmpty(resultDetails)) {
            BigDecimal sum = BigDecimal.ZERO;
            for (ResultDetail resultDetail : resultDetails) {
                BigDecimal checkWeight = NumberUtil.objToBigDecimalDefault(resultDetail.getCheckWeight(), BigDecimal.ZERO);
                BigDecimal acquireScore = NumberUtil.objToBigDecimalDefault(resultDetail.getAcquireScore(), BigDecimal.ZERO);
                sum = sum.add(checkWeight.multiply(acquireScore));
            }
            sum = BigDecimalUtil.setScale(sum, 3);
            String scoreLevel = resultDetailService.getScoreLevel(sum.doubleValue());
            resultRecord.setLastScore(sum);
            resultRecord.setAllScore(sum);
            resultRecord.setScoreLevel(scoreLevel);
            resultRecordService.updateResultRecordById(resultRecord);
        }
        return R.ok("保存成功").put("recordId", resultRecord.getId());
    }
    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("user:lzresultrecord:save")
    public R save(@RequestBody ResultRecord lzResultRecord) {
        lzResultRecordService.insertResultRecord(lzResultRecord);
        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("user:lzresultrecord:update")
    public R update(@RequestBody ResultRecord lzResultRecord) {
        lzResultRecordService.updateResultRecordById(lzResultRecord);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/deleteRecord")
    @RequiresPermissions("user:lzresultrecord:delete")
    public R deleteRecord(String ids) {
        if(StringUtil.isBlank(ids)){
            return R.error("请选择 ids");
        }
        String is[] = ids.split(",");
        for(String i : is ){
            ResultRecord resultRecord = resultRecordService.selectResultRecordById(NumberUtil.objToLongDefault(i,0l));
            if(resultRecord !=null){
                resultRecord.setIsDelete(1);
                resultRecordService.updateResultRecordById(resultRecord);
            }
        }
        return R.ok();
    }



    /**
     * 删除
     */
    @RequestMapping("/addRecordAjudex")
    public R addRecordAjudex(String type) {
        ResultRecord resultRecord = resultRecordService.selectCurrentMonthResultRecordByStaffIdType(getUserId(),NumberUtil.objToIntDefault(type,2));
        if(resultRecord !=null){
            return R.error("当月己经存在绩效，请编辑。");
        }
        return  R.ok();
    }



    /**
     * 删除
     */
    @RequestMapping("/getUploadFileList")
    public R getUploadFileList(ResultDetailReq req) {
        PageUtils page = recordFileService.queryPage(req, getUser());
        return R.ok()
                .put("page", page);
    }

    /**
     * 删除
     */
    @RequestMapping("/deleteFile")
    public R deleteFile(ResultDetailReq req) {
        RecordFile recordFile = recordFileService.selectRecordFileById(req.getId());
        recordFile.setIsDelete(1);
        recordFileService.updateRecordFileById(recordFile);
        return R.ok();
    }





    /**
     * 删除
     */
    // http://localhost:8080/lz_management/user/lzresultrecord/new/approval?resultRecordId=215&status=1&loginUserId=825
    @RequestMapping("/new/approval")
    public R approval(ApprovalDto approvalDto) {
        try {
            approvalDto.setLoginUserId(approvalDto.getLoginUserId());
            return resultRecordService.newApproval(approvalDto);
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
    }



    /**
     * 删除
     */
    // http://localhost:8080/lz_management/user/lzresultrecord/new/resultRecordList
    @RequestMapping("/new/resultRecordList")
    public R newResultRecordList(RecordListDto recordListDto) {


        return null;
    }


}
