package com.lz.modules.app.controller;

import com.lz.common.utils.*;
import com.lz.modules.app.dto.DepartmentsDto;
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.service.DepartmentsService;
import com.lz.modules.app.service.DepartmentsStaffRelateService;
import com.lz.modules.app.service.StaffService;
import com.lz.modules.sys.entity.app.ResultDetail;
import com.lz.modules.sys.entity.app.ResultRecord;
import com.lz.modules.sys.service.app.ResultDetailService;
import com.lz.modules.sys.service.app.ResultRecordService;
import io.jsonwebtoken.lang.Collections;
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.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 业绩记录表
 *
 * @author zgh
 * @email zgh@ldxinyong.com
 * @date 2020-08-10 17:19:22
 */
@RestController
@RequestMapping("user/lzresultrecord")
public class ResultRecordController {
    @Autowired
    private ResultRecordService lzResultRecordService;
    @Autowired
    private DepartmentsService departmentsService;

    @Autowired
    private ResultDetailService resultDetailService;
    @Autowired
    private ResultRecordService resultRecordService;

    @Autowired
    private StaffService staffService;

    @Autowired
    private DepartmentsStaffRelateService departmentsStaffRelateService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("user:lzresultrecord:list")
    public R list(ResultRecordReq req) {
        PageUtils page = lzResultRecordService.queryPage(req);
        List<DepartmentsDto> departmentList1 = departmentsService.selectByParentDepartmentId("0");
        return R.ok().put("page", page)
                .put("departmentList1", departmentList1);
    }

    @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) {
        ResultRecord resultRecord = resultRecordService.selectResultRecordById(req.getRecordResultId());
        StaffEntity staffEntity = staffService.getById(resultRecord.getStaffId());
        List<DepartmentsStaffRelateEntity> departmentsStaffRelateEntities = departmentsStaffRelateService.selectByStaffIds(Arrays.asList(staffEntity.getId()));
        DepartmentsStaffRelateEntity departmentsStaffRelateEntity = departmentsStaffRelateEntities.get(0);
        StaffDepartmentDto departmentDto = departmentsService.selectStaffAllDepartments(departmentsStaffRelateEntity.getDepartmentId());
        List<ResultDetail> resultDetails = resultDetailService.selectByRecordId(req.getRecordResultId());
        SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy年MM月dd");
        List<ResultDetailResp> list = new ArrayList<>();
        int firstRowspan = 0;
        int secondRowspan = 0;
        int threeRowspan = 0;
        int fourRowspan = 0;
        int fiveRowspan = 0;

        if (!Collections.isEmpty(resultDetails)) {
            Map<Integer, Long> details = resultDetails.stream().collect(Collectors.groupingBy(ResultDetail::getType, Collectors.counting()));
            int type1 = NumberUtil.objToIntDefault(details.get(new Integer(1)), 0);
            int type2 = NumberUtil.objToIntDefault(details.get(new Integer(2)), 0);
            firstRowspan = type1;
            secondRowspan = type1 + 1;
            threeRowspan = type1 + 1 + type2;
            fourRowspan = type1 + 1 + type2 + 1;
            fiveRowspan = type1 + 1 + type2 + 2;

            int count = 0;
            for (ResultDetail resultDetail : resultDetails) {
                count++;
                ResultDetailResp resp = new ResultDetailResp();
                BeanUtils.copyProperties(resultDetail, resp);
                resp.setCheckWeight(BigDecimalUtil.set2Scale(resp.getCheckWeight()));
                if (resultDetail.getType() == 1) {
                    resp.setCheckRange("业绩");
                } else if (resultDetail.getType() == 2) {
                    resp.setCheckRange("文化价值观");
                }
                if (count == type1 || count == type1 + type2) {
                    resp.setIsAdd(1);
                }
                if (count == type1 + 1) {
                    ResultDetailResp respHeader = new ResultDetailResp();
                    respHeader.setKeyResult("业务考核结果");
                    respHeader.setCheckWeight(new BigDecimal(0.7));
                    respHeader.setSuperScore("/");
                    respHeader.setAcquireScore(new BigDecimal(0));
                    respHeader.setScoreComment("/");
                    respHeader.setIsAdd(-1);
                    list.add(respHeader);
                }
                list.add(resp);
            }
        }

        ResultDetailResp tail1 = new ResultDetailResp();
        tail1.setKeyResult("文化价值观考核结果");
        tail1.setCheckWeight(new BigDecimal(0.3));
        tail1.setSuperScore("/");
        tail1.setAcquireScore(new BigDecimal(0));
        tail1.setScoreComment("/");
        tail1.setIsAdd(-1);

        ResultDetailResp tail2 = new ResultDetailResp();
        tail2.setCheckRange("文化价值观考核结果");
        tail2.setAcquireScore(new BigDecimal(0));
        tail2.setScoreComment("/");
        tail2.setIsAdd(-1);

        ResultDetailResp tail3 = new ResultDetailResp();
        tail3.setCheckRange("最终绩效考核结果等级");
        tail3.setAcquireScore(new BigDecimal(3.25));
        tail3.setScoreComment("/");
        tail3.setIsAdd(-1);

        list.add(tail1);
        list.add(tail2);
        list.add(tail3);

        return R.ok()
                .put("staffName", staffEntity.getName())
                .put("department1", departmentDto.getDepartment1())
                .put("department2", departmentDto.getDepartment2())
                .put("department3", departmentDto.getDepartment3())
                .put("checkMonth", sdf3.format(resultRecord.getGmtCreate()))
                .put("firstRowspan", firstRowspan)
                .put("secondRowspan", secondRowspan)
                .put("threeRowspan", threeRowspan)
                .put("fourRowspan", fourRowspan)
                .put("fiveRowspan", fiveRowspan)
                .put("list", list);

    }

    /**
     * 信息
     */
    @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("/recorddetailDelete/{id}")
    public R recorddetailDelete(@PathVariable("id") Long id) {
        resultDetailService.deleteResultDetailById(id);
        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("/detailAddOrUpdate")
    public R detailAddOrUpdate(ResultDetail resultDetail) {
        ResultDetail old = resultDetailService.selectResultDetailById(resultDetail.getId());
        if (old != null) {
            com.lz.modules.app.utils.BeanUtils.copyProperty(old, resultDetail, false);
            old.setKeyResult(StringUtil.decodeBase64(resultDetail.getKeyResult()));
            old.setCheckResult(StringUtil.decodeBase64(resultDetail.getCheckResult()));
            if (old.getType() == 2) {
                old.setTarget(old.getKeyResult());
            }
            resultDetailService.updateResultDetailById(old);
        }else{
            resultDetail.setKeyResult(StringUtil.decodeBase64(resultDetail.getKeyResult()));
            resultDetail.setCheckResult(StringUtil.decodeBase64(resultDetail.getCheckResult()));
            resultDetailService.insertResultDetail(resultDetail);
        }
        return R.ok("保存成功");
    }

    /**
     * 保存
     */
    @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("/delete")
    @RequiresPermissions("user:lzresultrecord:delete")
    public R delete(@RequestBody Long[] ids) {
        lzResultRecordService.deleteBatchIds(Arrays.asList(ids));
        return R.ok();
    }

}
