package cn.com.ctop.report.controller;

import cn.com.ctop.common.constant.AccountReportConstants;
import cn.com.ctop.common.mapper.SysRoleMapper;
import cn.com.ctop.common.service.IProjectMemberService;
import cn.com.ctop.common.service.IUserAllocationService;
import cn.com.ctop.common.utils.Check;
import cn.com.ctop.common.utils.ExportExcelUtils;
import cn.com.ctop.common.utils.HttpUtils;
import cn.com.ctop.common.utils.JsonResourceUtil;
import cn.com.ctop.report.service.IBytedanceMaterialVideoReportDailyDwService;
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.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.annotation.Resource;
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;

@RestController
@RequestMapping("material/bytedance/report")
@Slf4j
public class BytedanceMaterialReportDailyDwController {
    @Autowired
    IBytedanceMaterialVideoReportDailyDwService bytedanceMaterialVideoReportDailyDwService;
    @Resource
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private IProjectMemberService projectMemberService;
    @Autowired
    private IUserAllocationService userAllocationService;


    @PostMapping("/bytedance/list")
    public Result<PageInfo<JSONObject>> getListReport(@RequestBody JSONObject requestBody) {
        Result<PageInfo<JSONObject>> result = new Result<>();
        try {
            int pageSize = requestBody.getInteger("pageSize");
            int pageNo = requestBody.getInteger("pageNo");
            String startDate = requestBody.getString("startDate");
            String mediaType = requestBody.getString("mediaType");
            if (Check.isNull(startDate)) {
                throw new Exception("请输入查询开始时间");
            }
            String endDate = requestBody.getString("endDate");
            if (Check.isNull(endDate)) {
                throw new Exception("请输入查询结束时间");
            }

            //开始和结束时间的时间跨度，不能超过60天
            long days = DateUtils.getDiscrepantDays(startDate, endDate) + 1;
            if (days > 60) {
                throw new Exception("开始和结束时间的时间跨度，不能超过60天，请重新选择");
            }

            String filedAll = JsonResourceUtil.joinAllFiled(AccountReportConstants.getBytedanceVideoReportMap());
            if (Check.isNull(filedAll)) {
                throw new Exception("初始化查询 字段返回为空");
            }

            String userId = requestBody.getString("userId");
            if (Check.isNull(userId)) {
                throw new Exception("用户id不能为空");
            }
            Map<String, Object> requestMap = new HashMap<>();
            requestMap.put("filed", filedAll);
            requestMap.put("startDate", Long.parseLong(startDate.replace("-", "")));
            requestMap.put("endDate", Long.parseLong(endDate.replace("-", "")));

            if (!Check.isNull(requestBody.getJSONArray("accountIds"))) {
                requestMap.put("accountIds", requestBody.getJSONArray("accountIds"));
            }

            if (!Check.isNull(requestBody.getString("target"))) {
                requestMap.put("target", requestBody.getString("target"));
            }
            if (!Check.isNull(requestBody.getString("order"))) {
                requestMap.put("order", requestBody.getString("order"));
            }
            if (!Check.isNull(requestBody.getInteger("channelType"))) {
                requestMap.put("channelType", requestBody.getInteger("channelType"));
            }
            String roleCode = sysRoleMapper.getRoleCodeByUserId(userId);

            if (!Check.isNull(requestBody.getString("clipId"))) {
                requestMap.put("clipId", requestBody.getString("clipId"));
            }
            if (!Check.isNull(requestBody.getString("shotId"))) {
                requestMap.put("shotId", requestBody.getString("shotId"));
            }
            if (!Check.isNull(requestBody.getString("planId"))) {
                requestMap.put("planId", requestBody.getString("planId"));
            }
            if (!Check.isNull(requestBody.getString("leaderId"))) {
                requestMap.put("leaderId", requestBody.getString("leaderId"));
            }

            PageInfo<JSONObject> listData = bytedanceMaterialVideoReportDailyDwService.getBytedanceVideoPageReportByMap(requestMap, pageSize, pageNo);
            if (Check.isNull(listData)) {
                throw new Exception("暂无素材相关信息，请检查账户");
            }
            result.setSuccess(true);
            result.setResult(listData);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.setSuccess(false);
            result.setMessage(e.toString());
        }
        return result;
    }

    @PostMapping("/bytedance/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.getDicMapKs());
            try {
                if (accountIds.isEmpty()) {
                    accountIds = null;
                }
                List<JSONObject> listData = bytedanceMaterialVideoReportDailyDwService.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("/excelV2")
    public void excelV2(@RequestBody JSONObject requestBody,
                        HttpServletRequest request,
                        HttpServletResponse response) {
        Result<PageInfo<JSONObject>> result = new Result<>();
        try {
            String startDate = requestBody.getString("startDate");
            if (Check.isNull(startDate)) {
                throw new Exception("请输入查询开始时间");
            }
            String endDate = requestBody.getString("endDate");
            if (Check.isNull(endDate)) {
                throw new Exception("请输入查询结束时间");
            }


            String filedAll = JsonResourceUtil.joinAllFiled(AccountReportConstants.getBytedanceVideoReportMap());
            if (Check.isNull(filedAll)) {
                throw new Exception("初始化查询 字段返回为空");
            }

            String userId = requestBody.getString("userId");
            if (Check.isNull(userId)) {
                throw new Exception("用户id不能为空");
            }
            Map<String, Object> requestMap = new HashMap<>();
            requestMap.put("filed", filedAll);
            requestMap.put("startDate", Long.parseLong(startDate.replace("-", "")));
            requestMap.put("endDate", Long.parseLong(endDate.replace("-", "")));

            if (!Check.isNull(requestBody.getJSONArray("accountIds"))) {
                requestMap.put("accountIds", requestBody.getJSONArray("accountIds"));
            }

            if (!Check.isNull(requestBody.getString("target"))) {
                requestMap.put("target", requestBody.getString("target"));
            }
            if (!Check.isNull(requestBody.getString("order"))) {
                requestMap.put("order", requestBody.getString("order"));
            }
            if (!Check.isNull(requestBody.getInteger("channelType"))) {
                requestMap.put("channelType", requestBody.getInteger("channelType"));
            }
            String roleCode = sysRoleMapper.getRoleCodeByUserId(userId);

            if (!Check.isNull(requestBody.getString("clipId"))) {
                requestMap.put("clipId", requestBody.getString("clipId"));
            }
            if (!Check.isNull(requestBody.getString("shotId"))) {
                requestMap.put("shotId", requestBody.getString("shotId"));
            }
            if (!Check.isNull(requestBody.getString("planId"))) {
                requestMap.put("planId", requestBody.getString("planId"));
            }
            if (!Check.isNull(requestBody.getString("leaderId"))) {
                requestMap.put("leaderId", requestBody.getString("leaderId"));
            }

            JSONArray columns = requestBody.getJSONArray("columns");
            List<String> columns2 = new ArrayList();
            columns2.add("materialName");
            columns2.add("signature");
            columns2.add("projectName");
            columns2.add("designLeader");
            columns2.add("clip");
            columns2.add("plan");
            columns2.add("shot");
            columns2.add("purchaseRate");
            columns2.add("createTime");
            if (!Check.isNull(columns)) {
                for (int i = 0; i < columns.size(); i++) {
                    columns2.add(columns2.size(), columns.getString(i));
                }
            }
            columns2.add(columns2.size(), "url");
            List<String> titles = getfileIds(AccountReportConstants.getBytedanceVideoFiled(), columns2);

            List<JSONObject> listData = bytedanceMaterialVideoReportDailyDwService.getBytedanceVideoPageReportByMap(requestMap);


            if (Check.isNull(listData)) {
                throw new Exception("暂无素材相关信息，请检查账户");
            }
            List<List<Object>> excelList = new ArrayList<>();
            for (int i = 0; i < listData.size(); i++) {
                List<Object> temp = new ArrayList<>();
                JSONObject jsonObject = listData.get(i);
                for (int j = 0; j < columns2.size(); j++) {
                    String key = (String) columns2.get(j);
                    String value = jsonObject.getString(key);
                    temp.add(value);
                }
                excelList.add(temp);
            }
            try {
                String[] strings = titles.toArray(new String[]{});
                OutputStream os = response.getOutputStream();
                ExportExcelUtils eeu = new ExportExcelUtils();
                XSSFWorkbook workbook = new XSSFWorkbook();
                eeu.exportExcel(workbook, 0, "头条视频素材报表", strings, excelList);
                HttpUtils.setResponseHeader(response, "头条视频素材.xlsx");
                workbook.write(os);
                os.flush();
                os.close();
            } catch (IOException e) {
                log.error(e.getMessage());
            }
            result.setSuccess(true);

        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
            result.setSuccess(false);
            result.setMessage(e.getMessage());
        }


    }

    private List<String> getfileIds(Map<String, Map<String, Object>> kuaishouVideoReportMap, List columns) {

        List<String> titles = new ArrayList<>();
        for (int i = 0; i < columns.size(); i++) {
            String string = (String) columns.get(i);
            Map<String, Object> stringObjectMap = kuaishouVideoReportMap.get(string);
            if (Check.isNull(stringObjectMap)) {
                titles.add("-");
                continue;
            }
            Object comment = stringObjectMap.get("comment");
            titles.add(String.valueOf(comment));
        }

        return titles;
    }
}
