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

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

/**
 * Created by JQ.bi on 2020.11.2
 */
@Slf4j
@RestController
@RequestMapping("/ctop/kuaishou/newPlan")
public class KsNewPlanReportCtrl {

    @Autowired
    IKsNewPlanReportService newPlanReportService;

    @Autowired
    NewMonitorService newMonitorService;

    /**
     * 新建计划、有效计划 chart数据
     */
    @PostMapping("/report/data")
    public Result<Map<String, Object>> getNewPlanChartReport(@RequestBody JSONObject requestBody) {
        Result<Map<String, Object>> resultBody = new Result<>();
        Map<String, Object> result = new HashMap<>();
        JSONArray accountIds = requestBody.getJSONArray("accountIds");
        String userId = requestBody.getString("userId");
        //f6a6843879c949618e4a859140c8a127 李超  丁总 b161b7d9793942f980dbfe8c931cd1b0
        if ("f6a6843879c949618e4a859140c8a127".equals(userId) || "b161b7d9793942f980dbfe8c931cd1b0".equals(userId)) {
            accountIds = newPlanReportService.getAccountIdsByMedia();
        } else {
            if (!userId.isEmpty()) {
                accountIds = newPlanReportService.getAccountIdsByUserId(userId);
            }
            if (accountIds.isEmpty()) {
                return resultBody;
            }
        }
        String startDate = requestBody.getString("startDate");
        String endDate = requestBody.getString("endDate");

        Integer startDateInteger = DateUtils.getDateInteger(startDate);
        Integer endDateInteger = DateUtils.getDateInteger(endDate);

        String target = requestBody.getString("target");
        try {
            /*JSONObject sumData = newPlanReportService.getSumNewPlanBy(accountIds, startDate, endDate);
            List<JSONObject> chartData = newPlanReportService.getKsNewPlanGroupByStatDate(accountIds, startDate, endDate);
            List<JSONObject> listData = newPlanReportService.getKsNewPlanGroupByAccount(accountIds, startDate, endDate, target, order);*/
            List<JSONObject> listData = newMonitorService.getPlanMessage(accountIds, startDateInteger, endDateInteger);
            List<JSONObject> chartData = newMonitorService.getPlanMessageGroup(accountIds, startDate, endDate);
            JSONObject sumData = newMonitorService.getPlanSum(accountIds, startDateInteger, endDateInteger);
            result.put("sumData", sumData);
            result.put("chartData", chartData);
            result.put("listData", listData);
            resultBody.setResult(result);
            resultBody.setSuccess(true);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            resultBody.setSuccess(false);
        }
        return resultBody;
    }

    /**
     * 查询素材报表表格数据
     */
    @PostMapping("/report/list")
    public Result<List<JSONObject>> getListReport(@RequestBody JSONObject requestBody) {
        Result<List<JSONObject>> result = new Result<>();

        JSONArray accountIds = requestBody.getJSONArray("accountIds");
        if (accountIds.isEmpty()) {
            return result;
        }
        String startDate = requestBody.getString("startDate");
        String endDate = requestBody.getString("endDate");
        String target = requestBody.getString("target");
        String order = requestBody.getString("order");
        try {
            List<JSONObject> listData = newPlanReportService.getKsNewPlanGroupByAccount(accountIds, startDate, endDate, target, order);
            result.setResult(listData);
            result.setSuccess(true);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.setSuccess(false);
        }
        return result;
    }

    @PostMapping("/report/excel")
    public void getExcelReport(@RequestBody JSONObject requestBody,
                               HttpServletRequest request,
                               HttpServletResponse response) {

        JSONArray accountIds = requestBody.getJSONArray("accountIds");
        String userId = requestBody.getString("userId");
        //f6a6843879c949618e4a859140c8a127 李超  丁总 b161b7d9793942f980dbfe8c931cd1b0
        if ("f6a6843879c949618e4a859140c8a127".equals(userId) || "b161b7d9793942f980dbfe8c931cd1b0".equals(userId)) {
            accountIds = newPlanReportService.getAccountIdsByMedia();
        } else {
            if (!userId.isEmpty()) {
                accountIds = newPlanReportService.getAccountIdsByUserId(userId);
            }
            if (accountIds.isEmpty()) {
                return;
            }
        }
        String startDate = requestBody.getString("startDate");
        String endDate = requestBody.getString("endDate");
        Integer startDateInteger = DateUtils.getDateInteger(startDate);
        Integer endDateInteger = DateUtils.getDateInteger(endDate);
        startDate = startDate + " 00:00:00";
        endDate = endDate + " 59:59:59";
        String target = requestBody.getString("target");
        String order = requestBody.getString("order");
        List<JSONObject> listData = newMonitorService.getPlanMessage(accountIds, startDateInteger, endDateInteger);

        List<List<Object>> excelList = new ArrayList<>();
        listData.forEach(data -> {
            List<Object> temp = new ArrayList<>();
            temp.add(data.getString("authName"));
            temp.add(data.getLong("accountId"));
            temp.add(data.getString("userName"));
            temp.add(data.getLong("new"));
            temp.add(data.getLong("valid"));
            temp.add(data.getString("maxCreateTime"));
            excelList.add(temp);
        });
        try {
            String[] headers = {"账户名称", "账户ID", "账户所属人", "新上计划数", "有效计划数", "最近上新时间"};
            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("/report/AllOperator")
    public Result<List<JSONObject>> getAllOperator() {
        Result<List<JSONObject>> result = new Result<>();
        try {
            List<JSONObject> listData = newPlanReportService.getAllOperator();
            result.setResult(listData);
            result.setSuccess(true);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.setSuccess(false);
        }
        return result;
    }

}
