package cn.com.ctop.kuaishou.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.kuaishou.modules.report.service.IKsVideoReportService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
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.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.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by JQ.bi on 2020.09.27
 */
@Slf4j
@RestController
@RequestMapping("/ctop/kuaishou/videoReport")
public class KsVideoReportCtrl {

    @Autowired
    IKsVideoReportService ksVideoReportService;


    @PostMapping("/getDesignList")
    public Result<List<JSONObject>> getDesignList() {
        Result<List<JSONObject>> result = new Result<>();
        try {
            List<JSONObject> designList = ksVideoReportService.getDesignList();
            result.setSuccess(true);
            result.setResult(designList);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
            result.setSuccess(false);
            result.setMessage(e.getMessage());
        }
        return result;
    }

    @PostMapping("/list")
    public Result<PageInfo<JSONObject>> getListReport(@RequestBody JSONObject requestBody) {
        Result<PageInfo<JSONObject>> result = new Result<>();
        try {
            int pageSize = requestBody.getInteger("pageSize");
            int pageNo = requestBody.getInteger("pageNo");
            String startDate = requestBody.getString("startDate");
            if (Check.isNull(startDate)) {
                throw new Exception("请输入查询开始时间");
            }
            String endDate = requestBody.getString("endDate");
            if (Check.isNull(endDate)) {
                throw new Exception("请输入查询结束时间");
            }
            String filedAll = JsonResourceUtil.joinAllFiled(AccountReportConstants.kuaishouVideoReportMap);
            if (Check.isNull(filedAll)) {
                throw new Exception("初始化查询 字段返回为空");
            }
            Map<String, Object> requestMap = new HashMap<>();
            requestMap.put("filed", filedAll);
            requestMap.put("startDate", startDate);
            requestMap.put("endDate", endDate);
            if (!Check.isNull(requestBody.getJSONArray("accountIds"))) {
                requestMap.put("accountIds", requestBody.getJSONArray("accountIds"));
            }
            if (!Check.isNull(requestBody.getString("clipId"))) {
                requestMap.put("clipId", requestBody.getString("clipId"));
            }
            if (!Check.isNull(requestBody.getString("shotId"))) {
                requestMap.put("shotId", requestBody.getString("shotId"));
            }
            if (!Check.isNull(requestBody.getString("planId"))) {
                requestMap.put("planId", requestBody.getString("planId"));
            }
            if (!Check.isNull(requestBody.getString("leaderId"))) {
                requestMap.put("leaderId", requestBody.getString("leaderId"));
            }
            if (!Check.isNull(requestBody.getString("target"))) {
                requestMap.put("target", requestBody.getString("target"));
            }
            if (!Check.isNull(requestBody.getString("order"))) {
                requestMap.put("order", requestBody.getString("order"));
            }
            if (!Check.isNull(requestBody.getInteger("channelType"))) {
                requestMap.put("channelType", requestBody.getInteger("channelType"));
            }
            PageInfo<JSONObject> listData = ksVideoReportService.getKuaiShouVideoPageReportByMap(requestMap, pageSize, pageNo);
            if (Check.isNull(listData)) {
                throw new Exception("暂无素材相关信息，请检查账户");
            }
            result.setSuccess(true);
            result.setResult(listData);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.setSuccess(false);
            result.setMessage(e.toString());
        }
        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.dicMapKs);

            try {
                if (accountIds.isEmpty()) {
                    accountIds = null;
                }
                List<JSONObject> listData = ksVideoReportService.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.dicMapKs, columns);
        List<String> titles = new ArrayList<>(JsonResourceUtil.joinTitle(AccountReportConstants.dicMapKs, columns));
        //此处增加两个元素是为了保证数据顺序
        if ("exportDetail".equals(exportType)) {
            titles.add(0, "客户");
            titles.add(1, "项目名称");
            titles.add(2, "时间");
            titles.add(3, "消耗");
            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.addAll(JsonResourceUtil.joinTitle(AccountReportConstants.dicMapKs, columns));
            columns.add(0, "signature");
            columns.add(1, "url");
            columns.add(2, "materialName");
            columns.add(3, "projectName");
            columns.add(4, "createTime");
        }

        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 target = requestBody.getString("target");
        String order = requestBody.getString("order");
        List<JSONObject> excelData = null;
        if ("exportTable".equals(exportType)) {
            excelData = ksVideoReportService.exportExcelReportBy(accountIds, startDate, endDate, filed, target, order, clip, shot, plan);
        } else if ("exportDetail".equals(exportType)) {
            excelData = ksVideoReportService.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());
        }
    }


    @PostMapping("/excelV2")
    public void excelV2(@RequestBody JSONObject requestBody,
                        HttpServletRequest request,
                        HttpServletResponse response) {
        Result<PageInfo<JSONObject>> result = new Result<>();
        try {


            if (Check.isNull(requestBody)) {
                throw new Exception("入参不能为空");
            }
            JSONArray columns = requestBody.getJSONArray("columns");
            String startDate = requestBody.getString("startDate");
            if (Check.isNull(startDate)) {
                throw new Exception("请输入查询开始时间");
            }
            String endDate = requestBody.getString("endDate");
            if (Check.isNull(endDate)) {
                throw new Exception("请输入查询结束时间");
            }
            String filedAll = JsonResourceUtil.joinAllFiled(AccountReportConstants.kuaishouVideoReportMap);
            //   System.err.println(filedAll);
            if (Check.isNull(filedAll)) {
                throw new Exception("初始化查询 字段返回为空");
            }
            Map<String, Object> requestMap = new HashMap<>();
            requestMap.put("filed", filedAll);
            requestMap.put("startDate", startDate);
            requestMap.put("endDate", endDate);
            if (!Check.isNull(requestBody.getJSONArray("accountIds"))) {
                requestMap.put("accountIds", requestBody.getJSONArray("accountIds"));
            }
            if (!Check.isNull(requestBody.getString("clipId"))) {
                requestMap.put("clipId", requestBody.getString("clipId"));
            }
            if (!Check.isNull(requestBody.getString("shotId"))) {
                requestMap.put("shotId", requestBody.getString("shotId"));
            }
            if (!Check.isNull(requestBody.getString("planId"))) {
                requestMap.put("planId", requestBody.getString("planId"));
            }
            if (!Check.isNull(requestBody.getString("leaderId"))) {
                requestMap.put("leaderId", requestBody.getString("leaderId"));
            }
            if (!Check.isNull(requestBody.getString("target"))) {
                requestMap.put("target", requestBody.getString("target"));
            }
            if (!Check.isNull(requestBody.getString("order"))) {
                requestMap.put("order", requestBody.getString("order"));
            }
            if (!Check.isNull(requestBody.getInteger("channelType"))) {
                requestMap.put("channelType", requestBody.getInteger("channelType"));
            }

            JSONArray columns2 = new JSONArray();
            columns2.add(0, "materialName");
            columns2.add(1, "signature");
            columns2.add(2, "projectName");
            columns2.add(3, "channel");
            columns2.add(4, "designLeader");
            columns2.add(5, "clip");
            columns2.add(6, "plan");
            columns2.add(7, "shot");
            columns2.add(8, "createTime");
            if (!Check.isNull(columns)) {
                for (int i = 0; i < columns.size(); i++) {
                    columns2.add(columns2.size(), columns.getString(i));
                }
            }
            columns2.add(columns2.size(), "url");
            List<String> titles = getfileIds(AccountReportConstants.kuaishouVideoReportDict, columns2);
            List<JSONObject> listData = ksVideoReportService.getKuaiShouVideoReportByMap(requestMap);
            if (Check.isNull(listData)) {
                throw new Exception("暂无素材相关信息，请检查账户");
            }
            List<List<Object>> excelList = new ArrayList<>();
            for (int i = 0; i < listData.size(); i++) {
                List<Object> temp = new ArrayList<>();
                JSONObject jsonObject = listData.get(i);
                for (int j = 0; j < columns2.size(); j++) {
                    String key = columns2.getString(j);
                    String value = jsonObject.getString(key);
                    temp.add(value);
                }
                excelList.add(temp);
            }
            try {
                String[] strings = titles.toArray(new String[]{});
                OutputStream os = response.getOutputStream();
                ExportExcelUtils eeu = new ExportExcelUtils();
                XSSFWorkbook workbook = new XSSFWorkbook();
                eeu.exportExcel(workbook, 0, "快手素材报表", strings, excelList);
                HttpUtils.setResponseHeader(response, "快手素材.xlsx");
                workbook.write(os);
                os.flush();
                os.close();
            } catch (IOException e) {
                log.error(e.getMessage());
            }
            result.setSuccess(true);

        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
            result.setSuccess(false);
            result.setMessage(e.getMessage());
        }


    }

    private List<String> getfileIds(Map<String, Map<String, Object>> kuaishouVideoReportMap, JSONArray columns) {
        List<String> titles = new ArrayList<>();
        for (int i = 0; i < columns.size(); i++) {
            String string = columns.getString(i);
            Map<String, Object> stringObjectMap = kuaishouVideoReportMap.get(string);
            if (Check.isNull(stringObjectMap)) {
                titles.add("-");
                continue;
            }
            Object comment = stringObjectMap.get("comment");
            titles.add(String.valueOf(comment));

        }
        return titles;
    }
}
