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

import com.bonus.gs.sub.evaluate.evaluate.beans.TeamEvaluateBean;
import com.bonus.gs.sub.evaluate.evaluate.service.TeamEvaluateService;
import com.bonus.gs.sub.evaluate.manager.annotation.LogAnnotation;
import com.bonus.gs.sub.evaluate.manager.controller.BaseController;
import com.bonus.gs.sub.evaluate.manager.utils.*;
import io.swagger.annotations.ApiOperation;
import org.apache.catalina.security.SecurityUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.*;

/**
 * @className:TeamEvaluateController
 * @author:cwchen
 * @date:2024-11-18-18:00
 * @version:1.0
 * @description:班组评价
 */
@Controller
@RequestMapping("/backstage/teamEvaluate/")
public class TeamEvaluateController extends BaseController<TeamEvaluateBean> {

    @Autowired
    private TeamEvaluateService service;

    @RequestMapping(value = "findByPage", method = RequestMethod.POST)
    @ResponseBody
    public AjaxRes findByPage(Page<TeamEvaluateBean> page, TeamEvaluateBean o) {
        AjaxRes ar = getAjaxRes();
//        try {
            // shiro获取用户信息,shiro管理的session
            // 获得用户
//            if (o.getOperType() == 1) { // 项目经理评价
//                o.setParentId(Integer.parseInt(userBean.getDeptId()));
//            }
//            Page<TeamEvaluateBean> result = service.findByPage(o, page);
//            List<TeamEvaluateBean> list = result.getResults();
//            for (TeamEvaluateBean bean : list) {
//                String sendPhone = bean.getSendPhone();
//                if(StringUtils.isBlank(sendPhone)){
//                    String sendPhone2 = service.getSendPhone(bean);
//                    bean.setSendPhone(sendPhone2);
//                }
//            }
//            Map<String, Object> p = new HashMap<String, Object>();
//            p.put("list", result);
//            ar.setSucceed(p);
//        } catch (Exception e) {
//            logger.error(e.toString(), e);
//            ar.setFailMsg(GlobalConst.DATA_FAIL);
//        }
        return ar;
    }

    @GetMapping("getTeamEvaluateList")
    @ResponseBody
    public AjaxRes getTeamEvaluateList(TeamEvaluateBean o){
        AjaxRes ar = getAjaxRes();
        if (o.getOperType() == 1) { // 项目经理评价
            //TODO 获取部门id
            o.setParentId(Integer.parseInt("1"));
        }
        List<TeamEvaluateBean> list = service.getTeamEvaluateList(o);
        for (TeamEvaluateBean bean : list) {
            String sendPhone = bean.getSendPhone();
            if (StringUtils.isBlank(sendPhone)) {
                String sendPhone2 = service.getSendPhone(bean);
                bean.setSendPhone(sendPhone2);
            }
        }
        ar.setListSucceed(list);
        return ar;
    }



    /**
     * 评价/审核/重新评价
     *
     * @param bean
     * @return AjaxRes
     * @author cwchen
     * @date 2024/11/19 16:44
     */
    @RequestMapping(value = "evaluateData", method = RequestMethod.POST)
    @ResponseBody
    public AjaxRes evaluateData(@RequestBody TeamEvaluateBean bean) {
        bean.setRoleId(UserUtil.getLoginUser().getRoleId());
        return service.evaluateData(bean);
    }

    /**
     * 获取评价详情
     *
     * @param bean
     * @return AjaxRes
     * @author cwchen
     * @date 2024/11/19 17:14
     */
    @RequestMapping(value = "getEvaluateData", method = RequestMethod.GET)
    @ResponseBody
    public AjaxRes getEvaluateData(TeamEvaluateBean bean) {
        return service.getEvaluateData(bean);
    }

    /**
     * 通知
     *
     * @param bean
     * @return AjaxRes
     * @author cwchen
     * @date 2024/11/19 17:50
     */
    @RequestMapping(value = "notification", method = RequestMethod.POST)
    @ResponseBody
    public AjaxRes notification(@RequestBody TeamEvaluateBean bean) {
        return service.notification(bean);
    }

    /**
     * 下载
     *
     * @param request
     * @param response
     * @param bean
     * @return void
     * @author cwchen
     * @date 2024/11/20 14:10
     */
    @RequestMapping(value = "/exportByDoc", method = RequestMethod.GET)
    public void exportByDoc(HttpServletRequest request, HttpServletResponse response, TeamEvaluateBean bean) {
        try {
            AjaxRes ar = service.getEvaluateData(bean);
            TeamEvaluateBean vo = (TeamEvaluateBean) ar.getObj();
            String title = setNullValue(vo.getProName()) + setNullValue(vo.getSubName()) + setNullValue(vo.getTeamName()), ftlName = "evaluate_model.ftl";
            Map<String, Object> data = new HashMap<String, Object>(16);
            data.put("title", title);
            data.put("subName", setNullValue(vo.getSubName()));
            data.put("teamName", setNullValue(vo.getTeamName()));
            data.put("userName", setNullValue(vo.getUserName()));
            data.put("manager", setNullValue(vo.getManager()));
            data.put("evaluateTime", vo.getEvaluateTime());
            String[] markArr = vo.getMark().split("@@");
            data.put("name", markArr[0]);
            data.put("name2", markArr[1]);
            data.put("name3", markArr[2]);
            data.put("name4", markArr[3]);
            data.put("name5", markArr[4]);
            if (Objects.equals(vo.getLevel(), "1")) {
                data.put("l1", "✔");
                data.put("l2", "");
                data.put("l3", "");
                data.put("l4", "");
            } else if (Objects.equals(vo.getLevel(), "2")) {
                data.put("l1", "");
                data.put("l2", "✔");
                data.put("l3", "");
                data.put("l4", "");
            } else if (Objects.equals(vo.getLevel(), "3")) {
                data.put("l1", "");
                data.put("l2", "");
                data.put("l3", "✔");
                data.put("l4", "");
            } else if (Objects.equals(vo.getLevel(), "4")) {
                data.put("l1", "");
                data.put("l2", "");
                data.put("l3", "");
                data.put("l4", "✔");
            }
            WordUtils.exportMillCertificateWord(request, response, data, title + "评价表", ftlName);
            System.err.println("评价表生成完毕");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String setNullValue(String value) {
        if (StringUtils.isBlank(value)) {
            return "";
        } else {
            return value;
        }
    }


    /**
     * 导出退场班组评价列表
     *
     * @param request
     * @param response
     * @param bean
     * @return void
     * @author cwchen
     * @date 2024/11/20 14:32
     */
    @RequestMapping("exportExcelData")
    public void exportability(HttpServletRequest request, HttpServletResponse response, TeamEvaluateBean bean) {
        String filename = "退场班组评价";
        // shiro获取用户信息,shiro管理的session
//        String deptId = UserUtil.getLoginUser().getDeptId();
        //TODO 获取部门id
        String deptId = "1";
        if (bean.getOperType() == 1) { // 项目经理评价
            bean.setParentId(Integer.parseInt(deptId));
        }
        List<TeamEvaluateBean> list = service.getExportExcelData(bean);
        // 导出所有人员基本信息
        try {
            for (TeamEvaluateBean vo : list) {
                if (bean.getOperType() == 1 || bean.getOperType() == 3) {
                    if (Objects.equals("评价驳回", vo.getCheckStatus())) {
                        vo.setEvStatus("评价驳回");
                    }
                } else if (bean.getOperType() == 2) {
                    if (Objects.equals("待评价", vo.getEvStatus())) {
                        vo.setEvaluateTime("");
                    }
                }
            }
            excelOut(response, list, filename, "退场班组评价", bean.getOperType());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void excelOut(HttpServletResponse response, List<TeamEvaluateBean> registlist, String filename, String sheetname, int operType)
            throws Exception {
        if (registlist != null) {
            List<Map<String, Object>> results = new ArrayList<Map<String, Object>>();
            int size = registlist.size();
            for (int i = 0; i < size; i++) {
                TeamEvaluateBean bean = registlist.get(i);
                Map<String, Object> maps = outVehicleOilBeanMap(i, bean, sheetname, operType);
                results.add(maps);
            }
            List<String> headers = outVehicleOilHeaders(sheetname, operType);
            HSSFWorkbook workbook = POIOutputHelperNumBer.excel(results, headers, filename);
            OutputStream out = null;
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.addHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode(filename, "UTF-8") + ".xls");
            response.setHeader("Pragma", "No-cache");
            out = response.getOutputStream();
            workbook.write(out);
            out.flush();
            out.close();
        }
    }

    private Map<String, Object> outVehicleOilBeanMap(int i, TeamEvaluateBean bean, String sheetname, int operType) {
        Map<String, Object> maps = new LinkedHashMap<String, Object>();
        maps.put("id", i + 1);
        switch (operType) {
            case 1:
                maps.put("teamName", bean.getTeamName());
                maps.put("userName", bean.getUserName());
                maps.put("phone", bean.getPhone());
                maps.put("subName", bean.getSubName());
                maps.put("proName", bean.getProName());
                maps.put("evStatus", bean.getEvStatus());
                maps.put("rejectReason", bean.getRejectReason());
                break;
            case 2:
                maps.put("teamName", bean.getTeamName());
                maps.put("userName", bean.getUserName());
                maps.put("phone", bean.getPhone());
                maps.put("subName", bean.getSubName());
                maps.put("proName", bean.getProName());
                maps.put("checkStatus", bean.getCheckStatus());
                maps.put("manager", bean.getManager());
                maps.put("evaluateTime", bean.getEvaluateTime());
                break;
            case 3:
                maps.put("teamName", bean.getTeamName());
                maps.put("userName", bean.getUserName());
                maps.put("phone", bean.getPhone());
                maps.put("subName", bean.getSubName());
                maps.put("proName", bean.getProName());
                maps.put("evStatus", bean.getEvStatus());
                maps.put("manager", bean.getManager());
                maps.put("level", bean.getLevel());
                break;
            default:
                break;
        }

        return maps;
    }

    private List<String> outVehicleOilHeaders(String sheetname, int operType) {
        ArrayList<String> list = new ArrayList<String>();
        list.add("序号");

        switch (operType) {
            case 1:
                list.add("班组名称");
                list.add("班长");
                list.add("班长联系方式");
                list.add("退场前所属外包商");
                list.add("退场前所属项目");
                list.add("评价状态");
                list.add("驳回原因");
                break;
            case 2:
                list.add("班组名称");
                list.add("班长");
                list.add("班长联系方式");
                list.add("退场前所属外包商");
                list.add("退场前所属项目");
                list.add("审核状态");
                list.add("项目经理");
                list.add("评价时间");
                break;
            case 3:
                list.add("班组名称");
                list.add("班长");
                list.add("班长联系方式");
                list.add("退场前所属外包商");
                list.add("退场前所属项目");
                list.add("评价状态");
                list.add("项目经理");
                list.add("评价结果");
                break;
            default:
                break;
        }
        return list;
    }
}
