package com.lz.modules.performance.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import cn.hutool.poi.excel.StyleSet;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.lz.modules.app.entity.StaffEntity;
import com.lz.modules.app.service.StaffService;
import com.lz.modules.flow.model.ResultDetailDto;
import com.lz.modules.flow.model.ResultRecordDetailDto;
import com.lz.modules.flow.model.ResultRecortModelDto;
import com.lz.modules.job.business.DingtalkBusiness;
import com.lz.modules.performance.dto.RecordDetailExportDto;
import com.lz.modules.performance.enums.ResultFlowProcessEnum;
import com.lz.modules.performance.req.ChartResultReq;
import com.lz.modules.performance.res.LevelDetailExportRes;
import com.lz.modules.performance.service.ChartResultService;
import com.lz.modules.sys.service.app.ResultRecordService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.seimicrawler.xpath.JXDocument;
import org.seimicrawler.xpath.JXNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: djc
 * @Desc:
 * @Date: 2020/12/1 10:26
 */
@RestController
@RequestMapping("/file")
@Slf4j
@Api(value="导出excel接口", tags={"导出表格"})
public class ExportController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private ChartResultService chartResultService;
    @Autowired
    DingtalkBusiness dingtalkBusiness;
    @Autowired
    private ResultRecordService resultRecordService;
    @Autowired
    private StaffService staffService;

    static final List<Integer> process = Lists.newArrayList(ResultFlowProcessEnum.TARGET.getStatus(), ResultFlowProcessEnum.CONFIRM.getStatus(),
            ResultFlowProcessEnum.DO.getStatus(), ResultFlowProcessEnum.WRITE.getStatus());

    @GetMapping("/export/levelDetail")
    @ApiOperation("导出等级详情")
    public void levelDetail(ChartResultReq req,HttpServletResponse response){
        try {
            //Long userId = getUserId();
            Long userId = 313L;
            req.setLoginUserId(userId);
            //获取数据
            List data = chartResultService.selectLevelDetailList(req);
            //导出
            buildLevelExcelExport(data,response);

        } catch (Exception e) {
            log.error("导出等级详情异常，e: ",e);
        }

    }




    @GetMapping("/export/recordDetail")
    @ApiOperation("导出绩效详情")
    public void recordDetail(ResultRecordDetailDto dto, HttpServletResponse response){
        try {
            String test = "";

            if(CollectionUtils.isEmpty(dto.getRecortModelDtos())){
                log.info("没有模板信息，无法生成,id: " + dto.getId());
            }
            ResultRecordDetailDto testDto = com.alibaba.fastjson.JSONObject.parseObject(test,ResultRecordDetailDto.class);

            buildRecordExcelExport(testDto, response);

        } catch (Exception e) {
            log.error("导出绩效详情异常，e: ",e);
        }

    }

    @GetMapping("/testDingTalkTask")
    public void testDingTalkTask(){
        List<Long> ids = resultRecordService.selectStaffIdsByFlowProcess(process);
        log.info(JSON.toJSONString(ids));
        List<Long> objects = Lists.newArrayList(313L,314L,294L);
        List<StaffEntity> staffEntities = staffService.selectByIds(objects);
        String res = dingtalkBusiness.sendTaskInputMsg(staffEntities);
        logger.info("绩效任务填写通知响应：" + res);
    }



    //对应实体属性名与表列名
    private void buildHeaderData(Class<?> data,List<String> tags,ExcelWriter writer){
        if(data == null || CollectionUtils.isEmpty(tags)){
            log.info("导出excel-实体属性或数据为空!");
            return;
        }
        Field[] fields = data.getDeclaredFields();
        if(fields.length != tags.size()){
            log.info("导出excel-实体属性与数据大小不一致!");
            return;
        }
        for(int i=0; i<fields.length; i++){
            Field field = fields[i];
            field.setAccessible(true);
            writer.addHeaderAlias(field.getName(), tags.get(i));
        }
    }

    private void buildLevelExcelExport(List data, HttpServletResponse response){
        //设置表头表尾及数据
        List<String> rowHead = CollUtil.newArrayList("序号", "工号", "员工姓名", "当月状态", "一级部门", "二级部门", "三级部门", "职位", "员工月度绩效考核评分","员工月度绩效考核结果等级");
        ExcelWriter writer = ExcelUtil.getWriter();
        writer.setColumnWidth(-1,15);
        writer.passRows(4);
        buildHeaderData(LevelDetailExportRes.class,rowHead,writer);
        writer.merge(0,2,0,9,"绩效考核总表",false);
        writer.merge(3,3,0,1,"考核月份",false);
        writer.write(data, true);
        writer.merge(7 + data.size(),8 + data.size(),0,0,"签字",false);

        //设置下拉框数据
        String[] values = {"已转正", "试用期"};
        Sheet sheet = writer.getSheet();
        int firstRow = 4;
        int lastRow = 4;
        int firstCol = 3;
        int lastCol = 3;
        CellRangeAddressList addressList = new CellRangeAddressList(firstRow, lastRow, firstCol, lastCol);
        StyleSet styleSet = writer.getStyleSet();
        CellStyle cellStyle = styleSet.getCellStyle();
        cellStyle.setDataFormat((short) BuiltinFormats.getBuiltinFormat("text"));
        DataValidationHelper helper = sheet.getDataValidationHelper();
        DataValidationConstraint constraint = helper.createExplicitListConstraint(values);
        DataValidation dataValidation = helper.createValidation(constraint, addressList);
        writer.addValidationData(dataValidation);

         //响应
        String name = "test测试";
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + name + ".xls");
        ServletOutputStream out = null;
        try {
            out = response.getOutputStream();
            writer.flush(out, true);
        }
        catch (IOException e) {
            log.error("生成excel文档异常，e: ",e);
        }
        finally {
            writer.close();
        }
        IoUtil.close(out);
    }


    private void buildRecordExcelExport(ResultRecordDetailDto dto, HttpServletResponse response){
        //设置表头表尾及数据
        List<String> row = CollUtil.newArrayList("考核月份", "09", "工号", "YN", "员工姓名", "老白", "一级部门", "业务中台", "二级部门","技术中心", "三级部门","攻关小组", "职位","java", "直属上级","佟湘玉");
        List<String> rowHead = CollUtil.newArrayList("考核维度", "目标/指标", "关键结果", "考核权重", "考核结果（员工填写）", "直属上级评分（100%）", "得分","评分说明（直属上级填写）");
        ExcelWriter writer = ExcelUtil.getWriter();
        writer.setColumnWidth(-1,15);
        writer.passRows(3);


        buildHeaderData(RecordDetailExportDto.class,rowHead,writer);
        writer.merge(0,2,0,9,"员工月度绩效计划与评估表",false);
        writer.writeHeadRow(row);
        List<ResultRecortModelDto> recortModelDtos = dto.getRecortModelDtos();
        List data = Lists.newArrayList();
        int mergeStart = 5;
        for(ResultRecortModelDto modelDto:recortModelDtos){
            //维度名称
            String name = modelDto.getName();
            //详细条目
            List<ResultDetailDto> detailDtos = modelDto.getDetailDtos();

            List<RecordDetailExportDto> collect = detailDtos.stream().map(resultDetailDto -> {
                RecordDetailExportDto detailExportDto = new RecordDetailExportDto();
                BeanUtils.copyProperties(resultDetailDto, detailExportDto);
                detailExportDto.setName(name);
                return detailExportDto;
            }).collect(Collectors.toList());
            data.addAll(collect);
            int i = mergeStart + collect.size();
            writer.merge(mergeStart,i -1,0,0,null,false);
            //添加汇总
            RecordDetailExportDto add = new RecordDetailExportDto();
            add.setAcquireScore(BigDecimal.valueOf(0.01));
            add.setKeyResult(name + "考核结果");
            add.setCheckWeight(modelDto.getWeight());
            writer.merge(i,mergeStart + collect.size(),0,1,null,false);
            //1为跳过插入的记录
            mergeStart = i + 1;
            data.add(add);
        }

        //设置尾部
        RecordDetailExportDto add;
        add = new RecordDetailExportDto();
        add.setName("最终绩效考核评分");
        data.add(add);
        add = new RecordDetailExportDto();
        add.setName("最终绩效考核结果等级");
        data.add(add);
        writer.write(data,true);
        //writer.merge(7 + data.size(),8 + data.size(),0,0,"签字",false);
        //writer.setRowHeight(5,50);
        //设置生效的是没有数据的，有数据的反而不生效
        //writer.setRowHeight(-1,50);

        //响应
        String name = "test测试";
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + name + ".xls");
        ServletOutputStream out = null;
        try {
            out = response.getOutputStream();
            writer.flush(out, true);
        }
        catch (IOException e) {
            log.error("生成excel文档异常，e: ",e);
        }
        finally {
            writer.close();
        }
        IoUtil.close(out);
    }


    /*{\n" +
        "    \"id\": 807,\n" +
                "    \"status\": 0,\n" +
                "    \"lastScore\": null,\n" +
                "    \"allScore\": null,\n" +
                "    \"remark\": null,\n" +
                "    \"staffId\": 303,\n" +
                "    \"startId\": 83,\n" +
                "    \"gradeGroupId\": 1,\n" +
                "    \"flowStaffIdRole\": null,\n" +
                "    \"departmentId\": \"154231708\",\n" +
                "    \"departmentName\": \"技术中心\",\n" +
                "    \"staffName\": \"傅美爱\",\n" +
                "    \"avatar\": \"https://static-legacy.dingtalk.com/media/lADPBbCc1Tp1ysPNAu7NAu4_750_750.jpg\",\n" +
                "    \"jobNumber\": \"9\",\n" +
                "    \"currentApprovalStaffId\": 322,\n" +
                "    \"currentApprovalStaffName\": \"徐虹杰\",\n" +
                "    \"scoreLevel\": null,\n" +
                "    \"flowProcess\": 1,\n" +
                "    \"recortModelDtos\": [\n" +
                "      {\n" +
                "        \"id\": 1276,\n" +
                "        \"name\": \"业绩绩效\",\n" +
                "        \"type\": 1,\n" +
                "        \"weight\": 0.7,\n" +
                "        \"maxCount\": 10,\n" +
                "        \"orderBy\": 0,\n" +
                "        \"detailDtos\": [\n" +
                "          {\n" +
                "            \"id\": 932,\n" +
                "            \"isDelete\": 0,\n" +
                "            \"type\": 1,\n" +
                "            \"target\": \"85496\",\n" +
                "            \"keyResult\": \"56632\",\n" +
                "            \"calculate\": \"0.7*{acquireScore}\",\n" +
                "            \"checkWeight\": 0.7,\n" +
                "            \"checkResult\": null,\n" +
                "            \"superScore\": \"4分-卓越\",\n" +
                "            \"acquireScore\": 0,\n" +
                "            \"scoreComment\": null,\n" +
                "            \"priority\": 0,\n" +
                "            \"scoreDtos\": [\n" +
                "              {\n" +
                "                \"id\": 296,\n" +
                "                \"acquireScore\": 0,\n" +
                "                \"detailId\": 932,\n" +
                "                \"approvalId\": 322,\n" +
                "                \"approvalName\": \"徐虹杰\",\n" +
                "                \"weight\": 1,\n" +
                "                \"calculate\": \"0.7*1.0*{acquireScore}\",\n" +
                "                \"scoreComment\": null\n" +
                "              }\n" +
                "            ],\n" +
                "            \"modelId\": 1276\n" +
                "          },\n" +
                "           {\n" +
                "            \"id\": 932,\n" +
                "            \"isDelete\": 0,\n" +
                "            \"type\": 1,\n" +
                "            \"target\": \"85496\",\n" +
                "            \"keyResult\": \"56632\",\n" +
                "            \"calculate\": \"0.7*{acquireScore}\",\n" +
                "            \"checkWeight\": 0.7,\n" +
                "            \"checkResult\": null,\n" +
                "            \"superScore\": \"4分-卓越\",\n" +
                "            \"acquireScore\": 0,\n" +
                "            \"scoreComment\": null,\n" +
                "            \"priority\": 0,\n" +
                "            \"scoreDtos\": [\n" +
                "              {\n" +
                "                \"id\": 296,\n" +
                "                \"acquireScore\": 0,\n" +
                "                \"detailId\": 932,\n" +
                "                \"approvalId\": 322,\n" +
                "                \"approvalName\": \"徐虹杰\",\n" +
                "                \"weight\": 1,\n" +
                "                \"calculate\": \"0.7*1.0*{acquireScore}\",\n" +
                "                \"scoreComment\": null\n" +
                "              }\n" +
                "            ],\n" +
                "            \"modelId\": 1276\n" +
                "          }\n" +
                "        ]\n" +
                "      },\n" +
                "      {\n" +
                "        \"id\": 1277,\n" +
                "        \"name\": \"文化价值观\",\n" +
                "        \"type\": 1,\n" +
                "        \"weight\": 0.3,\n" +
                "        \"maxCount\": 1,\n" +
                "        \"orderBy\": 1,\n" +
                "        \"detailDtos\": [\n" +
                "          {\n" +
                "            \"id\": 931,\n" +
                "            \"isDelete\": 0,\n" +
                "            \"type\": 1,\n" +
                "            \"target\": \"文化价值观\",\n" +
                "            \"keyResult\": \"发挥个人体会\",\n" +
                "            \"calculate\": \"0.3*{acquireScore}\",\n" +
                "            \"checkWeight\": 0.3,\n" +
                "            \"checkResult\": null,\n" +
                "            \"superScore\": null,\n" +
                "            \"acquireScore\": 0,\n" +
                "            \"scoreComment\": null,\n" +
                "            \"priority\": 0,\n" +
                "            \"scoreDtos\": [\n" +
                "              {\n" +
                "                \"id\": 295,\n" +
                "                \"acquireScore\": 0,\n" +
                "                \"detailId\": 931,\n" +
                "                \"approvalId\": 322,\n" +
                "                \"approvalName\": \"徐虹杰\",\n" +
                "                \"weight\": 1,\n" +
                "                \"calculate\": \"0.3*1.0*{acquireScore}\",\n" +
                "                \"scoreComment\": null\n" +
                "              }\n" +
                "            ],\n" +
                "            \"modelId\": 1277\n" +
                "          },\n" +
                "          {\n" +
                "            \"id\": 931,\n" +
                "            \"isDelete\": 0,\n" +
                "            \"type\": 1,\n" +
                "            \"target\": \"文化价值观\",\n" +
                "            \"keyResult\": \"发挥个人体会\",\n" +
                "            \"calculate\": \"0.3*{acquireScore}\",\n" +
                "            \"checkWeight\": 0.3,\n" +
                "            \"checkResult\": null,\n" +
                "            \"superScore\": null,\n" +
                "            \"acquireScore\": 0,\n" +
                "            \"scoreComment\": null,\n" +
                "            \"priority\": 0,\n" +
                "            \"scoreDtos\": [\n" +
                "              {\n" +
                "                \"id\": 295,\n" +
                "                \"acquireScore\": 0,\n" +
                "                \"detailId\": 931,\n" +
                "                \"approvalId\": 322,\n" +
                "                \"approvalName\": \"徐虹杰\",\n" +
                "                \"weight\": 1,\n" +
                "                \"calculate\": \"0.3*1.0*{acquireScore}\",\n" +
                "                \"scoreComment\": null\n" +
                "              }\n" +
                "            ],\n" +
                "            \"modelId\": 1277\n" +
                "          }\n" +
                "        ]\n" +
                "      }\n" +
                "    ],\n" +
                "    \"weight\": 1\n" +
                "  }*/





}
