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

import cn.com.ctop.common.module.utils.*;
import cn.com.ctop.kuaishou.modules.report.service.IDuanJUReportService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
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.util.DateUtils;
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.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/duanju/report")
public class DuanJUReportController {
    @Autowired
    private IDuanJUReportService duanJUReportService;

    @GetMapping("/getTotalCharge")
    public Result<Object> getTotalCharge(String startDate, String endDate) {
        try {
            Long start = DateUtils.dateToLong(startDate);
            Long end = DateUtils.dateToLong(endDate);
            Map<String, Object> requestMap = new HashMap<>();
            requestMap.put("start", start);
            requestMap.put("end", end);
            JSONObject data = duanJUReportService.getTotalCharge(requestMap);
            return Result.OK(data);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.error("查询失败");
    }


    @GetMapping("/getAccountList")
    public Result<Object> getAccountList(String startDate, String endDate, Integer pageNo, Integer pageSize) {
        try {
            Long start = DateUtils.dateToLong(startDate);
            Long end = DateUtils.dateToLong(endDate);
            Map<String, Object> requestMap = new HashMap<>();
            requestMap.put("start", start);
            requestMap.put("end", end);
            return duanJUReportService.getAccountList(pageNo, pageSize, requestMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.error("查询失败");
    }

    @GetMapping("/getDuanJuList")
    public Result<Object> getDuanJuList(String startDate, String endDate, Integer pageNo, Integer pageSize) {
        try {
            Long start = DateUtils.dateToLong(startDate);
            Long end = DateUtils.dateToLong(endDate);
            Map<String, Object> requestMap = new HashMap<>();
            requestMap.put("start", start);
            requestMap.put("end", end);
            return duanJUReportService.getDuanJuList(pageNo, pageSize, requestMap);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.error("查询失败");
    }

    @GetMapping("/stopList")
    public Result<Object> stopList(Long accountId) {
        try {

            Map<String, Object> requestMap = new HashMap<>();
            requestMap.put("accountId", accountId);

            List<JSONObject> data = duanJUReportService.stopList(requestMap);
            return Result.OK(data);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.error("查询失败");
    }

    @GetMapping("/getViodeoList")
    public Result<Object> getViodeoList(String startDate, String endDate, String videoName, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo, @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        try {
            Long start = DateUtils.dateToLong(startDate);
            Long end = DateUtils.dateToLong(endDate);
            Map<String, Object> requestMap = new HashMap<>();
            requestMap.put("start", start);
            requestMap.put("end", end);
            if (!Check.isNull(videoName)) {
                requestMap.put("videoName", videoName);
            }
            return duanJUReportService.getViodeoListByPage(requestMap, pageNo, pageSize);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.error("查询失败");
    }

    @GetMapping("/exportVideoList")
    public Result<Object> exportVideoList(String startDate, String endDate, String videoName,
                                          HttpServletRequest request, HttpServletResponse response) {
        try {
            Long start = DateUtils.dateToLong(startDate);
            Long end = DateUtils.dateToLong(endDate);
            Map<String, Object> requestMap = new HashMap<>();
            requestMap.put("start", start);
            requestMap.put("end", end);
            if (!Check.isNull(videoName)) {
                requestMap.put("videoName", videoName);
            }
            List<JSONObject> data = duanJUReportService.getViodeoList(requestMap);
            List<List<Object>> exportList = new ArrayList<>();
            if (!Check.isNull(data)) {
                for (int i = 0; i < data.size(); i++) {
                    JSONObject date = data.get(i);
                    List<Object> export = new ArrayList();
                    export.add(date.getString("photo_id"));
                    export.add(date.getString("photo_name"));
                    export.add(date.getString("cover_url"));
                    export.add(date.getString("photo_url"));
                    export.add(date.getString("charge"));
                    export.add(date.getString("roi"));
                    export.add(date.getString("event_pay_purchase_amount"));
                    export.add(date.getString("aclick"));
                    export.add(date.getString("bclick"));
                    export.add(date.getString("ctr"));
                    export.add(date.getString("cpc"));
                    export.add(date.getString("cpm"));
                    export.add(date.getString("activation"));
                    export.add(date.getString("active_cost"));
                    export.add(date.getString("event_pay"));
                    export.add(date.getString("pay_cost"));
                    export.add(date.getString("event_new_user_pay"));
                    export.add(date.getString("new_pay_cost"));
                    export.add(date.getString("play_3s_rate"));
                    export.add(date.getString("play_5s_rate"));
                    export.add(date.getString("play_end_rate"));
                    exportList.add(export);
                }
            }
            String[] headers = new String[]{"素材ID", "素材名称", "封面", "素材链接", "消耗", "ROI", "付费金额", "曝光", "点击", "ctr", "cpc", "cpm", "激活", "激活成本", "付费次数", "付费成本", "新增付费人数", "新增付费单价", "3s播放率", "5s播放率", "完播率"};


            OutputStream os = response.getOutputStream();
            ExportExcelUtils eeu = new ExportExcelUtils();
            XSSFWorkbook workbook = new XSSFWorkbook();
            eeu.exportExcel(workbook, 0, "短剧报表", headers, exportList);
            this.setResponseHeader(response, "短剧报表.xls");
            workbook.write(os);
            os.flush();
            os.close();

            return Result.OK(data);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.error("查询失败");
    }


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

    @GetMapping("/stopPlan")
    public Result<Object> stopPlan(Long accountId) {
        try {

            if (Check.isNull(accountId)) {
                throw new Exception("请传入账户ID");
            }
            String token = duanJUReportService.getAgentToken(165893351L);
            getPlan(accountId, token, 1);
            return Result.OK();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.error("查询失败");
    }

    /*   @GetMapping("/getPlan")*/
    public void getPlan(Long accountId, String token, Integer page) {
        String url = "https://ad.e.kuaishou.com/rest/openapi/gw/dsp/campaign/list";
        Map<String, String> headers = new HashMap<>();
        headers.put("Access-Token", token);
        headers.put("Content-Type", " application/json");
        JSONObject param = new JSONObject();
        param.put("advertiser_id", accountId);
        param.put("page", page);
        param.put("page_size", 500);
        param.put("status", 4);

        String result = HttpUtils.kuaiShouhttpPostRequest(url, param.toJSONString(), headers);
        JSONObject resultJson = JSONObject.parseObject(result);
        if (Check.isNull(resultJson)) {
            log.error("获取广告计划信息返回结果异常,advertiserId:{}", accountId);
            return;
        }
        Integer code = resultJson.getInteger("code");
        if (null == code || code != 0) {
            log.error("获取广告计划信息返回结果异常,advertiserId:{},异常信息:{}", accountId, resultJson);
            return;
        }
        JSONObject dataJson = resultJson.getJSONObject("data");
        JSONArray details = dataJson.getJSONArray("details");
        List<JSONObject> adds = new ArrayList<>();
        if (!Check.isNull(details)) {
            for (int i = 0; i < details.size(); i++) {
                JSONObject addJson = new JSONObject();
                JSONObject planInfo = details.getJSONObject(i);
                String campaignName = planInfo.getString("campaign_name");
                Long campaignId = planInfo.getLong("campaign_id");
                addJson.put("accountId", accountId);
                addJson.put("campaignId", campaignId);
                addJson.put("campaignName", campaignName);
                String updateUrl = "https://ad.e.kuaishou.com/rest/openapi/v1/campaign/update/status";
                JSONObject updateParam = new JSONObject();
                updateParam.put("advertiser_id", accountId);
                updateParam.put("put_status", 2);
                updateParam.put("campaign_id", campaignId);
                String updateResult = HttpUtils.kuaiShouhttpPostRequest(updateUrl, updateParam.toJSONString(), headers);
                JSONObject updateJson = JSONObject.parseObject(updateResult);
                if (!Check.isNull(updateJson)) {
                    addJson.put("updateMessage", "暂停失败，返回为空");
                }
                Integer code1 = updateJson.getInteger("code");
                if (code1 == 0) {
                    addJson.put("updateMessage", "暂停成功");
                } else {
                    addJson.put("updateMessage", "暂停失败，" + updateJson.getString("message"));
                }
                adds.add(addJson);
            }
        }

        if (!Check.isNull(adds)) {
            duanJUReportService.replaceDatas(adds);
        }

        if (details.size() >= 500) {
            getPlan(accountId, token, page + 1);
        }

    }

}
