package cn.com.ctop.kuaishou.modules.batch.service.impl;

import cn.com.ctop.common.module.service.ISendMessageService;
import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.common.module.utils.HttpUtils;
import cn.com.ctop.common.module.utils.LoadFileUtil;
import cn.com.ctop.kuaishou.modules.batch.entity.JyClipCooperation;
import cn.com.ctop.kuaishou.modules.batch.entity.JyClipTopList;
import cn.com.ctop.kuaishou.modules.batch.entity.JyOrderList;

import cn.com.ctop.kuaishou.modules.batch.mapper.JiaoYangFenXiaoMapper;
import cn.com.ctop.kuaishou.modules.batch.service.IJiaoYangFenXiaoService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.jeecg.common.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class JiaoYangFenXiaoServiceImpl implements IJiaoYangFenXiaoService {

    private static String url = "https://cps.kwaixiaodian.com/gateway/distribute/platform/mcn/order/list";

    @Autowired
    private JiaoYangFenXiaoMapper jiaoYangFenXiaoMapper;
    @Autowired
    private ISendMessageService sendMessageService;

    @Override
    public List<JSONObject> getCookie() {
        return jiaoYangFenXiaoMapper.getCookie();
    }

    @Override
    public void getOrderList(String cookie, Integer current, Integer offset, Long orderCreateTimeStart, Long orderCreateTimeEnd) throws Exception {
        Thread.sleep(4000L);
        log.info("骄阳订单数据入参，开始时间：{},结束时间：{},数据：{}", DateUtils.tempToLongDateStr(orderCreateTimeStart), DateUtils.tempToLongDateStr(orderCreateTimeEnd), offset);
        Map<String, Object> params = new HashMap<>();
        if (!Check.isNull(orderCreateTimeStart)) {
            params.put("orderCreateTimeStart", orderCreateTimeStart);
        }
        if (!Check.isNull(orderCreateTimeEnd)) {
            params.put("orderCreateTimeEnd", orderCreateTimeEnd);
        }
        params.put("pageSize", 100);
        params.put("current", current);
        params.put("offset", offset);
        params.put("limit", 100);
        params.put("timeType", 1);
        Map<String, String> headers = new HashMap<>();
        headers.put("Cookie", cookie);
      /*  headers.put("Accept", "application/json");
        headers.put("Accept-Encoding", "gzip, deflate, br");
        headers.put("Accept-Language", "gzip, deflate, br");
        headers.put("Connection", "keep-alive");
        headers.put("Host", "cps.kwaixiaodian.com");
        headers.put("kpf", "PC_WEB");
        headers.put("Referer", "https://cps.kwaixiaodian.com/pc/leader/base/order-manage");
        headers.put("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:122.0) Gecko/20100101 Firefox/122.0");*/
        log.info("骄阳分销数据入参：{}", params);
        String resultStr = HttpUtils.KuaiShouttpGetRequest(url, params, headers);

        JSONObject result = JSONObject.parseObject(resultStr);
        if (Check.isNull(result)) {
            log.error("骄阳分销数据返回为空");
            return;
        }
        Integer code = result.getInteger("result");
        if (code != 1) {
            log.info("骄阳分销数据返回异常：", resultStr);
            sendMessageService.sendMessage("113dee46c7df464da78c07a985e92cd1", "骄阳分销cookie失效，请及时更新。媒体返回信息：" + resultStr);
            return;
        }
        JSONObject dataJson = result.getJSONObject("data");
        if (Check.isNull(dataJson)) {
            log.error("骄阳分销数据返回为data数据为空");
            return;
        }
        JSONArray list = dataJson.getJSONArray("list");
        if (Check.isNull(list)) {
            log.error("骄阳分销数据返回为list数据为空");
            return;
        }
        log.info("骄阳分销当前数据条数:{}", list.size());
        List<JyOrderList> orders = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            JSONObject jsonObject = list.getJSONObject(i);
            JyOrderList order = new JyOrderList();
            order.setOid(jsonObject.getLong("oid"));
            JSONObject item = jsonObject.getJSONArray("itemList").getJSONObject(0);
            if (!Check.isNull(item)) {
                order.setItemId(item.getLong("itemId"));
                order.setItemTitle(item.getString("itemTitle"));
                order.setReservePrice(item.getLong("reservePrice"));
                order.setImageUrl(item.getString("imageUrl"));
            }
            order.setOrderStatus(jsonObject.getInteger("orderStatus"));
            order.setOrderCreateTime(jsonObject.getLong("orderCreateTime"));
            order.setSendStatus(jsonObject.getInteger("sendStatus"));
            order.setSettlementBizType(jsonObject.getInteger("settlementBizType"));
            order.setSettlementBizTypeDesc(jsonObject.getString("settlementBizTypeDesc"));
            order.setSendTime(jsonObject.getLong("sendTime"));
            order.setRecvTime(jsonObject.getLong("recvTime"));
            order.setSellerId(jsonObject.getLong("sellerId"));
            order.setPromotionId(jsonObject.getLong("promotionId"));
            order.setPromotionNickName(filterSupplement(jsonObject.getString("promotionNickName")));
            order.setClipUserId(jsonObject.getLong("clipUserId"));
            order.setClipNickName(jsonObject.getString("clipNickName"));
            order.setActivityId(jsonObject.getLong("activityId"));
            order.setOrderAmount(jsonObject.getLong("orderAmount"));
            order.setPayAmount(jsonObject.getLong("payAmount"));
            order.setRegimentalPromotionRate(jsonObject.getLong("regimentalPromotionRate"));
            order.setShareRate(jsonObject.getLong("shareRate"));
            order.setBaseAmount(jsonObject.getLong("baseAmount"));
            order.setCommissionRate(jsonObject.getLong("commissionRate"));
            order.setRegimentalPromotionAmount(jsonObject.getLong("regimentalPromotionAmount"));
            order.setTotalRegimentalSettleAmount(jsonObject.getLong("totalRegimentalSettleAmount"));
            order.setStatDate(DateUtils.tempToLongDate(jsonObject.getLong("orderCreateTime")));
            order.setStatHour(DateUtils.getHour(jsonObject.getLong("orderCreateTime")));
            order.setMcnPromotionAmount(jsonObject.getLong("mcnPromotionAmount"));
            order.setMcnSettlementAmount(jsonObject.getLong("mcnSettlementAmount"));
            orders.add(order);
        }
        try {
            if (!Check.isNull(orders)) {
                jiaoYangFenXiaoMapper.replace(orders);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (list.size() >= 100) {
            getOrderList(cookie, current + 1, offset + 100, orderCreateTimeStart, orderCreateTimeEnd);
        }

    }

    @Override
    public void getClipCooperation(String cookie, Integer offset, Long statDate, Integer status) throws Exception {
        Thread.sleep(2000L);
        Map<String, Object> params = new HashMap<>();
        params.put("status", status);
        params.put("limit", 10);
        params.put("offset", offset);
        Map<String, String> headers = new HashMap<>();
        headers.put("Cookie", cookie);
        String postUrl = "https://cps.kwaixiaodian.com/gateway/distribute/platform/recreate/leader/clip/cooperation/list";
        String resultStr = HttpUtils.httpPostRequest(postUrl, params, headers);
        JSONObject result = JSONObject.parseObject(resultStr);
        if (Check.isNull(result)) {
            log.error("骄阳分销数据返回为空");
            return;
        }
        Integer code = result.getInteger("result");
        if (code != 1) {
            log.info("骄阳分销尔创列表数据返回异常：", resultStr);
            sendMessageService.sendMessage("113dee46c7df464da78c07a985e92cd1", "骄阳分销cookie失效，请及时更新。媒体返回信息：" + resultStr);
            return;
        }
        JSONObject dataJson = result.getJSONObject("data");
        if (Check.isNull(dataJson)) {
            log.error("骄阳分销数据返回为data数据为空");
            return;
        }
        JSONArray list = dataJson.getJSONArray("leaderCoopClip");
        if (Check.isNull(list)) {
            log.error("骄阳分销数据返回为list数据为空");
            return;
        }
        log.info("骄阳分销当前数据条数:{}", list.size());
        List<JyClipCooperation> adds = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            JSONObject jsonObject = list.getJSONObject(i);
            JyClipCooperation clipCooperation = new JyClipCooperation();
            clipCooperation.setClipId(jsonObject.getLong("clipId"));
            clipCooperation.setClipName(jsonObject.getString("clipName"));
            clipCooperation.setHeadImg(jsonObject.getString("headImg"));
            clipCooperation.setCommissionRate(jsonObject.getLong("commissionRate"));
            clipCooperation.setFansNum(jsonObject.getString("fansNum"));
            clipCooperation.setGmv30d(jsonObject.getString("gmv30d"));
            clipCooperation.setStartTime(jsonObject.getString("startTime"));
            clipCooperation.setEndTime(jsonObject.getString("endTime"));
            clipCooperation.setStatus(jsonObject.getInteger("status"));
            clipCooperation.setTerminationReason(jsonObject.getString("terminationReason"));
            clipCooperation.setCommissionRateView(jsonObject.getString("commissionRateView"));
            clipCooperation.setShopScore(jsonObject.getString("shopScore"));
            clipCooperation.setClipGmv30d(jsonObject.getString("clipGmv30d"));
            clipCooperation.setAuthItemGmv30d(jsonObject.getString("authItemGmv30d"));
            clipCooperation.setStatDate(statDate);
           /*  JSONObject getData = this.getClipData(jsonObject.getLong("clipId"), cookie);
           if (!Check.isNull(getData)) {
                clipCooperation.setVideoCount(getData.getString("videoCount"));
                clipCooperation.setVideoShow(getData.getString("videoShow"));
                Thread.sleep(60 * 1000);
            }*/
            adds.add(clipCooperation);


        }
        jiaoYangFenXiaoMapper.replaceClipCooperation(adds);
        if (list.size() >= 10) {
            getClipCooperation(cookie, offset + 10, statDate, status);
        }
    }

    @Override
    public String getCookieById(Long id) {
        return jiaoYangFenXiaoMapper.getCookieById(id);
    }

    @Override
    public List<JSONObject> getAccountList() {
        return jiaoYangFenXiaoMapper.getAccountList();
    }

    @Override
    public void getItemTop(String cookie, Long statDate, Long id, String name, Integer offset) {
        JSONObject returnJson = new JSONObject();
        Map<String, Object> params = new HashMap<>();
        params.put("activityUserId", id);
        params.put("bizCode", 2);
        params.put("limit", 10);
        params.put("offset", offset);
        Map<String, String> headers = new HashMap<>();
        headers.put("Cookie", cookie);
        String postUrl = "https://cps.kwaixiaodian.com/gateway/distribute/platform/seller/activity/topItem/list";
        String resultStr = null;
        try {
            resultStr = HttpUtils.KuaiShouttpGetRequest(postUrl, params, headers);
        } catch (Exception e) {
            e.printStackTrace();
        }
        JSONObject result = JSONObject.parseObject(resultStr);
        Integer code = result.getInteger("result");
        JSONArray topActivityItemInfo = new JSONArray();
        if (code == 1) {
            JSONObject data = result.getJSONObject("data");
            if (!Check.isNull(data)) {
                topActivityItemInfo = data.getJSONArray("topActivityItemInfo");
                for (int i = 0; i < topActivityItemInfo.size(); i++) {
                    JSONObject jsonObject = topActivityItemInfo.getJSONObject(i);
                    jsonObject.put("statDate", statDate);
                    jsonObject.put("clipId", id);
                    jsonObject.put("clipName", name);
                }

                List<JyClipTopList> adds = topActivityItemInfo.toJavaList(JyClipTopList.class);
                if (!Check.isNull(adds)) {
                    jiaoYangFenXiaoMapper.replaceTopItem(adds);
                }
            }
        }

        if (topActivityItemInfo.size() > 0) {
            getItemTop(cookie, statDate, id, name, offset + 10);
        }

    }

    @Override
    public void getClipCooperationV2(String cookie, int offset, Long statDate, Integer status) throws Exception {
        Map<String, Object> params = new HashMap<>();
        params.put("status", status);
        params.put("limit", 10);
        params.put("offset", offset);
        Map<String, String> headers = new HashMap<>();
        headers.put("Cookie", cookie);
        String postUrl = "https://cps.kwaixiaodian.com/gateway/distribute/platform/recreate/leader/clip/cooperation/list";
        String resultStr = HttpUtils.httpPostRequest(postUrl, params, headers);
        JSONObject result = JSONObject.parseObject(resultStr);
        if (Check.isNull(result)) {
            log.error("骄阳分销数据返回为空");
            return;
        }
        Integer code = result.getInteger("result");
        if (code != 1) {
            log.info("骄阳分销尔创列表数据返回异常：", resultStr);
            sendMessageService.sendMessage("113dee46c7df464da78c07a985e92cd1", "骄阳分销cookie失效，请及时更新。媒体返回信息：" + resultStr);
            return;
        }
        JSONObject dataJson = result.getJSONObject("data");
        if (Check.isNull(dataJson)) {
            log.error("骄阳分销数据返回为data数据为空");
            return;
        }
        JSONArray list = dataJson.getJSONArray("leaderCoopClip");
        if (Check.isNull(list)) {
            log.error("骄阳分销数据返回为list数据为空");
            return;
        }
        log.info("骄阳分销当前数据条数:{}", list.size());
        List<JyClipCooperation> adds = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            JSONObject jsonObject = list.getJSONObject(i);
            JyClipCooperation clipCooperation = new JyClipCooperation();
            clipCooperation.setClipId(jsonObject.getLong("clipId"));
            clipCooperation.setClipName(jsonObject.getString("clipName"));
            clipCooperation.setHeadImg(jsonObject.getString("headImg"));
            clipCooperation.setCommissionRate(jsonObject.getLong("commissionRate"));
            clipCooperation.setFansNum(jsonObject.getString("fansNum"));
            clipCooperation.setGmv30d(jsonObject.getString("gmv30d"));
            clipCooperation.setStartTime(jsonObject.getString("startTime"));
            clipCooperation.setEndTime(jsonObject.getString("endTime"));
            clipCooperation.setStatus(jsonObject.getInteger("status"));
            clipCooperation.setTerminationReason(jsonObject.getString("terminationReason"));
            clipCooperation.setCommissionRateView(jsonObject.getString("commissionRateView"));
            clipCooperation.setShopScore(jsonObject.getString("shopScore"));
            clipCooperation.setClipGmv30d(jsonObject.getString("clipGmv30d"));
            clipCooperation.setAuthItemGmv30d(jsonObject.getString("authItemGmv30d"));
            clipCooperation.setStatDate(statDate);
            JSONObject getData = this.getClipData(jsonObject.getLong("clipId"), cookie);
            if (!Check.isNull(getData)) {
                clipCooperation.setVideoCount(getData.getString("videoCount"));
                clipCooperation.setVideoShow(getData.getString("videoShow"));
                Thread.sleep(60 * 1000);
            }
            adds.add(clipCooperation);


        }
        jiaoYangFenXiaoMapper.replaceClipCooperation(adds);
        if (list.size() >= 10) {
            getClipCooperation(cookie, offset + 10, statDate, status);
        }
    }

    private JSONObject getClipData(Long clipId, String cookie) {
        JSONObject returnJson = new JSONObject();
        Map<String, Object> params = new HashMap<>();
        params.put("clipId", clipId);
        params.put("dimensionType", 1);
        Map<String, String> headers = new HashMap<>();
        headers.put("Cookie", cookie);
        String postUrl = "https://cps.kwaixiaodian.com/gateway/distribute/platform/recreate/leader/clip/cooperation/detail/export";
        String resultStr = HttpUtils.httpPostRequest(postUrl, params, headers);
        JSONObject result = JSONObject.parseObject(resultStr);
        log.info("骄阳获取二创返回结果：{}", result);
        Integer code = result.getInteger("result");
        if (code == 1) {
            JSONObject data = result.getJSONObject("data");
            if (!Check.isNull(data)) {
                String fileUrl = data.getString("fileUrl");
                try {
                    // 创建Workbook对象
                    String localPath = LoadFileUtil.downLoadExcel(fileUrl, "/data/file/jy/", clipId + ".xlsx", cookie);
                    // FileFormat.Ver
                    Workbook workbook = WorkbookFactory.create(new FileInputStream(new File(localPath)));
                    // 获取第一个Sheet对象
                    Sheet sheet = workbook.getSheet("概况");
                    int firstRowNum = sheet.getFirstRowNum();
                    int lastRowNum = sheet.getLastRowNum();
                    for (int rowNum = firstRowNum + 1; rowNum <= lastRowNum; rowNum++) {
                        Row row = sheet.getRow(rowNum);
                        if (row == null) {
                            continue;
                        }
                        int firstCellNum = row.getFirstCellNum();
                        int lastCellNum = row.getLastCellNum();

                        for (int cellNum = firstCellNum; cellNum < lastCellNum; cellNum++) {
                            Cell cell = row.getCell(cellNum);
                            String cellValue = getCellValue(cell);
                            if (cellNum == 4) {
                                returnJson.put("videoCount", cellValue);
                            }
                            if (cellNum == 6) {
                                returnJson.put("videoShow", cellValue);
                            }
                        }
                    }
                    LoadFileUtil.delFile(localPath);
                    // 关闭Workbook对象
                    workbook.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } else {
            log.info("获取文件失败");
        }

        return returnJson;

    }


    public static String getCellValue(Cell cell) {
        String cellValue = "";
        if (cell == null) {
            return cellValue;
        }
        // 把数字当成String来读，避免出现1读成1.0的情况
        if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
            cell.setCellType(Cell.CELL_TYPE_STRING);
        }
        // 判断数据的类型
        switch (cell.getCellType()) {
            case Cell.CELL_TYPE_NUMERIC:
                // 数字
                cellValue = String.valueOf(cell.getNumericCellValue());
                break;
            case Cell.CELL_TYPE_STRING:
                // 字符串
                cellValue = String.valueOf(cell.getStringCellValue());
                break;
            case Cell.CELL_TYPE_BOOLEAN:
                // Boolean
                cellValue = String.valueOf(cell.getBooleanCellValue());
                break;
            case Cell.CELL_TYPE_FORMULA:
                // 公式
                cellValue = String.valueOf(cell.getCellFormula());
                break;
            case Cell.CELL_TYPE_BLANK:
                // 空值
                cellValue = "";
                break;
            case Cell.CELL_TYPE_ERROR:
                // 故障
                cellValue = "非法字符";
                break;
            default:
                cellValue = "未知类型";
                break;
        }

        return cellValue;
    }


    public static String filterSupplement(String content) {
        StringBuilder sb = new StringBuilder();
        for (char ch : content.toCharArray()) {
            if (!Character.isHighSurrogate(ch) && !Character.isLowSurrogate(ch)) {
                sb.append(ch);
            }
        }
        return sb.toString();
    }

}
