package cn.com.ctop.report.controller;

import cn.com.ctop.common.constant.AccountReportConstants;
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.report.entity.AccountAttributionInfo;
import cn.com.ctop.report.service.AccountAttributionInfoService;
import cn.com.ctop.report.service.IBytedanceAccountReportDailyDwService;
import com.alibaba.fastjson.JSONArray;
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.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.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("account/bytedance/report")
@Slf4j
public class BytedanceAccountReportDailyDwController {
    @Autowired
    IBytedanceAccountReportDailyDwService accountReportDailyDwService;
    @Autowired
    private AccountAttributionInfoService accountAttributionInfoService;

    /**
     * 查询账户报表数据
     */
    @PostMapping("/bytedance/list")
    public Result<List<JSONObject>> getListReport(@RequestBody JSONObject requestBody) throws ParseException {
        Result<List<JSONObject>> result = new Result<>();
        if (requestBody.isEmpty()) {
            log.error("request body is empty");
            result.setSuccess(false);
        }
        BigDecimal discount = requestBody.getBigDecimal("disscount");
        JSONArray accounts = requestBody.getJSONArray("accountIds");
        String userId = requestBody.getString("userId");
        if (accounts.isEmpty()) {
            List<AccountAttributionInfo> accountAttributionInfos = accountAttributionInfoService.getAccountInfoList(userId, "bytedance");
            accounts = new JSONArray();
            for (AccountAttributionInfo account : accountAttributionInfos) {
                accounts.add(account.getAccountId());
            }
        }
        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;
        }

        Integer hour = requestBody.getInteger("hour");
        if (null == hour) {
            hour = DateUtils.getNowHour();
        }
        String target = requestBody.getString("target");
        String order = requestBody.getString("order");
        try {
            List<JSONObject> listData = accountReportDailyDwService.getListDataByParams("1", discount, accounts, startDate, endDate, hour, target, order);
            result.setResult(listData);
            result.setSuccess(true);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.setSuccess(false);
        }
        return result;
    }

    /**
     * 查询素材报表chart数据
     */
    @PostMapping("/bytedance/chart")
    public Result<Map<String, Object>> getAccountChartReport(@RequestBody JSONObject requestBody) {
        Result<Map<String, Object>> resultBody = new Result<>();
        Map<String, Object> result = new HashMap<>();
        if (requestBody.isEmpty()) {
            log.error("request body is empty");
            resultBody.setSuccess(false);
        }
        String startDate = requestBody.getString("startDate");
        String endDate = requestBody.getString("endDate");
        //开始和结束时间的时间跨度，不能超过60天
        long days = DateUtils.getDiscrepantDays(startDate, endDate) + 1;
        if (days > 60) {
            resultBody.setSuccess(false);
            resultBody.setMessage("开始和结束时间的时间跨度，不能超过60天，请重新选择");
            return resultBody;
        }
        String mediaId = requestBody.getString("mediaId");
        BigDecimal discount = requestBody.getBigDecimal("disscount");
        JSONArray accounts = requestBody.getJSONArray("accountIds");
        if (accounts.isEmpty()) {
            return resultBody;
        }
        try {
            Map<String, Object> sumData = accountAttributionInfoService.getBytedanceSumDataBy(mediaId, discount, accounts, startDate, endDate);
            List<JSONObject> chartData = accountAttributionInfoService.getBytedanceChartDataBy(mediaId, discount, accounts, startDate, endDate);
            result.put("sumData", sumData);
            result.put("chartData", chartData);
            resultBody.setResult(result);
            resultBody.setSuccess(true);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            resultBody.setSuccess(false);
        }
        return resultBody;
    }


    @PostMapping("/bytedance/excelV2")
    public void excelV2(@RequestBody JSONObject requestBody, HttpServletRequest request, HttpServletResponse response) {
        Result<List<JSONObject>> result = new Result<>();
        try {
            if (requestBody.isEmpty()) {
                log.error("request body is empty");
                result.setSuccess(false);
            }
            BigDecimal discount = requestBody.getBigDecimal("disscount");
            JSONArray accounts = requestBody.getJSONArray("accountIds");
            String userId = requestBody.getString("userId");
            if (accounts.isEmpty()) {
                List<AccountAttributionInfo> accountAttributionInfos = accountAttributionInfoService.getAccountInfoList(userId, "bytedance");
                accounts = new JSONArray();
                for (AccountAttributionInfo account : accountAttributionInfos) {
                    accounts.add(account.getAccountId());
                }
            }
            String startDate = requestBody.getString("startDate");
            String endDate = requestBody.getString("endDate");
            Integer hour = requestBody.getInteger("hour");
            if (null == hour) {
                hour = DateUtils.getNowHour();
            }
            String target = requestBody.getString("target");
            String order = requestBody.getString("order");
            List<JSONObject> listData = accountReportDailyDwService.getListDataByParams("1", discount, accounts, startDate, endDate, hour, target, order);

            JSONArray columns = requestBody.getJSONArray("columns");
            List<String> columns2 = new ArrayList();
            columns2.add("statDate");
            columns2.add("accountId");
            columns2.add("authName");

            if (!Check.isNull(columns)) {
                for (int i = 0; i < columns.size(); i++) {
                    columns2.add(columns.getString(i));
                }
            }
            List<String> titles = getfileIds(AccountReportConstants.getBytedanceVideoFiled(), columns2);


            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 = (String) columns2.get(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, List columns) {

        List<String> titles = new ArrayList<>();
        for (int i = 0; i < columns.size(); i++) {
            String string = (String) columns.get(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;
    }


}
