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

import cn.com.ctop.common.module.entity.UserCompany;
import cn.com.ctop.common.module.service.ISysUserService;
import cn.com.ctop.common.module.service.IUserCompanyService;
import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.common.module.utils.ExportExcelUtils;
import cn.com.ctop.common.module.utils.HttpUtils;
import cn.com.ctop.kuaishou.modules.report.service.IKsVideoReportService;
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.system.entity.SysUser;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.utils.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.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by JQ.bi on 2020.09.27
 */
@Slf4j
@RestController
@RequestMapping("/ctop/kuaishou/videoReport")
public class KsVideoReportCtrl {

    @Autowired
    IKsVideoReportService ksVideoReportService;
    @Autowired
    private IUserCompanyService companyService;


    @PostMapping("/getDesignList")
    public Result<List<JSONObject>> getDesignList() {
        Result<List<JSONObject>> result = new Result<>();
        try {
            List<JSONObject> designList = ksVideoReportService.getDesignList();
            result.setSuccess(true);
            result.setResult(designList);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
            result.setSuccess(false);
            result.setMessage(e.getMessage());
        }
        return result;
    }

    @Autowired
    private ISysUserService sysUserService;

    @PostMapping("/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");
            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.getKuaishouVideoReportMap());
            filedAll = filedAll.replace("t1.photo_show", "`show`");
            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<>();
            SysUser user = sysUserService.getById(userId);
            if (Check.isNull(user)) {
                throw new Exception("用户信息为空");
            }

            JSONArray accountIds = requestBody.getJSONArray("accountIds");
            if (Check.isNull(accountIds)) {
                if (!"管理员".equals(user.getRealname()) && !"吴睿刚".equals(user.getRealname())) {
                    UserCompany userCompany = companyService.getByUserId(userId);
                    if (Check.isNull(userCompany)) {
                        throw new Exception("公司信息为空");
                    }
                    requestMap.put("companyId", userCompany.getCompanyId());
                }
            }
            requestMap.put("filed", filedAll);
            requestMap.put("startDate", startDate);
            requestMap.put("endDate", endDate);
            if (!Check.isNull(accountIds)) {
                requestMap.put("accountIds", requestBody.getJSONArray("accountIds"));
            }
            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"));
            }
            if (!Check.isNull(requestBody.getString("target"))) {
                if ("photo_show".equals(requestBody.getString("target"))) {
                    requestMap.put("target", "`show`");
                } else {
                    requestMap.put("target", requestBody.getString("target"));
                }
            }
            if (!Check.isNull(requestBody.getString("order"))) {
                requestMap.put("order", requestBody.getString("order"));
            }
            if (!Check.isNull(requestBody.getString("channelType"))) {
                requestMap.put("channelType", requestBody.getString("channelType"));
            }
            PageInfo<JSONObject> listData = ksVideoReportService.getKuaiShouVideoPageReportByMap(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("/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 = ksVideoReportService.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 {


            if (Check.isNull(requestBody)) {
                throw new Exception("入参不能为空");
            }
            JSONArray columns = requestBody.getJSONArray("columns");
            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 userId = requestBody.getString("userId");
            if (Check.isNull(userId)) {
                throw new Exception("用户id不能为空");
            }
            Map<String, Object> requestMap = new HashMap<>();
            SysUser user = sysUserService.getById(userId);
            if (Check.isNull(user)) {
                throw new Exception("用户信息为空");
            }
            JSONArray accountIds = requestBody.getJSONArray("accountIds");
            if (Check.isNull(accountIds)) {
                if (!"管理员".equals(user.getRealname()) && !"吴睿刚".equals(user.getRealname())) {
                    UserCompany userCompany = companyService.getByUserId(userId);
                    if (Check.isNull(userCompany)) {
                        throw new Exception("公司信息为空");
                    }
                    requestMap.put("companyId", userCompany.getCompanyId());
                }
            }
            String filedAll = JsonResourceUtil.joinAllFiled(AccountReportConstants.getKuaishouVideoReportMap());
            if (Check.isNull(filedAll)) {
                throw new Exception("初始化查询 字段返回为空");
            }
            filedAll = filedAll.replace("photo_show", "`show`")
                    .replace("keyAction", "key_action")
                    .replace("keyActionCost", "key_action_cost");

            requestMap.put("filed", filedAll);
            requestMap.put("startDate", startDate);
            requestMap.put("endDate", endDate);
            if (!Check.isNull(requestBody.getJSONArray("accountIds"))) {
                requestMap.put("accountIds", requestBody.getJSONArray("accountIds"));
            }
            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"));
            }
            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.getString("channelType"))) {
                requestMap.put("channelType", requestBody.getString("channelType"));
            }
            JSONArray columns2 = new JSONArray();
            columns2.add(0, "materialName");
            columns2.add(1, "signature");
            columns2.add(2, "projectName");
            columns2.add(3, "channel");
            columns2.add(4, "designLeader");
            columns2.add(5, "clip");
            columns2.add(6, "plan");
            columns2.add(7, "shot");
            columns2.add(8, "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.getKuaishouVideoReportDict(), columns2);
            List<JSONObject> listData = ksVideoReportService.getKuaiShouVideoReportByMap(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 = columns2.getString(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, JSONArray columns) {
        List<String> titles = new ArrayList<>();
        for (int i = 0; i < columns.size(); i++) {
            String string = columns.getString(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;
    }
}
