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.IKsNewGroupReportService;
import cn.com.ctop.kuaishou.modules.report.service.IKsNewPlanReportService;
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.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.6
 */
@Slf4j
@RestController
@RequestMapping("/ctop/kuaishou/newGroup")
public class KsNewGroupReportCtrl {

    @Autowired
    IKsNewGroupReportService newGroupReportService;

    @Autowired
    IKsNewPlanReportService newPlanReportService;

    /**
     * 新建计划、有效计划 chart数据
     */
    @PostMapping("/report/data")
    public Result<Map<String, Object>> getNewGroupChartReport(@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");
        //TODO 没有维护快手事业部负责人角色，增加判断
        if (userId.equals("b73c6a1cafb4469a8c0081acd50f703b") || userId.equals("228c45f913924639bf20c79ce5dadb16")) {
            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");
        String target = requestBody.getString("target");
        String order = requestBody.getString("order");
        try {
            JSONObject sumData = newGroupReportService.getSumNewGroupBy(accountIds, startDate, endDate);
            List<JSONObject> chartData = newGroupReportService.getKsNewGroupGroupByStatDate(accountIds, startDate, endDate);
            List<JSONObject> listData = newGroupReportService.getKsNewGroupGroupByAccount(accountIds, startDate, endDate, target, order);
            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 = newGroupReportService.getKsNewGroupGroupByAccount(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");
        //TODO 没有维护快手事业部负责人角色，增加判断
        if (userId.equals("6b4c821adc414dc8b7718ab63ccbfcaf")) {
            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");
        String target = requestBody.getString("target");
        String order = requestBody.getString("order");
        List<JSONObject> listData = newGroupReportService.getKsNewGroupGroupByAccount(accountIds, startDate, endDate, target, order);

        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;
    }

}
