package cn.com.ctop.toutiao.modules.material.controller;

import cn.com.ctop.common.module.service.ISendMessageService;
import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.common.module.utils.ExportExcelUtils;
import cn.com.ctop.common.module.utils.HttpUtils;
import cn.com.ctop.shiwan.modules.FileUtil;
import cn.com.ctop.toutiao.modules.material.service.FirstDeliveryValidService;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * 首投有效数据导入
 */
@Slf4j
@RestController
@RequestMapping("/first/delivery")
public class FirstDeliveryValidController {
    @Resource
    private FirstDeliveryValidService firstDeliveryValidService;

    @Value("${zip.local.download-path}")
    private String downloadPath;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private ISendMessageService sendMessageService;

    /**
     * 导入EXCEL批量创建
     * ruixuan 服务
     * 返点-首投有效素材明细
     */
    @PostMapping(value = "/importExcelMaterials")
    @ResponseBody
    public Result<Object> importExcelMaterials(HttpServletResponse response, @RequestParam("file") MultipartFile file) throws Exception {
        String nowDate = DateUtils.date2Str();
        String key = nowDate + "_importExcelMaterials";
        Object creative = redisUtil.get(key);
        if (Check.isNull(creative)) {
            redisUtil.set(key, "NO");
            Thread thread = new Thread() {
                @Override
                public void run() {
                    try {
                        StringBuffer path = new StringBuffer();
                        path.append(downloadPath).append("excel").append("/").append(DateUtils.formatDate()).append("/");
                        String newFileUrl = FileUtil.approvalFile(file, path.toString());
                        //宇鹏本地服务
//                        HttpUtils.fileUpload("http://192.168.1.149:8765/webhook/get_file", newFileUrl, null);
                        //宇鹏外网服务
                        HttpUtils.fileUpload("http://114.242.47.94:9998/webhook/get_file", newFileUrl, null);
                    } catch (Exception e) {
                        e.printStackTrace();
                        redisUtil.removeAll(key);
                    }
                }
            };
            thread.start();
        } else {
            return Result.error("文件上传中...");
        }
        return Result.successMsg("ok", null);
    }


    @GetMapping(value = "/excelCallBack")
    public void excelCallBack(String msg) {
        String nowDate = DateUtils.date2Str();
        String key = nowDate + "_importExcelMaterials";
        redisUtil.removeAll(key);
        List<String> userIds = new ArrayList<>();
        //秦可心  于蒙
        userIds.add("c6dcc96ef9ed413aa224f10ec652fb88");
        userIds.add("113dee46c7df464da78c07a985e92cd1");
        StringBuilder text = new StringBuilder();
        if ("error".equals(msg)) {
//            赵西安
            userIds.add("1b3deb8258e84df994f1371a51cfc14a");
            text.append("上传首投有效素材失败通知:").append("<br/>")
                    .append("您好，您上传的EXCEL文件录入失败").append("<br/>")
                    .append("请联系管理员！").append("<br/>")
                    .append("上传页面：统计报表->头条-有效素材->导入明细");
            for (String userId : userIds) {
                sendMessageService.sendMessage(userId, text.toString());
            }
        } else {
            text.append("上传首投有效素材成功通知:").append("<br/>")
                    .append("您好，您上传的EXCEL文件已录入成功");
            for (String userId : userIds) {
                sendMessageService.sendMessage(userId, text.toString());
            }
        }
    }
    /**
     * 导入EXCEL批量创建
     * 返点-首投有效素材明细
     */
   /* @PostMapping(value = "/importExcelMaterials")
    @ResponseBody
    public Result<Object> importExcelMaterials(HttpServletResponse response, @RequestParam("file") MultipartFile file) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        try {
            if (Check.isNull(file)) {
                return Result.error("执行失败，请上传应用Excel文件");
            }
            return firstDeliveryValidService.importExcelMaterials(file);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("导入EXCEL失败，" + e.getMessage());
        }
    }*/


    /**
     * 导入EXCEL批量创建
     * 返点-首投有效占比结果表
     */
    @PostMapping(value = "/importExcelRatio")
    @ResponseBody
    public Result<Object> importExcelRatio(HttpServletResponse response, @RequestParam("file") MultipartFile file) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        try {
            if (Check.isNull(file)) {
                return Result.error("执行失败，请上传应用Excel文件");
            }
            return firstDeliveryValidService.importExcelRatio(file);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("导入EXCEL失败，" + e.getMessage());
        }
    }

    @GetMapping(value = "/projectData")
    @ResponseBody
    public Result<Object> projectData(String date, Integer pageSize, Integer pageNo) {
        try {
            return firstDeliveryValidService.projectData(date, pageSize, pageNo);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("导入EXCEL失败，" + e.getMessage());
        }
    }


    @GetMapping(value = "/getDesignData")
    @ResponseBody
    public Result<Object> getDesignData(String date, Integer pageSize, Integer pageNo, Integer designRole) {
        try {
            return firstDeliveryValidService.getDesignData(date, pageSize, pageNo, designRole);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("导入EXCEL失败，" + e.getMessage());
        }
    }


    @GetMapping(value = "/getTotalData")
    @ResponseBody
    public Result<Object> getTotalData(String date, Integer pageSize, Integer pageNo) {
        try {
            return firstDeliveryValidService.getTotalData(date, pageSize, pageNo);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("导入EXCEL失败，" + e.getMessage());
        }
    }


    /**
     * 导出数据
     */
    @GetMapping("/excel")
    public void getExcelReport(HttpServletResponse response, String date) {
        if (Check.isNull(date)) {
            log.error("缺失参数!");
            return;
        }
        String[] split = date.split("-");
        String year = split[0];
        String monthStr = split[1];
        String month = "";
        if ("10".equals(month)) {
            month = "10";
        } else {
            month = monthStr.replace("0", "");
        }
        List<JSONObject> projectInfo = firstDeliveryValidService.getDataForProject(year, month);
        //剪辑
        List<JSONObject> clipInfo = firstDeliveryValidService.getDesignDataExport(date, 1);
        // 拍摄
        List<JSONObject> shotInfo = firstDeliveryValidService.getDesignDataExport(date, 2);
        // 编导
        List<JSONObject> planInfo = firstDeliveryValidService.getDesignDataExport(date, 3);

        try {
            List<List<Object>> projectExcelList = new ArrayList<>();
            List<List<Object>> clipExcelList = new ArrayList<>();
            List<List<Object>> shotExcelList = new ArrayList<>();
            List<List<Object>> planExcelList = new ArrayList<>();
            if (!projectInfo.isEmpty()) {
                projectInfo.forEach(data -> {
                    List<Object> temp = new ArrayList<>();
                    temp.add(data.getString("projectName"));
                    temp.add(data.getString("projectLeaderName"));
                    temp.add(data.getString("dessLeaderName"));
                    temp.add(data.getString("rebateType"));
                    temp.add(data.getString("settlement1l"));
                    temp.add(data.getString("settlement2l"));
                    temp.add(data.getString("materialNum"));
                    temp.add(data.getString("effCount"));
                    if (!Check.isNull(data.getInteger("color"))) {
                        if (data.getInteger("color") == 2) {
                            temp.add(data.getString("effRate") + "-GREEN");
                        } else {
                            temp.add(data.getString("effRate") + "-G");
                        }
                    } else {
                        temp.add("-");
                    }
                    temp.add(data.getString("mediaEffRate"));
                    temp.add(data.getString("selfEffCount"));
                    temp.add(data.getString("selfEffRate"));
                    temp.add(data.getString("thirdEffCount"));
                    projectExcelList.add(temp);
                });
            }
            getExcelInfo(clipInfo, clipExcelList);
            getExcelInfo(shotInfo, shotExcelList);
            getExcelInfo(planInfo, planExcelList);
            OutputStream os = response.getOutputStream();
            ExportExcelUtils eeu = new ExportExcelUtils();
            XSSFWorkbook workbook = new XSSFWorkbook();
            String[] titles = {"项目", "运营负责人", "设计负责人", "政策类型", "一级行业", "二级行业", "素材量",
                    "有效首投数", "有效首投率", "媒体考核有效率", "自产素材有效数", "自产素材有效占比", "三方素材有效数"};
            String[] overtimeTitles = {"项目名称", "项目设计负责人", "项目运营负责人", "设计leader", "设计", "政策类型", "一级行业", "二级行业", "首投素材量",
                    "有效首投素材量", "有效率", "媒体考核有效率"};
            eeu.exportExcelForFirstDelivery(workbook, 0, "分项目", titles, projectExcelList);
            eeu.exportExcelForFirstDelivery(workbook, 1, "分剪辑", overtimeTitles, clipExcelList);
            eeu.exportExcelForFirstDelivery(workbook, 2, "分拍摄", overtimeTitles, shotExcelList);
            eeu.exportExcelForFirstDelivery(workbook, 3, "分编导", overtimeTitles, planExcelList);
            HttpUtils.setResponseHeader(response, "data.xlsx");
            workbook.write(os);
            os.flush();
            os.close();
        } catch (IOException e) {
            log.error(e.getMessage());
        }
    }

    private void getExcelInfo(List<JSONObject> info, List<List<Object>> excelList) {
        if (!info.isEmpty()) {
            info.forEach(data -> {
                List<Object> temp = new ArrayList<>();
                temp.add(data.getString("projectName"));
                temp.add(data.getString("projectDesignLeaderName"));
                temp.add(data.getString("projectLeaderName"));
                temp.add(data.getString("leaderName"));
                temp.add(data.getString("designName"));
                temp.add(data.getString("rebateType"));
                temp.add(data.getString("settlement1l"));
                temp.add(data.getString("settlement2l"));
                temp.add(data.getString("materialNum"));
                temp.add(data.getString("effMaterialNum"));
                if (!Check.isNull(data.getBigDecimal("effRate"))) {
                    String str = "";
                    str = data.getString("effRate") + "%";
                    if (data.getBigDecimal("effRate").compareTo(data.getBigDecimal("mediaEffRate")) < 0) {
                        temp.add(str + "-GREEN");
                    } else {
                        temp.add(str + "-G");
                    }
                } else {
                    temp.add("-" + "-G");
                }

                if (!Check.isNull(data.getString("mediaEffRate"))) {
                    temp.add(data.getString("mediaEffRate") + "%");
                } else {
                    temp.add("-");
                }
                temp.add(data.getString("materialValidRatio"));
                excelList.add(temp);
            });
        }
    }

}
