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.IKuaishouDimensionReportService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
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.List;
import java.util.Map;

@Slf4j
@Api(tags = "快手-多维度数据报表")
@RestController
@RequestMapping("/dimension/report")
public class KuaishouDimensionReportController {
    @Autowired
    private IKuaishouDimensionReportService dimensionReportService;


    /**
     * 获取分版位数据
     *
     * @param requestJson
     * @return
     */
    @PostMapping(value = "/getPositionData")
    public Result<List<JSONObject>> getPositionData(@RequestBody JSONObject requestJson) {
        Result<List<JSONObject>> result = new Result<>();
        try {
            JSONArray accountIds = requestJson.getJSONArray("accountIds");
            if (Check.isNull(accountIds)) {
                throw new Exception("请输入需要账户id");
            }
            String startDate = requestJson.getString("startDate");
            if (Check.isNull(startDate)) {
                throw new Exception("请输入开始时间");
            }
            String endDate = requestJson.getString("endDate");
            if (Check.isNull(endDate)) {
                throw new Exception("请输入结束时间");
            }
            String filedAll = JsonResourceUtil.joinAllFiled(AccountReportConstants.dicMapKs);
            if (Check.isNull(filedAll)) {
                throw new Exception("查询配置为空");
            }
            List<JSONObject> positionList = dimensionReportService.getPositionData(accountIds, startDate, endDate, filedAll);
            result.setResult(positionList);
            result.setSuccess(true);
            result.setMessage("success");
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage(e.getMessage());
            e.printStackTrace();
        }
        return result;
    }


    /**
     * 分版位数据导出
     *
     * @param requestJson
     * @param request
     * @param response
     */
    @PostMapping("/positionDataImportExcel")
    public void positionDataImportExcel(@RequestBody JSONObject requestJson,
                                        HttpServletRequest request,
                                        HttpServletResponse response) {
        Result<PageInfo<JSONObject>> result = new Result<>();
        try {

            JSONArray columns = requestJson.getJSONArray("columns");
            if (Check.isNull(columns)) {
                throw new Exception("请传入表头");
            }
            JSONArray accountIds = requestJson.getJSONArray("accountIds");
            if (Check.isNull(accountIds)) {
                throw new Exception("请输入需要账户id");
            }
            String startDate = requestJson.getString("startDate");
            if (Check.isNull(startDate)) {
                throw new Exception("请输入开始时间");
            }
            String endDate = requestJson.getString("endDate");
            if (Check.isNull(endDate)) {
                throw new Exception("请输入结束时间");
            }
            String filedAll = JsonResourceUtil.joinAllFiled(AccountReportConstants.dicMapKs);
            if (Check.isNull(filedAll)) {
                throw new Exception("查询配置为空");
            }
            JSONArray columns2 = new JSONArray();
            columns2.add(0, "adScene");

            for (int i = 0; i < columns.size(); i++) {
                columns2.add(columns2.size(), columns.getString(i));
            }
            List<String> titles = getfileIds(AccountReportConstants.kuaishouVideoReportDict, columns2);
            List<JSONObject> positionList = dimensionReportService.getPositionData(accountIds, startDate, endDate, filedAll);
            if (Check.isNull(positionList)) {
                throw new Exception("暂无投放场景相关信息，请检查账户");
            }
            List<List<Object>> excelList = new ArrayList<>();
            for (int i = 0; i < positionList.size(); i++) {
                List<Object> temp = new ArrayList<>();
                JSONObject jsonObject = positionList.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;
    }


}
