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.RateUtil;
import cn.com.ctop.common.module.vo.DailyAccountReportVO;
import cn.com.ctop.common.module.vo.DailyGroupReportVO;
import cn.com.ctop.common.module.vo.DailyReportVO;
import cn.com.ctop.kuaishou.modules.report.service.IDailyReportService;
import com.alibaba.fastjson.JSONObject;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Api(tags = "广告主日报表")
@RestController
@RequestMapping("/ctop/daily")
public class DailyReportController {
    @Autowired
    private IDailyReportService dailyReportService;


    @PostMapping(value = "/getDailyReport")
    public Result<DailyReportVO> getDailyReport(@RequestBody JSONObject requestJson) {

        Result<DailyReportVO> result = new Result<>();
        try {
            DailyReportVO dailyReport = dailyReportService.getDailyReport(requestJson);
            result.setSuccess(true);
            result.setResult(dailyReport);

        } catch (Exception e) {
            result.setSuccess(false);

            e.printStackTrace();

        }
        return result;

    }

    /**
     * 导出报表
     *
     * @return
     */
    @RequestMapping(value = "/exportDailyReport")
    @ResponseBody
    public void export(HttpServletRequest request, HttpServletResponse response, @RequestBody JSONObject requestJson) throws Exception {
        DailyReportVO dailyReport = dailyReportService.getDailyReport(requestJson);

        List<List<Object>> accountData = new ArrayList<>();
        if (!Check.isNull(dailyReport)) {
            DailyAccountReportVO dailyAccountReport = dailyReport.getDailyAccountReport();
            if (!Check.isNull(dailyAccountReport)) {
                List<Object> rowData = new ArrayList();
                rowData.add(requestJson.getString("date")); // 时间
                rowData.add(dailyAccountReport.getCost()); // 消耗
                rowData.add(dailyAccountReport.getContractRebateRealCharged()); // 激励花费
                rowData.add(dailyAccountReport.getActualCost()); // 实际花费
                rowData.add(dailyAccountReport.getPhotoShow()); // 展示数
                rowData.add(dailyAccountReport.getAclick()); // 素材曝光数数
                rowData.add(dailyAccountReport.getPhotoClick()); // 点击数

                rowData.add(RateUtil.getRate(dailyAccountReport.getPhotoClickRatio())); // 点击率
                rowData.add(dailyAccountReport.getPhotoClickCost()); // 平均点击花费
                rowData.add(dailyAccountReport.getBclick()); // 行为数
                rowData.add(RateUtil.getRate(dailyAccountReport.getActionRatio())); // 行为率
                rowData.add(dailyAccountReport.getImpression1kCost()); // 平均千次展现花费
                rowData.add(dailyAccountReport.getConversions()); // 转化数
                rowData.add(dailyAccountReport.getConversionPrice()); // 转化单价
                rowData.add(RateUtil.getRate(dailyAccountReport.getConversionRate())); // 转化率
                rowData.add(dailyAccountReport.getDiscountConversionPrice()); // 折后转化成本
                accountData.add(rowData);
            }
        }

        List<List<Object>> group = new ArrayList<>();
        List<DailyGroupReportVO> dailyGroupReport = dailyReport.getDailyGroupReport();
        if (!Check.isNull(dailyGroupReport)) {
            for (DailyGroupReportVO groupReportVO : dailyGroupReport) {
                List<Object> dailyGroup = new ArrayList();
                dailyGroup.add(groupReportVO.getAccountId());
                dailyGroup.add(groupReportVO.getAuthName());
                dailyGroup.add(groupReportVO.getStatDate());
                dailyGroup.add(groupReportVO.getCampaignName());
                dailyGroup.add(groupReportVO.getUnitName());
                dailyGroup.add(groupReportVO.getCost()); // 花费
                dailyGroup.add(groupReportVO.getDisCountCost()); // 折后花费
                dailyGroup.add(groupReportVO.getPhotoShow()); // 展示数
                dailyGroup.add(groupReportVO.getPhotoClick()); // 点击数
                dailyGroup.add(groupReportVO.getBclick());   // 行为数
                dailyGroup.add(RateUtil.getRate(groupReportVO.getPhotoClickRatio())); // 点击率
                dailyGroup.add(RateUtil.getRate(groupReportVO.getActionRatio())); // 行为率

                dailyGroup.add(groupReportVO.getImpression1kCost()); // 平均千次展现花费
                dailyGroup.add(groupReportVO.getPhotoClickCost()); // 平均点击花费
                dailyGroup.add(groupReportVO.getConversions()); // 转化数
                //  dailyGroup.add(groupReportVO.getConversionPrice()); // 转化单价
                dailyGroup.add(groupReportVO.getDiscountConversionPrice()); // 折后转化成本
                dailyGroup.add(RateUtil.getRate(groupReportVO.getClickConversionRate())); // 点击转化率

                group.add(dailyGroup);
            }

        }

        String[] accountHeaders = {"时间", "消耗（元）", "激励花费（元）", "实际消耗（元）", "展示数", "素材曝光数", "点击数", "点击率", "平均点击花费（元）", "行为数", "行为率", "平均千次展现花费（元）", "转化数（元）", "转化单价", "转化率", "折后转化成本（元）"};
        String[] groupHeaders = {"账号", "账号名称", "日期", "计划名称", "广告组名称", "消耗（元）", "折后消耗（元）", "展现", "点击数", "行为数", "点击率", "行为率", "平均千次展现费用（元）", "平均点击费用（元）", "转化数", "折后转化成本（元）", "点击转化率"};
        OutputStream os = response.getOutputStream();
        ExportExcelUtils eeu = new ExportExcelUtils();
        XSSFWorkbook workbook = new XSSFWorkbook();
        eeu.exportExcel(workbook, 0, "分日数据", accountHeaders, accountData);
        eeu.exportExcel(workbook, 1, "分组数据", groupHeaders, group);
        this.setResponseHeader(response, "日报.xls");
        workbook.write(os);
        os.flush();
        os.close();
    }

    //发送响应流方法
    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(), "ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }


}
