package com.bonus.gs.sub.evaluate.evaluate.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bonus.gs.sub.evaluate.evaluate.beans.*;
import com.bonus.gs.sub.evaluate.evaluate.dao.OutsourcerEvaluateDao;
import com.bonus.gs.sub.evaluate.evaluate.service.OutsourcerEvaluateService;
import com.bonus.gs.sub.evaluate.manager.controller.BaseController;
import com.bonus.gs.sub.evaluate.manager.model.SysUser;
import com.bonus.gs.sub.evaluate.manager.utils.AjaxRes;
import com.bonus.gs.sub.evaluate.manager.utils.GlobalConst;
import com.bonus.gs.sub.evaluate.manager.utils.POIOutputHelperNumBer;
import com.bonus.gs.sub.evaluate.manager.utils.UserUtil;
import com.bonus.gs.sub.evaluate.outsourceEnterprise.beans.ViolationBean;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.*;

@Controller
@RequestMapping("/outsourcer/")
public class OutsourcerEvaluateController extends BaseController<EvaluateSubBean> {
    @Resource
    private OutsourcerEvaluateService outsourcerEvaluateService;
    @Resource
    private OutsourcerEvaluateDao outsourcerEvaluateDao;

    @RequestMapping(value = "/getTableTitle", method = RequestMethod.GET)
    @ResponseBody
    public AjaxRes getTableTitle(EvaluateSubBean o) {
        o.setDeptId(Objects.requireNonNull(UserUtil.getLoginUser()).getDeptId());
        AjaxRes ar = outsourcerEvaluateService.getTableTitle(o);
        return ar;
    }

    //该接口未使用
    @RequestMapping(value = "/getTableList", method = RequestMethod.GET)
    @ResponseBody
    public AjaxRes getTableList(EvaluateSubBean o) {
        o.setDeptId(Objects.requireNonNull(UserUtil.getLoginUser()).getDeptId());
        AjaxRes ar = outsourcerEvaluateService.getTableList(o);
        return ar;
    }

    @RequestMapping(value = "/getCollectData", method = RequestMethod.GET)
    @ResponseBody
    public AjaxRes getCollectData(EvaluateSubBean o) {
        o.setDeptId(Objects.requireNonNull(UserUtil.getLoginUser()).getDeptId());
        AjaxRes ar = outsourcerEvaluateService.getCollectData(o);
        return ar;
    }
    @RequestMapping(value = "/getTotalTitle", method = RequestMethod.GET)
    @ResponseBody
    public AjaxRes getTotalTitle(EvaluateSubBean o) {
        o.setDeptId(Objects.requireNonNull(UserUtil.getLoginUser()).getDeptId());
        AjaxRes ar = outsourcerEvaluateService.getTotalTitle(o);
        return ar;
    }
    @RequestMapping(value = "/getCollectTitle", method = RequestMethod.GET)
    @ResponseBody
    public AjaxRes getCollectTitle(EvaluateSubBean o) {
        o.setDeptId(Objects.requireNonNull(UserUtil.getLoginUser()).getDeptId());
        AjaxRes ar = outsourcerEvaluateService.getCollectTitle(o);
        return ar;
    }


    /**
     * 外包商评价列表
     *
     * @param o OutsourceBean
     * @return AjaxRes
     */
    @RequestMapping(path = "outsourcerEvaluateList", method = RequestMethod.GET)
    @ResponseBody
    public AjaxRes outsourcerEvaluateList(OutSourceBean o) {
        AjaxRes ar = getAjaxRes();
        try {
            List<OutSourceBean> list = outsourcerEvaluateService.getTeamEvaluateList(o);
            ar.setListSucceed(list);
        } catch (Exception e) {
            logger.error(e.toString(), e);
            ar.setFailMsg(GlobalConst.DATA_FAIL);
        }
        return ar;
    }


    /**
     * 外包商评价
     * @param o
     * @return
     */
    @RequestMapping("saveEvaluateData")
    @ResponseBody
    public AjaxRes saveEvaluateData(EvaluateDataBean o) {
        AjaxRes ar = new AjaxRes();
        try {
            ar = outsourcerEvaluateService.saveEvaluateData(o);
        } catch (Exception e) {
            ar.setFailMsg(GlobalConst.DATA_FAIL);
        }
        return ar;
    }

    @RequestMapping("updateEvaluateData")
    @ResponseBody
    public AjaxRes updateEvaluateData(EvaluateDataBean o) {
        AjaxRes ar = new AjaxRes();
        try {
            ar = outsourcerEvaluateService.updateEvaluateData(o);
        } catch (Exception e) {
            ar.setFailMsg(GlobalConst.DATA_FAIL);
        }
        return ar;
    }

    @RequestMapping(path = "getEvaluateAuditList", method = RequestMethod.GET)
    @ResponseBody
    public AjaxRes getEvaluateAuditList(OutSourceBean o) {
        AjaxRes ar = getAjaxRes();
        try {
//            if (StringUtils.isBlank(o.getDeptId())) {
//                ar.setFailMsg("部门ID不能为空");
//                return ar;
//            }
//            if (!Arrays.asList(UserUtil.getLoginUser().getRoleId().split(",")).contains("4")) {
//                ar.setFailMsg("您没有当前的权限");
//            }
            o.setDeptId(UserUtil.getLoginUser().getDeptId());
            String isBusinessDivision = outsourcerEvaluateDao.getIsBusinessDivision(o.getDeptId());
            if (!StringUtils.isBlank(isBusinessDivision) && "1".equals(isBusinessDivision)) {
                o.setIsBusinessDivision("1");
            }else{
                o.setIsBusinessDivision("0");
            }
            List<OutSourceBean> list = outsourcerEvaluateService.getEvaluateAuditList(o);
            ar.setListSucceed(list);
        } catch (Exception e) {
            logger.error(e.toString(), e);
            ar.setFailMsg(GlobalConst.DATA_FAIL);
        }
        return ar;
    }

    @RequestMapping(value = "/getAuditTitleData", method = RequestMethod.GET)
    @ResponseBody
    public AjaxRes getAuditTitleData(EvaluateSubBean o) {
        if (StringUtils.isBlank(o.getDeptId())) {
            o.setDeptId(UserUtil.getLoginUser().getDeptId());
        }
        AjaxRes ar = outsourcerEvaluateService.getAuditTitleData(o);
        return ar;
    }

    @RequestMapping("allAudit")
    @ResponseBody
    public synchronized AjaxRes allAudit(EvaluateDataBean o) {
        AjaxRes ar = new AjaxRes();
        List<String> stringList = outsourcerEvaluateDao.getExaminePersonByDeptAndRoleName("7","汇总审批人");
        if(StringUtils.isBlank(o.getEvaluateId())){
            ar.setFailMsg("评价ID不能为空");
            return ar;
        }

        if(stringList==null || stringList.size() == 0){
            ar.setFailMsg("请先配置汇总审批人");
            return ar;

        }

        o.setUserId(String.valueOf(UserUtil.getLoginUser().getId()));
        if (StringUtils.isBlank(o.getRejectReason())) {
            o.setRejectReason("");
        } else {
            o.setIsApprove("2");
        }
        //修改pj_evaluate_details状态
        outsourcerEvaluateDao.updatePjEvaluateDetailsStatusByThreeParams(o);

        int code = outsourcerEvaluateDao.auditByThreeParams(o);
        if (code > 0) {
            ar.setSucceedMsg("审核成功");
        } else {
            ar.setFailMsg("审核失败");
        }
        //修改pj_evaluate状态
        outsourcerEvaluateDao.updatePjEvaluateDetailsStatusByThreeParams(o);

        //从result表根据evaluate_id对deptId分类查询已经评价的deptId
        List<String> deptIdList = outsourcerEvaluateDao.getPjEvaluateResultDeptId(o);
        //从pj_task_evaluated 根据evaluate_id 查询需要评价的postId
        List<String> postIdList = outsourcerEvaluateDao.getPjTaskEvaluatedPostId(o);
        Collections.sort(deptIdList);
        Collections.sort(postIdList);
        //对两次查询的结果判断是否完全相同
        if (deptIdList.equals(postIdList)){
            int startId  = outsourcerEvaluateService.startCollectExamineByEvaluateId(o);
            String evaluateType = o.getEvaluateType();
            System.err.println("startId:"+startId+" ,evaluateType="+evaluateType);
            if(startId == 0 && "1".equals(evaluateType)){

                int examineNum = outsourcerEvaluateDao.getExamineNumByEvaluateId(o.getEvaluateId(),"1");
                if(examineNum == 0){
                    //新增二级审核
                    ExamineBean childBean = new ExamineBean();
                    childBean.setEvaluateId(o.getEvaluateId());
                    //添加汇总审核人id
                    childBean.setUserList(String.valueOf(String.join(",",stringList)));
                    //添加汇总审核人姓名
                    childBean.setPostId("7");
                    childBean.setEvaluateType("0");
                    childBean.setEvaluateNode("1");
                    outsourcerEvaluateDao.addExaminePerson(childBean);
                }

            } else if (startId == 0 && "3".equals(evaluateType)) {
                //汇总审核结束 更新状态
                outsourcerEvaluateDao.updateEvaluateRecordByEvaluateId("2",o.getEvaluateId());
                //添加到月度排名表
                addMonthRank(o);
            }else{
                //过程中 暂不做处理

            }
        }
        if("1".equals(o.getType())){
            outsourcerEvaluateDao.updateEvalStatus("3",o.getEvaluateId());
        }else {
            outsourcerEvaluateDao.updateEvalStatus("4",o.getEvaluateId());
        }


        return  ar;
    }
    /**
     * 添加到月度排名表
     * @param o
     */
    private void addMonthRank(EvaluateDataBean o) {
        //添加到月度排名表
        EvaluateSubBean subBean = new EvaluateSubBean();
        subBean.setEvaluateId(o.getEvaluateId());
        subBean.setTemplateId(o.getTemplateId());
        subBean.setType("total");
        AjaxRes ajaxRes = getCollectTitle(subBean);
        JSONArray childDataList = JSONArray.parseArray(ajaxRes.getResMsg());

        List<EvaluateDataBean> dataBeanList = outsourcerEvaluateDao.getEvaluateSubInfo(o);
        o.setUserName(UserUtil.getLoginUser().getNickname());
        dataBeanList.forEach(dataBean -> {
            childDataList.forEach(item ->{
                if ( dataBean.getSubId().equals(((JSONObject) item).getString("subId"))) {
                    //取出item中的所有包含total的数据
                    dataBean.setTotalScore(String.format("%.2f", ((JSONObject) item).getDouble("totalScore")));
                    dataBean.setTitleName(dataBean.getEvaluateDate() + "对标得分");
                }
            });
        });
        String deptId = outsourcerEvaluateDao.getOrgIddByEvaluateId(o.getEvaluateId());
        o.setDeptId(deptId);
        outsourcerEvaluateDao.addMonthRank(o,dataBeanList);
    }

    @RequestMapping("audit")
    @ResponseBody
    public synchronized AjaxRes audit(EvaluateDataBean o) {
        AjaxRes ar = new AjaxRes();
        List<String> stringList = outsourcerEvaluateDao.getExaminePersonByDeptAndRoleName("7","汇总审批人");
        if(StringUtils.isBlank(o.getEvaluateId())){
            ar.setFailMsg("评价ID不能为空");
            return ar;
        }

        if(stringList==null || stringList.size() == 0){
            ar.setFailMsg("请先配置汇总审批人");
            return ar;

        }
        try {
            o.setUserId(String.valueOf(UserUtil.getLoginUser().getId()));
            if (StringUtils.isBlank(o.getRejectReason())) {
                o.setRejectReason("");
            } else {
                o.setIsApprove("2");
                //修改pj_evaluate_details状态
                outsourcerEvaluateDao.updatepjEvaluateDetailsStatus(o);

            }

            int code = outsourcerEvaluateDao.audit(o);
            if (code > 0) {
                ar.setSucceedMsg("审核成功");
            } else {
                ar.setFailMsg("审核失败");
            }
            //查询当前的审核状态
            int count = outsourcerEvaluateDao.getCurrentIsApprove(o);
            if (count == 0) {
                //修改pj_evaluate状态
                o.setIsApprove("1");
                outsourcerEvaluateDao.updatepjEvaluateDetailsStatus(o);
            }
            //从result表根据evaluate_id对deptId分类查询已经评价的deptId
            List<String> deptIdList = outsourcerEvaluateDao.getPjEvaluateResultDeptId(o);
            //从pj_task_evaluated 根据evaluate_id 查询需要评价的postId
            List<String> postIdList = outsourcerEvaluateDao.getPjTaskEvaluatedPostId(o);
            Collections.sort(deptIdList);
            Collections.sort(postIdList);
            //对两次查询的结果判断是否完全相同
            if (deptIdList.equals(postIdList)){
                int startId  = outsourcerEvaluateService.startCollectExamineByEvaluateId(o);
                String evaluateType = o.getEvaluateType();
                System.err.println("startId:"+startId+" ,evaluateType="+evaluateType);
                if(startId == 0 && "1".equals(evaluateType)){

                    int examineNum = outsourcerEvaluateDao.getExamineNumByEvaluateId(o.getEvaluateId(),"1");
                    if(examineNum == 0){
                        //新增二级审核
                        ExamineBean childBean = new ExamineBean();
                        childBean.setEvaluateId(o.getEvaluateId());
                        //添加汇总审核人id
                        childBean.setUserList(String.valueOf(String.join(",",stringList)));
                        //添加汇总审核人姓名
                        childBean.setPostId("7");
                        childBean.setEvaluateType("0");
                        childBean.setEvaluateNode("1");
                        outsourcerEvaluateDao.addExaminePerson(childBean);
                    }

                } else if (startId == 0 && "3".equals(evaluateType)) {
                    //汇总审核结束 更新状态
                    outsourcerEvaluateDao.updateEvaluateRecordByEvaluateId("2",o.getEvaluateId());
                    //添加到月度排名表
                    addMonthRank(o);
                }else{
                    //过程中 暂不做处理

                }
            }
        if("1".equals(o.getType())){
            outsourcerEvaluateDao.updateEvalStatus("2",o.getEvaluateId());
        }else {
            outsourcerEvaluateDao.updateEvalStatus("4",o.getEvaluateId());
        }

        } catch (Exception e) {
            ar.setFailMsg("审核失败");
        }
        return ar;
    }


    @RequestMapping("getAuditBtn")
    @ResponseBody
    public AjaxRes getAuditBtn(EvaluateDataBean o) {
        AjaxRes ar = new AjaxRes();
        try {
            ar = outsourcerEvaluateService.getAuditBtn(o);
        } catch (Exception e) {
            ar.setFailMsg(GlobalConst.DATA_FAIL);
        }
        return ar;
    }

    /**
     * 查看第一级是否审核
     * @param o
     * @return
     */
    @RequestMapping("isCheckOneIsAudit")
    @ResponseBody
    public AjaxRes isCheckOneIsAudit(EvaluateDataBean o) {
        AjaxRes ar = new AjaxRes();
        try {
            ar = outsourcerEvaluateService.isCheckOneIsAudit(o);
        } catch (Exception e) {
            ar.setFailMsg(GlobalConst.DATA_FAIL);
        }
        return ar;
    }

    /**
     * 查看第二级是否审核
     * @param o
     * @return
     */
    @RequestMapping("isCheckTwoIsAudit")
    @ResponseBody
    public AjaxRes isCheckTwoIsAudit(EvaluateDataBean o) {
        AjaxRes ar = new AjaxRes();
        try {
            ar = outsourcerEvaluateService.isCheckTwoIsAudit(o);
        } catch (Exception e) {
            ar.setFailMsg(GlobalConst.DATA_FAIL);
        }
        return ar;
    }


    /**
     * 专员审核
     * @param o
     * @return
     */
    @RequestMapping("dedicatedAudit")
    @ResponseBody
    public synchronized AjaxRes dedicatedAudit(EvaluateDataBean o) {
        AjaxRes ar = new AjaxRes();
        List<String> stringList = outsourcerEvaluateDao.getExaminePersonByDeptAndRoleName("7","专责");
        if(StringUtils.isBlank(o.getEvaluateId())){
            ar.setFailMsg("评价ID不能为空");
            return ar;
        }

        if(stringList==null || stringList.size() == 0){
            ar.setFailMsg("请先配置专责审批人");
            return ar;
        }
        try {
            o.setUserId(String.valueOf(UserUtil.getLoginUser().getId()));
            if (StringUtils.isBlank(o.getRejectReason())) {
                o.setRejectReason("");
            } else {
                o.setIsApprove("2");
                //修改pj_evaluate_details状态
                outsourcerEvaluateDao.updatepjEvaluateDetailsStatus(o);
            }
            int code = outsourcerEvaluateDao.audit(o);
            if (code > 0) {
                ar.setSucceedMsg("审核成功");
            } else {
                ar.setFailMsg("审核失败");
            }
            //查询当前的审核状态
            int count = outsourcerEvaluateDao.getCurrentIsApprove(o);
            if (count == 0) {
                //修改pj_evaluate状态
                o.setIsApprove("1");
                outsourcerEvaluateDao.updatepjEvaluateDetailsStatus(o);
            }
        } catch (Exception e) {
            ar.setFailMsg("审核失败");
        }
        return ar;
    }

    @RequestMapping("dedicatedAllAudit")
    @ResponseBody
    public synchronized AjaxRes dedicatedAllAudit(EvaluateDataBean o) {
        AjaxRes ar = new AjaxRes();
        List<String> stringList = outsourcerEvaluateDao.getExaminePersonByDeptAndRoleName("7","专责");
        if(StringUtils.isBlank(o.getEvaluateId())){
            ar.setFailMsg("评价ID不能为空");
            return ar;
        }

        if(stringList==null || stringList.size() == 0){
            ar.setFailMsg("请先配置专责审批人");
            return ar;

        }

        o.setUserId(String.valueOf(UserUtil.getLoginUser().getId()));
        if (StringUtils.isBlank(o.getRejectReason())) {
            o.setRejectReason("");
        } else {
            o.setIsApprove("2");
        }
        //修改pj_evaluate_details状态
        outsourcerEvaluateDao.updatePjEvaluateDetailsStatusByThreeParams(o);

        int code = outsourcerEvaluateDao.auditByThreeParams(o);
        if (code > 0) {
            ar.setSucceedMsg("审核成功");
        } else {
            ar.setFailMsg("审核失败");
        }
        //修改pj_evaluate状态
        outsourcerEvaluateDao.updatePjEvaluateDetailsStatusByThreeParams(o);

        int startId  = outsourcerEvaluateService.startCollectExamineByEvaluateId(o);
        String evaluateType = o.getEvaluateType();
        System.err.println("startId:"+startId+" ,evaluateType="+evaluateType);
        if(startId == 0 && ("1".equals(evaluateType) || "2".equals(evaluateType))){

            int examineNum = outsourcerEvaluateDao.getExamineNumByEvaluateId(o.getEvaluateId(),"1");
            if(examineNum == 0){
                //新增二级审核
                ExamineBean childBean = new ExamineBean();
                childBean.setEvaluateId(o.getEvaluateId());
                //添加汇总审核人id
                childBean.setUserList(String.valueOf(String.join(",",stringList)));
                //添加汇总审核人姓名
                childBean.setPostId("7");
                childBean.setEvaluateType("0");
                childBean.setEvaluateNode("1");
                outsourcerEvaluateDao.addExaminePerson(childBean);
            }

        } else if (startId == 0 && "3".equals(evaluateType)) {
            //汇总审核结束 更新状态
            outsourcerEvaluateDao.updateEvaluateRecordByEvaluateId("2",o.getEvaluateId());
        }else{
            //过程中 暂不做处理

        }
        if("1".equals(o.getType())){
            outsourcerEvaluateDao.updateEvalStatus("2",o.getEvaluateId());
        }else {
            outsourcerEvaluateDao.updateEvalStatus("4",o.getEvaluateId());
        }

        return  ar;
    }

    @RequestMapping("updateJsonData")
    @ResponseBody
    public AjaxRes updateJsonData(EvaluateDataBean o) {
        AjaxRes ar = new AjaxRes();
        try {
            ar = outsourcerEvaluateDao.updateJsonData(o);
        } catch (Exception e) {
            ar.setFailMsg(GlobalConst.DATA_FAIL);
        }
        return ar;
    }

    @RequestMapping("fullApproval")
    @ResponseBody
    public AjaxRes fullApproval(EvaluateDataBean o) {
        AjaxRes ar = new AjaxRes();

        //需要evaluateId templateId postId
        try {
            ar = outsourcerEvaluateService.fullApproval(o);
        } catch (Exception e) {
            ar.setFailMsg("审核失败");
        }
        return ar;
    }

    @RequestMapping(value = "getSummaryCompareList", method = RequestMethod.GET)
    @ResponseBody
    public AjaxRes getSummaryCompareList(EvaluateSubBean o) {
        AjaxRes ar = new AjaxRes();
        try {
            ar = outsourcerEvaluateService.getSummaryCompareList(o);
        } catch (Exception e) {
            ar.setFailMsg(GlobalConst.DATA_FAIL);
        }
        return ar;
    }

}
