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.IBytedanceVideoReportService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
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;

/**
 * Created by JQ.bi on 2020.09.21
 */
@Slf4j
@RestController
@RequestMapping("/ctop/byteDance/videoReport")
public class BytedanceVideoReportCtrl {

    @Autowired
    IBytedanceVideoReportService bytedanceVideoReportService;

    @PostMapping("/list")
    public Result<PageInfo<JSONObject>> getListReport(@RequestBody JSONObject requestBody) {
        Result<PageInfo<JSONObject>> result = new Result<>();
        if (requestBody.isEmpty()) {
            log.error("request body is empty");
            result.setSuccess(false);
        } else {
            JSONArray accountIds = requestBody.getJSONArray("accountIds");
            String startDate = requestBody.getString("startDate");
            String endDate = requestBody.getString("endDate");
            String clip = requestBody.getString("clip");
            String shot = requestBody.getString("shot");
            String plan = requestBody.getString("plan");
            String target = requestBody.getString("target");
            String order = requestBody.getString("order");
            int pageSize = requestBody.getInteger("pageSize");
            int pageNo = requestBody.getInteger("pageNo");
            String filedAll = JsonResourceUtil.joinAllFiled(AccountReportConstants.dicMapByVideo);
            try {
                if (accountIds.isEmpty()) {
                    accountIds = null;
                }
                PageInfo<JSONObject> listData = bytedanceVideoReportService.getVideoReportBy(accountIds, startDate, endDate, filedAll, target, order, clip, shot,plan,pageSize, pageNo);
                result.setResult(listData);
                result.setSuccess(true);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                result.setSuccess(false);
            }
        }
        return result;
    }

    @PostMapping("/detail")
    public Result<List<JSONObject>> getReportDetail(@RequestBody JSONObject requestBody) {
        Result<List<JSONObject>> result = new Result<>();
        if (requestBody.isEmpty()) {
            log.error("request body is empty");
            result.setSuccess(false);
        } else {

            JSONArray accountIds = requestBody.getJSONArray("accountIds");
            String signature = requestBody.getString("signature");
            String startDate = requestBody.getString("startDate");
            String endDate = requestBody.getString("endDate");

            String filedAll = JsonResourceUtil.joinAllFiled(AccountReportConstants.dicMapByVideo);

            try {
                if (accountIds.isEmpty()) {
                    accountIds = null;
                }
                List<JSONObject> listData = bytedanceVideoReportService.getVideoDetailBy(accountIds, startDate, endDate, filedAll,signature);
                result.setResult(listData);
                result.setSuccess(true);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                result.setSuccess(false);
            }
        }
        return result;
    }

    @PostMapping("/excel")
    public void getExcelReport(@RequestBody JSONObject requestBody,
                               HttpServletRequest request,
                               HttpServletResponse response) {
        //加一个参数区分是table页，还是详情页。
        String exportType= requestBody.getString("exportType");
        if(exportType.isEmpty()){
            return;
        }
        JSONArray columns = requestBody.getJSONArray("columns");
        if (columns.isEmpty()) {
            //默认消耗必查
            columns.add("cost");
        }
        String filed = JsonResourceUtil.joinFiled(AccountReportConstants.dicMapByVideo, columns);
        List<String> titles = new ArrayList<>(JsonResourceUtil.joinTitle(AccountReportConstants.dicMapByVideo, columns));
        //此处增加两个元素是为了保证数据顺序
        if("exportDetail".equals(exportType)){
            titles.add(0,"客户");
            titles.add(1,"项目名称");
            titles.add(2,"时间");
            titles.add(3,"消耗");
            columns.add(0, "advertiserName");
            columns.add(1, "projectName");
            columns.add(2, "statDate");
        }else{
            titles.add(0,"唯一标识");
            titles.add(1,"视频");
            titles.add(2,"视频名称");
            titles.add(3,"项目名称");
            titles.add(4,"上传时间");
            columns.add(0, "signature");
            columns.add(1, "url");
            columns.add(2, "materialName");
            columns.add(3, "projectName");
            columns.add(4, "createTime");
        }
        JSONArray accountIds = requestBody.getJSONArray("accountIds");
        if (accountIds.isEmpty()) {
            accountIds = null;
        }
        String startDate = requestBody.getString("startDate");
        String endDate = requestBody.getString("endDate");
        String signature = requestBody.getString("signature");
        String clip = requestBody.getString("clip");
        String shot = requestBody.getString("shot");
        String plan = requestBody.getString("plan");
        String target = requestBody.getString("target");
        String order = requestBody.getString("order");
        List<JSONObject> excelData=null;
        if("exportTable".equals(exportType)){
            excelData = bytedanceVideoReportService.exportExcelReportBy(accountIds, startDate, endDate, filed, target, order,clip,shot,plan);
        }else if("exportDetail".equals(exportType)){
            excelData = bytedanceVideoReportService.getVideoDetailBy(accountIds,startDate,endDate,filed,signature);
        }
        if (null!=excelData&&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());
        }
    }
}
