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

import cn.com.ctop.common.module.utils.ExportExcelUtils;
import cn.com.ctop.common.module.utils.HttpUtils;
import cn.com.ctop.toutiao.modules.report.service.IBytedanceAccountReportService;
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.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.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by JQ.bi on 2020.6.5
 */
@Slf4j
@RestController
@RequestMapping("/ctop/byteDance/dailyPage")
public class BytedanceAccountReportCtrl {

    @Autowired
    IBytedanceAccountReportService bytedanceAccountReportService;

    /**
     * 查询素材报表chart数据
     *
     * @param requestBody
     * @return
     */
    @PostMapping("/report/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 mediaId = requestBody.getString("mediaId");
        BigDecimal discount = requestBody.getBigDecimal("discount");
        JSONArray accounts = requestBody.getJSONArray("accountIds");
        if (accounts.isEmpty()) {
            return resultBody;
        }
        String startDate = requestBody.getString("startDate");
        String endDate = requestBody.getString("endDate");
        try {
            Map<String, Object> sumData = bytedanceAccountReportService.getSumDataBy(mediaId, discount, accounts, startDate, endDate);
            List<JSONObject> chartData = bytedanceAccountReportService.getChartDataBy(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;
    }

    /**
     * 查询素材报表表格数据
     *
     * @param requestBody
     * @return
     */
    @PostMapping("/report/list")
    public Result<List<JSONObject>> getListReport(@RequestBody JSONObject requestBody) {
        Result<List<JSONObject>> result = new Result<>();
        if (requestBody.isEmpty()) {
            log.error("request body is empty");
            result.setSuccess(false);
        }
        String mediaId = requestBody.getString("mediaId");
        BigDecimal discount = requestBody.getBigDecimal("discount");
        JSONArray accounts = requestBody.getJSONArray("accountIds");
        if (accounts.isEmpty()) {
            return result;
        }
        String startDate = requestBody.getString("startDate");
        String endDate = requestBody.getString("endDate");
        int hour = requestBody.getInteger("hour");
        String target = requestBody.getString("target");
        String order = requestBody.getString("order");
        try {
            List<JSONObject> listData = bytedanceAccountReportService.getListDataBy(mediaId, 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;
    }

    /**
     * 导出数据
     *
     * @param requestBody
     * @param request
     * @param response
     */
    @PostMapping("/report/excel")
    public void getExcelReport(@RequestBody JSONObject requestBody,
                               HttpServletRequest request,
                               HttpServletResponse response) {
        JSONArray columns = requestBody.getJSONArray("columns");
        if (columns.isEmpty()) {
            log.error("请选择需要导出的字段");
        }
        String filed = JsonResourceUtil.joinFiled(AccountReportConstants.dicMapBy, columns);
        List<String> titles = new ArrayList<>();
        titles.add("账户Id");
        titles.add("账户名称");
        titles.addAll(JsonResourceUtil.joinTitle(AccountReportConstants.dicMapBy, columns));
        //此处增加两个元素是为了保证数据有序
        columns.add(0, "accountId");
        columns.add(1, "authName");
        String mediaId = requestBody.getString("mediaId");
        JSONArray accounts = requestBody.getJSONArray("accountIds");
        if (accounts.isEmpty()) {
            return;
        }
        String startDate = requestBody.getString("startDate");
        String endDate = requestBody.getString("endDate");
        String target = requestBody.getString("target");
        String order = requestBody.getString("order");
        int hour = requestBody.getInteger("hour");
        List<JSONObject> excelData = bytedanceAccountReportService.getExcelDataBy(filed, mediaId, accounts, startDate, endDate, hour, target, order);
        if (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());
        }
    }

}
