package cn.com.ctop.report.controller;

import cn.com.ctop.common.constant.AccountReportConstants;
import cn.com.ctop.common.mapper.SysRoleMapper;
import cn.com.ctop.common.utils.Check;
import cn.com.ctop.common.utils.ExportExcelUtils;
import cn.com.ctop.common.utils.HttpUtils;
import cn.com.ctop.common.utils.JsonResourceUtil;
import cn.com.ctop.report.service.ITencentMaterialVideoReportDailyDwService;
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.util.DateUtils;
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;
import java.util.Set;

@RestController
@RequestMapping("material/report")
@Slf4j
public class TencentMaterialReportDailyDwController {
    @Autowired
    private ITencentMaterialVideoReportDailyDwService tencentMaterialVideoReportDailyDwService;
    @Autowired
    private SysRoleMapper sysRoleMapper;

    @PostMapping("/tencent/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("请输入查询结束时间");
            }
            long days = DateUtils.getDiscrepantDays(startDate, endDate) + 1;
            if (days > 60) {
                throw new Exception("开始和结束时间的时间跨度，不能超过60天，请重新选择");
            }

            String filedAll = JsonResourceUtil.joinAllFiled(AccountReportConstants.getTencentVideoReportMap());
            if (Check.isNull(filedAll)) {
                throw new Exception("初始化查询 字段返回为空");
            }

            String userId = requestBody.getString("userId");
            if (Check.isNull(userId)) {
                throw new Exception("用户id不能为空");
            }
            Map<String, Object> requestMap = buildRequestMap(requestBody, filedAll, startDate, endDate, userId);
            PageInfo<JSONObject> listData =
                    tencentMaterialVideoReportDailyDwService.getTencentVideoPageReportByMap(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("/tencent/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);
            return result;
        }

        JSONArray accountIds = requestBody.getJSONArray("accountIds");
        String signature = requestBody.getString("signature");
        String materialType = requestBody.getString("materialType");
        String startDate = requestBody.getString("startDate");
        String endDate = requestBody.getString("endDate");
        if (!Check.isNull(startDate)) {
            startDate = startDate.replace("-", "");
        }
        if (!Check.isNull(endDate)) {
            endDate = endDate.replace("-", "");
        }
        String filedAll = JsonResourceUtil.joinAllFiled(AccountReportConstants.getTencentVideoReportMap());
        try {
            if (accountIds != null && accountIds.isEmpty()) {
                accountIds = null;
            }
            List<JSONObject> listData = tencentMaterialVideoReportDailyDwService.getVideoDetailBy(
                    accountIds, startDate, endDate, filedAll, signature, materialType);
            result.setResult(listData);
            result.setSuccess(true);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.setSuccess(false);
        }
        return result;
    }

    @PostMapping("/tencent/excelV2")
    public void excelV2(@RequestBody JSONObject requestBody,
                        HttpServletRequest request,
                        HttpServletResponse response) {
        try {
            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.getTencentVideoReportMap());
            if (Check.isNull(filedAll)) {
                throw new Exception("初始化查询 字段返回为空");
            }

            String userId = requestBody.getString("userId");
            if (Check.isNull(userId)) {
                throw new Exception("用户id不能为空");
            }
            Map<String, Object> requestMap = buildRequestMap(requestBody, filedAll, startDate, endDate, userId);

            JSONArray columns = requestBody.getJSONArray("columns");
            List<String> columns2 = new ArrayList<>();
            columns2.add("materialTypeName");
            columns2.add("materialName");
            columns2.add("signature");
            columns2.add("projectName");
            columns2.add("designLeader");
            columns2.add("clip");
            columns2.add("plan");
            columns2.add("shot");
            columns2.add("channel");
            columns2.add("createTime");
            if (!Check.isNull(columns)) {
                for (int i = 0; i < columns.size(); i++) {
                    columns2.add(columns.getString(i));
                }
            }
            columns2.add("url");
            List<String> titles = getFieldTitles(AccountReportConstants.getKuaishouVideoReportDict(), columns2);

            List<JSONObject> listData = tencentMaterialVideoReportDailyDwService.getTencentVideoPageReportByMap(requestMap);
            if (Check.isNull(listData)) {
                throw new Exception("暂无素材相关信息，请检查账户");
            }
            List<List<Object>> excelList = new ArrayList<>();
            for (JSONObject jsonObject : listData) {
                List<Object> temp = new ArrayList<>();
                for (String key : columns2) {
                    temp.add(jsonObject.getString(key));
                }
                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());
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    private Map<String, Object> buildRequestMap(JSONObject requestBody,
                                                String filedAll,
                                                String startDate,
                                                String endDate,
                                                String userId) {
        Map<String, Object> requestMap = new HashMap<>();
        requestMap.put("filed", filedAll);
        requestMap.put("startDate", Long.parseLong(startDate.replace("-", "")));
        requestMap.put("endDate", Long.parseLong(endDate.replace("-", "")));

        if (!Check.isNull(requestBody.getJSONArray("accountIds"))) {
            requestMap.put("accountIds", requestBody.getJSONArray("accountIds"));
        }
        requestMap.put("target", getSortTarget(requestBody.getString("target")));
        requestMap.put("order", getSortOrder(requestBody.getString("order")));
        if (!Check.isNull(requestBody.getInteger("channelType"))) {
            requestMap.put("channelType", requestBody.getInteger("channelType"));
        }
        if (!Check.isNull(requestBody.getString("materialType"))) {
            requestMap.put("materialType", requestBody.getString("materialType"));
        }

        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"));
        }
        return requestMap;
    }

    private String getSortTarget(String target) {
        Set<String> fieldNames = AccountReportConstants.getTencentVideoReportMap().keySet();
        if (!Check.isNull(target) && fieldNames.contains(target)) {
            return target;
        }
        return "cost";
    }

    private String getSortOrder(String order) {
        if ("asc".equalsIgnoreCase(order)) {
            return "asc";
        }
        return "desc";
    }

    private List<String> getFieldTitles(Map<String, Map<String, Object>> fieldMap, List<String> columns) {
        List<String> titles = new ArrayList<>();
        for (String column : columns) {
            if ("materialTypeName".equals(column)) {
                titles.add("素材类型");
                continue;
            }
            Map<String, Object> value = fieldMap.get(column);
            if (Check.isNull(value)) {
                titles.add("-");
                continue;
            }
            titles.add(String.valueOf(value.get("comment")));
        }
        return titles;
    }
}
