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.kuaishou.modules.batch.entity.KuaishouSupplyChain;
import cn.com.ctop.kuaishou.modules.batch.entity.KuaishouSupplyChainSettlement;
import cn.com.ctop.kuaishou.modules.batch.entity.vo.ItemCheck;
import cn.com.ctop.kuaishou.modules.batch.mapper.KuaishouSupplyChainMapper;
import cn.com.ctop.kuaishou.modules.batch.mapper.RocketSupplyChainMapper;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaishouSupplyChainService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 快手电商-供应链订单信息
 *
 * @author jeecg-boot
 * 2022-12-01
 * @version V1.0
 */
@Slf4j
@Service
public class KuaishouSupplyChainServiceImpl extends ServiceImpl<KuaishouSupplyChainMapper, KuaishouSupplyChain> implements IKuaishouSupplyChainService {
    private static String url = "https://cps.kwaixiaodian.com/distribute/pc/investment/order/list";
    @Autowired
    private ISendMessageService sendMessageService;
    @Autowired
    private KuaishouSupplyChainMapper supplyChainMapper;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private RocketSupplyChainMapper rocketSupplyChainMapper;

    public static void main(String[] args) {
        System.err.println(DateUtils.tempToLongDateStr(1706112000000L));
    }


    @Transactional
    @Override
    public void getOrderList(String cookie, Integer offset, Long orderCreateTimeStart, Long orderCreateTimeEnd, Long regimentalId) throws Exception {
        Thread.sleep(1500);
        log.info("567团长抓取订单数据入参，开始时间：{},结束时间：{},数据：{}", 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("fundType", 1);
        params.put("timeType", 1);
        params.put("limit", 100);
        params.put("offset", offset);

        Map<String, String> headers = new HashMap<>();
        headers.put("Cookie", cookie);

        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<KuaishouSupplyChain> ruixuanSupplyChains = new ArrayList<>();
        List<KuaishouSupplyChain> mgsSupplyChains = new ArrayList<>();
        List<KuaishouSupplyChain> rocketSupplyChains = new ArrayList<>();
        List<KuaishouSupplyChain> yufuSupplyChains = new ArrayList<>();
        List<KuaishouSupplyChain> yuxiuSupplyChains = new ArrayList<>();
        List<KuaishouSupplyChain> zhiShuiSupplyChains = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            JSONObject jsonObject = list.getJSONObject(i);
            KuaishouSupplyChain supplyChain = new KuaishouSupplyChain();
            supplyChain.setRegimentalId(regimentalId);
            supplyChain.setOid(jsonObject.getLong("oid"));
            JSONObject item = jsonObject.getJSONArray("itemList").getJSONObject(0);
            Long itemId = null;
            if (!Check.isNull(item)) {
                itemId = item.getLong("itemId");
                supplyChain.setItemId(item.getLong("itemId"));
                supplyChain.setItemTitle(item.getString("itemTitle"));
                supplyChain.setReservePrice(item.getLong("reservePrice"));
                supplyChain.setImageUrl(item.getString("imageUrl"));
            }
            supplyChain.setOrderStatus(jsonObject.getInteger("orderStatus"));
            supplyChain.setOrderCreateTime(jsonObject.getLong("orderCreateTime"));
            supplyChain.setSendStatus(jsonObject.getInteger("sendStatus"));
            supplyChain.setSettlementBizType(jsonObject.getInteger("settlementBizType"));
            supplyChain.setSettlementBizTypeDesc(jsonObject.getString("settlementBizTypeDesc"));
            supplyChain.setSendTime(jsonObject.getLong("sendTime"));
            supplyChain.setRecvTime(jsonObject.getLong("recvTime"));
            supplyChain.setSellerId(jsonObject.getLong("sellerId"));
            supplyChain.setPromoterId(jsonObject.getLong("promoterId"));
            supplyChain.setPromoterNickName(filterSupplement(jsonObject.getString("promoterNickName")));
            supplyChain.setActivityId(jsonObject.getLong("activityId"));
            supplyChain.setOrderAmount(jsonObject.getLong("orderAmount"));
            supplyChain.setPayAmount(jsonObject.getLong("payAmount"));
            supplyChain.setRegimentalPromotionRate(jsonObject.getLong("regimentalPromotionRate"));
            supplyChain.setShareRate(jsonObject.getLong("shareRate"));
            supplyChain.setBaseAmount(jsonObject.getLong("baseAmount"));
            supplyChain.setServiceAmount(jsonObject.getLong("serviceAmount"));
            supplyChain.setRegimentalPromotionAmount(jsonObject.getLong("regimentalPromotionAmount"));
            supplyChain.setTotalRegimentalSettleAmount(jsonObject.getLong("totalRegimentalSettleAmount"));
            supplyChain.setStatDate(DateUtils.tempToDateLong(jsonObject.getLong("orderCreateTime")));
            supplyChain.setStatHour(DateUtils.getHour(jsonObject.getLong("orderCreateTime")));
            Criteria criteria = new Criteria();
            criteria = Criteria.where("_id").is(itemId);
            Query query = new Query(criteria);
            ItemCheck itemCheck = mongoTemplate.findOne(query, ItemCheck.class);
            if (Check.isNull(itemCheck)) {
                ruixuanSupplyChains.add(supplyChain);
            }
            if (!Check.isNull(itemCheck)) {
                String ownership = itemCheck.getOwnership();
                if ("ruixuan".equals(ownership)) {
                    ruixuanSupplyChains.add(supplyChain);
                }
                if ("miaogousi".equals(ownership)) {
                    mgsSupplyChains.add(supplyChain);
                }
                if ("rocket".equals(ownership)) {
                    rocketSupplyChains.add(supplyChain);
                }
                if ("yufu".equals(ownership)) {
                    yufuSupplyChains.add(supplyChain);
                }
                if ("yuxiu".equals(ownership)) {
                    yuxiuSupplyChains.add(supplyChain);
                }

                if ("zhishui".equals(ownership)) {
                    zhiShuiSupplyChains.add(supplyChain);
                }


            }

        }
        try {
            if (!Check.isNull(ruixuanSupplyChains)) {
                supplyChainMapper.replaceRuixuanSupplyChains(ruixuanSupplyChains);
            }

            if (!Check.isNull(mgsSupplyChains)) {
                supplyChainMapper.replaceMgsSupplyChains(mgsSupplyChains);
            }

            if (!Check.isNull(rocketSupplyChains)) {
                supplyChainMapper.replaceRocketSupplyChains(rocketSupplyChains);
            }

            if (!Check.isNull(yufuSupplyChains)) {
                supplyChainMapper.replaceYufuSupplyChains(yufuSupplyChains);
            }

            if (!Check.isNull(yuxiuSupplyChains)) {
                supplyChainMapper.replaceYuXiuSupplyChains(yuxiuSupplyChains);
            }

            if (!Check.isNull(zhiShuiSupplyChains)) {
                supplyChainMapper.replaceZhiShuiSupplyChains(zhiShuiSupplyChains);
            }


        } catch (Exception e) {
            e.printStackTrace();
        }

        if (list.size() >= 100) {
            getOrderList(cookie, offset + 100, orderCreateTimeStart, orderCreateTimeEnd, regimentalId);
        }

    }


    @Override
    public void getCcrInfo(String cookie, Integer offset, String type, String activityKeyWord) throws InterruptedException {
        Thread.sleep(3000);
        Map<String, Object> params = new HashMap<>();
        params.put("filters", "{}");
        params.put("sorter", "{}");
        params.put("baseOrderStatus", 0);
        params.put("limit", 20);
        params.put("activityKeyWord", activityKeyWord);
        params.put("offset", offset);
        Map<String, String> headers = new HashMap<>();
        headers.put("Cookie", cookie);

        String resultStr = HttpUtils.httpPostFormRequest("https://cps.kwaixiaodian.com/gateway/distribute/platform/investment/activity/queryCrossActivityItem", params, headers);
        JSONObject result = JSONObject.parseObject(resultStr);
        Integer result1 = result.getInteger("result");
        if (result1 == 1) {
            List<JSONObject> adds = new ArrayList<>();
            if (!Check.isNull(result)) {
                JSONObject data = result.getJSONObject("data");
                if (!Check.isNull(data)) {
                    JSONArray activityItem = data.getJSONArray("activityItem");
                    if (!Check.isNull(activityItem)) {
                        for (int i = 0; i < activityItem.size(); i++) {
                            JSONObject jsonObject = activityItem.getJSONObject(i);
                            if (!Check.isNull(jsonObject)) {
                                Long itemId = jsonObject.getLong("itemId");
                                JSONObject ccrInfo = jsonObject.getJSONObject("ccrInfo");
                                if (!Check.isNull(ccrInfo)) {
                                    JSONObject addJSon = new JSONObject();
                                    String ccrValue = ccrInfo.getString("ccrValue");
                                    addJSon.put("itemId", itemId);
                                    addJSon.put("ccrValue", ccrValue);
                                    adds.add(addJSon);
                                } else {
                                    log.info("ccr数据为空，团：{},itemId:{}", type, itemId);
                                }
                            }
                        }
                    }
                }

            }
            if (!Check.isNull(adds)) {
                if ("ruixuan".equals(type)) {
                    supplyChainMapper.replaceRuiXuanCcr(adds);
                }
                if ("miaogousi".equals(type)) {
                    supplyChainMapper.replaceMiaoGouSICcr(adds);
                }
                if ("rocket".equals(type)) {
                    supplyChainMapper.replaceRocketCcr(adds);
                }

                if ("yufu".equals(type)) {
                    supplyChainMapper.replaceYUfuCcr(adds);
                }

                if (adds.size() >= 20) {
                    getCcrInfo(cookie, offset + 20, type, activityKeyWord);
                }
            }
        } else {
            log.error("{},获取ccr数据异常,返回数据： {}", type, result);
            sendMessageService.sendMessage("113dee46c7df464da78c07a985e92cd1", type + "获取ccr数据失败，返回数据：" + resultStr);
        }


    }

    @Override
    public List<JSONObject> getMgsCookie() {
        return supplyChainMapper.getMgsCookie();
    }

    @Override
    public List<JSONObject> getRocketCookie() {
        return supplyChainMapper.getRocketCookie();
    }

    @Override
    public List<JSONObject> getYuFuCiikie() {
        return supplyChainMapper.getYuFuCiikie();
    }

    @Override
    public List<JSONObject> getYufuDataList(Long statDate) {
        return supplyChainMapper.getYufuDataList(statDate);
    }

    @Override
    public void deleteYufuPromoterBindChannelByDate(Long date) {
        supplyChainMapper.deleteYufuPromoterBindChannelByDate(date);
    }

    @Override
    public void cleanYufuKuaiShouPromoterBindChannel(Long date) {
        supplyChainMapper.cleanYufuKuaiShouPromoterBindChannel(date);
    }

    @Override
    public List<String> getActivityKeyWord(String yesDate, String db) {
        return supplyChainMapper.getActivityKeyWord(yesDate, db);
    }

    @Override
    public void getSellerInfo(String cookie, Integer offset, String db, String date) throws InterruptedException {
        Thread.sleep(2000);
        Map<String, Object> params = new HashMap<>();
        params.put("startDate", date);
        params.put("endDate", date);
        params.put("limit", 20);
        params.put("offset", offset);
        Map<String, String> headers = new HashMap<>();
        headers.put("Cookie", cookie);

        String resultStr = HttpUtils.httpGet("https://cps.kwaixiaodian.com/distribute/pc/investment/dashboard/seller/detail", params, headers);
        JSONObject result = JSONObject.parseObject(resultStr);
        Integer result1 = result.getInteger("result");
        if (result1 == 1) {
            List<JSONObject> adds = new ArrayList<>();
            if (!Check.isNull(result)) {
                JSONObject data = result.getJSONObject("data");
                if (!Check.isNull(data)) {
                    JSONArray dataArray = data.getJSONArray("data");
                    if (!Check.isNull(dataArray)) {
                        for (int i = 0; i < dataArray.size(); i++) {
                            JSONObject dateJson = dataArray.getJSONObject(i);
                            Long sellerId = dateJson.getLong("id");
                            String sellerName = dateJson.getString("name");
                            JSONObject addJson = new JSONObject();
                            addJson.put("sellerId", sellerId);
                            addJson.put("sellerName", sellerName);
                            adds.add(addJson);
                        }

                    }


                }

            }
            if (!Check.isNull(adds)) {
                if ("ruixuan".equals(db)) {
                    supplyChainMapper.replaceRuiXuanSellerInfo(adds);
                }
                if ("miaogousi".equals(db)) {
                    supplyChainMapper.replaceMiaogousiSellerInfo(adds);
                }
                if ("rocket".equals(db)) {
                    supplyChainMapper.replaceRocketSellerInfo(adds);
                }

                if ("yufu".equals(db)) {
                    supplyChainMapper.replaceYUfuSellerInfo(adds);
                }

                if ("yuxiu".equals(db)) {
                    supplyChainMapper.replaceYuXiuSellerInfo(adds);
                }
                if ("zhishui".equals(db)) {
                    supplyChainMapper.replaceZhishuiSellerInfo(adds);
                }


                if (adds.size() >= 20) {
                    getSellerInfo(cookie, offset + 20, db, date);
                }
            }
        } else {
            log.error("{},获取商铺数据异常,返回数据： {}", db, result);
            sendMessageService.sendMessage("113dee46c7df464da78c07a985e92cd1", db + "获取ccr数据失败，返回数据：" + resultStr);
        }
    }

    @Override
    public void deleteItemBindCourtshipByDate(Long date) {
        supplyChainMapper.deleteItemBindCourtshipByDate(date);
    }

    @Override
    public void cleanKuaiShouItemBindCourtship(Long date) {
        supplyChainMapper.cleanKuaiShouItemBindCourtship(date);
    }

    @Override
    public void cleanBytedanceItemBindCourtship(Long date) {
        supplyChainMapper.cleanBytedanceItemBindCourtship(date);
    }

    @Override
    public void deleteMgsItemBindCourtshipByDate(Long date) {
        supplyChainMapper.deleteMgsItemBindCourtshipByDate(date);
    }

    @Override
    public void cleanMgsItemBindCourtship(Long date) {
        supplyChainMapper.cleanMgsItemBindCourtship(date);
    }

    @Override
    public void deleteRocketItemBindCourtshipByDate(Long date) {
        supplyChainMapper.deleteRocketItemBindCourtshipByDate(date);
    }

    @Override
    public void cleanRocketItemBindCourtship(Long date) {
        supplyChainMapper.cleanRocketItemBindCourtship(date);
    }

    @Override
    public void deleteYufuItemBindCourtshipByDate(Long date) {
        supplyChainMapper.deleteYufuItemBindCourtshipByDate(date);
    }

    @Override
    public void cleanYufuItemBindCourtship(Long date) {
        supplyChainMapper.cleanYufuItemBindCourtship(date);
    }

    @Override
    public void deleteYuXiuPromoterBindChannelByDate(Long date) {
        supplyChainMapper.deleteYuXiuPromoterBindChannelByDate(date);
    }

    @Override
    public void cleanYuXiuKuaiShouPromoterBindChannel(Long date) {
        supplyChainMapper.cleanYuXiuKuaiShouPromoterBindChannel(date);
    }

    @Override
    public void deleteYuXiuItemBindCourtshipByDate(Long date) {
        supplyChainMapper.deleteYuXiuItemBindCourtshipByDate(date);
    }

    @Override
    public void cleanYuXiuItemBindCourtship(Long date) {
        supplyChainMapper.cleanYuXiuItemBindCourtship(date);
    }

    @Override
    public void deleteZhiShuiPromoterBindChannelByDate(Long date) {
        supplyChainMapper.deleteZhiShuiPromoterBindChannelByDate(date);
    }

    @Override
    public void cleanZhiShuiKuaiShouPromoterBindChannel(Long date) {
        supplyChainMapper.cleanZhiShuiKuaiShouPromoterBindChannel(date);
    }

    @Override
    public void deleteZhiShuiItemBindCourtshipByDate(Long date) {
        supplyChainMapper.deleteZhiShuiItemBindCourtshipByDate(date);
    }

    @Override
    public void cleanZhiShuiItemBindCourtship(Long date) {
        supplyChainMapper.cleanZhiShuiItemBindCourtship(date);
    }

    @Override
    public List<JSONObject> getZhiShuiCiikie() {
        return supplyChainMapper.getZhiShuiCiikie();
    }

    @Override
    public List<JSONObject> getyuxiuCiikie() {
        return supplyChainMapper.getyuxiuCiikie();
    }


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


    @Override
    public List<JSONObject> getDataList(Long statDate) {
        return supplyChainMapper.getDataList(statDate);
    }

    @Override
    public List<JSONObject> getPromoterDataList(Long statDate) {
        return supplyChainMapper.getPromoterDataList(statDate);
    }

    @Override
    public void deletePromoterBindChannelByDate(Long date) {
        supplyChainMapper.deletePromoterBindChannelByDate(date);
    }

    @Override
    public void cleanKuaiShouPromoterBindChannel(Long date) {
        supplyChainMapper.cleanKuaiShouPromoterBindChannel(date);
    }

    @Override
    public List<JSONObject> getSamplesData(String startDate) {
        return supplyChainMapper.getSamplesData(startDate);
    }

    @Override
    public void cleanBytedancePromoterBindChannel(Long date) {
        supplyChainMapper.cleanBytedancePromoterBindChannel(date);
    }

    @Override
    public void deleteMgsPromoterBindChannelByDate(Long date) {
        supplyChainMapper.deleteMgsPromoterBindChannelByDate(date);
    }

    @Override
    public void cleanMgsKuaiShouPromoterBindChannel(Long date) {
        supplyChainMapper.cleanMgsKuaiShouPromoterBindChannel(date);
    }

    @Override
    public List<JSONObject> getMgsDataList(Long statDate) {
        return supplyChainMapper.getMgsDataList(statDate);
    }


    @Override
    public List<JSONObject> getRocketDataList(Long statDate) {
        return supplyChainMapper.getRocketDataList(statDate);
    }


    @Override
    public void deleteRocketPromoterBindChannelByDate(Long date) {
        supplyChainMapper.deleteRocketPromoterBindChannelByDate(date);
    }

    @Override
    public void cleanRocketKuaiShouPromoterBindChannel(Long date) {
        supplyChainMapper.cleanRocketKuaiShouPromoterBindChannel(date);
    }


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

}



