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

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.toutiao.modules.report.service.IBytedanceVideoReportService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.AccountReportConstants;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.utils.JsonResourceUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.naming.ldap.HasControls;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by JQ.bi on 2020.09.21
 */
@Slf4j
@RestController
@RequestMapping("/ctop/byteDance/videoReport")
public class BytedanceVideoReportCtrl {

    @Autowired
    IBytedanceVideoReportService bytedanceVideoReportService;


    @PostMapping("/getBytedanceSevenDayCost")
    public Result<PageInfo<JSONObject>> getBytedanceSevenDayCost(@RequestBody JSONObject requestBody) {
        Result<PageInfo<JSONObject>> result = new Result<>();
        if (requestBody.isEmpty()) {
            log.error("request body is empty");
            result.setSuccess(false);
        } else {
            Long projectId = requestBody.getLong("projectId");
            Long startDate = Long.valueOf(requestBody.getString("startDate").replace("-", ""));
            Long endDate = Long.valueOf(requestBody.getString("endDate").replace("-", ""));
            Map<String, Long> requestMap = new HashMap<>();
            if (!Check.isNull(projectId)) {
                requestMap.put("projectId", projectId);
            }
            if (!Check.isNull(startDate)) {
                requestMap.put("startDate", startDate);
            }
            if (!Check.isNull(endDate)) {
                requestMap.put("endDate", endDate);
            }
            Integer pageSize = requestBody.getInteger("pageSize");
            Integer pageNo = requestBody.getInteger("pageNo");
            try {
                PageInfo<JSONObject> listData = bytedanceVideoReportService.getBytedanceSevenDayCost(requestMap, pageSize, pageNo);
                result.setResult(listData);
                result.setSuccess(true);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                result.setSuccess(false);
            }
        }
        return result;
    }

    @PostMapping("/exportBytedanceSevenDayCost")
    public void exportBytedanceSevenDayCost(HttpServletRequest request, HttpServletResponse response, @RequestBody JSONObject requestBody) {

        if (requestBody.isEmpty()) {
            log.error("request body is empty");

        } else {
            Long projectId = requestBody.getLong("projectId");
            Long startDate = Long.valueOf(requestBody.getString("startDate").replace("-", ""));
            Long endDate = Long.valueOf(requestBody.getString("endDate").replace("-", ""));
            Map<String, Long> requestMap = new HashMap<>();
            if (!Check.isNull(projectId)) {
                requestMap.put("projectId", projectId);
            }
            if (!Check.isNull(startDate)) {
                requestMap.put("startDate", startDate);
            }
            if (!Check.isNull(endDate)) {
                requestMap.put("endDate", endDate);
            }

            try {
                List<JSONObject> listData = bytedanceVideoReportService.getBytedanceSevenDayCostNoPage(requestMap);
                List<List<Object>> exportList = new ArrayList<>();
                if (!Check.isNull(listData)) {
                    for (int i = 0; i < listData.size(); i++) {
                        JSONObject date = listData.get(i);
                        List<Object> export = new ArrayList();
                        export.add(date.getString("project_name"));
                        export.add(date.getString("material_id"));
                        export.add(date.getString("material_name"));
                        export.add(date.getString("first_cost_time"));
                        export.add(date.getString("diff_day"));
                        export.add(date.getString("seven_day_cost"));
                        export.add(date.getString("leader_name"));
                        export.add(date.getString("clip_name"));
                        export.add(date.getString("shot_name"));
                        export.add(date.getString("plan_name"));
                        exportList.add(export);
                    }
                }
                String[] headers = {"项目名称", "素材ID", "素材名称", "首次消耗日期", "消耗天数", "消耗", "负责人", "剪辑", "拍摄", "编导"};
                OutputStream os = response.getOutputStream();
                ExportExcelUtils eeu = new ExportExcelUtils();
                XSSFWorkbook workbook = new XSSFWorkbook();
                eeu.exportExcel(workbook, 0, "首消视频", headers, exportList);
                this.setResponseHeader(response, "首消视频.xls");
                workbook.write(os);
                os.flush();
                os.close();
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }
    }


    @PostMapping("/list")
    public Result<PageInfo<JSONObject>> getListReport(@RequestBody JSONObject requestBody) {
        Result<PageInfo<JSONObject>> result = new Result<>();
        if (requestBody.isEmpty()) {
            log.error("request body is empty");
            result.setSuccess(false);
        } else {
            String startDate = requestBody.getString("startDate");
            String endDate = requestBody.getString("endDate");
            //开始和结束时间的时间跨度，不能超过60天
            long days = DateUtils.getDiscrepantDays(startDate, endDate) + 1;
            if (days > 60) {
                result.setSuccess(false);
                result.setMessage("开始和结束时间的时间跨度，不能超过60天，请重新选择");
                return result;
            }

            JSONArray accountIds = requestBody.getJSONArray("accountIds");
            String clip = requestBody.getString("clip");
            String shot = requestBody.getString("shot");
            String plan = requestBody.getString("plan");
            String leader = requestBody.getString("leader");
            String target = requestBody.getString("target");
            String order = requestBody.getString("order");
            int pageSize = requestBody.getInteger("pageSize");
            int pageNo = requestBody.getInteger("pageNo");
            String filedAll = JsonResourceUtil.joinAllFiled(AccountReportConstants.getDicMapByVideo2());

            if (!Check.isNull(target) && "material_show".equals(target)) {
                target = "`show`";
            } else if ("convert_material".equals(target)) {
                target = "`convert`";
            } else if ("play50_feed_break".equals(target)) {
                target = "play_50_feed_break";
            } else if ("play100_feed_break".equals(target)) {
                target = "play_100_feed_break";
            } else if ("play25_feed_break".equals(target)) {
                target = "play_25_feed_break";
            } else if ("play75_feed_break".equals(target)) {
                target = "play_75_feed_break";
            } else if ("share_material".equals(target)) {
                target = "share";
            }

            try {
                if (accountIds.isEmpty()) {
                    accountIds = null;
                }
                PageInfo<JSONObject> listData = bytedanceVideoReportService.getVideoReportBy(accountIds, startDate, endDate, filedAll, target, order, clip, shot, plan, leader, pageSize, pageNo);
                result.setResult(listData);
                result.setSuccess(true);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                result.setSuccess(false);
            }
        }
        return result;
    }

    @PostMapping("/detail")
    public Result<List<JSONObject>> getReportDetail(@RequestBody JSONObject requestBody) {
        Result<List<JSONObject>> result = new Result<>();
        if (requestBody.isEmpty()) {
            log.error("request body is empty");
            result.setSuccess(false);
        } else {
            JSONArray accountIds = requestBody.getJSONArray("accountIds");
            String signature = requestBody.getString("signature");
            String startDate = requestBody.getString("startDate");
            String endDate = requestBody.getString("endDate");

            String filedAll = JsonResourceUtil.joinAllFiled(AccountReportConstants.getDicMapByVideo2());

            try {
                if (accountIds.isEmpty()) {
                    accountIds = null;
                }
                List<JSONObject> listData = bytedanceVideoReportService.getVideoDetailBy(accountIds, startDate, endDate, filedAll, signature);
                result.setResult(listData);
                result.setSuccess(true);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                result.setSuccess(false);
            }
        }
        return result;
    }

    @PostMapping("/excel")
    public void getExcelReport(@RequestBody JSONObject requestBody,
                               HttpServletRequest request,
                               HttpServletResponse response) {
        //加一个参数区分是table页，还是详情页。
        String exportType = requestBody.getString("exportType");
        if (exportType.isEmpty()) {
            return;
        }
        JSONArray columns = requestBody.getJSONArray("columns");
        if (columns.isEmpty()) {
            //默认消耗必查
            columns.add("cost");
        }
        String filed = JsonResourceUtil.joinFiled(AccountReportConstants.getDicMapByVideo2(), columns);

        List<String> titles = new ArrayList<>(JsonResourceUtil.joinTitle(AccountReportConstants.getDicMapByVideo2(), columns));
        //此处增加两个元素是为了保证数据顺序
        if ("exportDetail".equals(exportType)) {
            titles.add(0, "客户");
            titles.add(1, "项目名称");
            titles.add(2, "时间");
            columns.add(0, "advertiserName");
            columns.add(1, "projectName");
            columns.add(2, "statDate");
        } else {
            titles.add(0, "唯一标识");
            titles.add(1, "视频");
            titles.add(2, "视频名称");
            titles.add(3, "项目名称");
            titles.add(4, "上传时间");
            titles.add(5, "剪辑");
            titles.add(6, "拍摄");
            titles.add(7, "编导");
            titles.add(8, "负责人");
            titles.add(9, "首购率");
            columns.add(0, "signature");
            columns.add(1, "url");
            columns.add(2, "materialName");
            columns.add(3, "projectName");
            columns.add(4, "createTime");
            columns.add(5, "clip");
            columns.add(6, "shot");
            columns.add(7, "plan");
            columns.add(8, "teamLeader");
            columns.add(9, "firstPurchase");
        }
        JSONArray accountIds = requestBody.getJSONArray("accountIds");
        if (accountIds.isEmpty()) {
            accountIds = null;
        }
        String startDate = requestBody.getString("startDate");
        String endDate = requestBody.getString("endDate");
        String signature = requestBody.getString("signature");
        String clip = requestBody.getString("clip");
        String shot = requestBody.getString("shot");
        String plan = requestBody.getString("plan");
        String leader = requestBody.getString("leader");
        String target = requestBody.getString("target");
        String order = requestBody.getString("order");
        List<JSONObject> excelData = null;
        if ("exportTable".equals(exportType)) {
            excelData = bytedanceVideoReportService.exportExcelReportBy(accountIds, startDate, endDate, filed, target, order, clip, shot, plan, leader);
        } else if ("exportDetail".equals(exportType)) {
            excelData = bytedanceVideoReportService.getVideoDetailBy(accountIds, startDate, endDate, filed, signature);
        }
        if (null != excelData && excelData.isEmpty()) {
            return;
        }
        List<List<Object>> excelList = new ArrayList<>();
        excelData.forEach(data -> {
            List<Object> temp = new ArrayList<>();
            columns.forEach(k -> {
                temp.add(data.get(k.toString()));
            });
            excelList.add(temp);
        });
        try {
            String[] headers = titles.toArray(new String[titles.size()]);
            OutputStream os = response.getOutputStream();
            ExportExcelUtils eeu = new ExportExcelUtils();
            XSSFWorkbook workbook = new XSSFWorkbook();
            eeu.exportExcel(workbook, 0, "头条视频报表", headers, excelList);
            HttpUtils.setResponseHeader(response, "头条视频报表.xlsx");
            workbook.write(os);
            os.flush();
            os.close();
        } catch (IOException e) {
            log.error(e.getMessage());
        }
    }

    //发送响应流方法
    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(), "ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
