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.controller.KuaiShouActivityItemList;
import cn.com.ctop.kuaishou.modules.batch.entity.KuaiShouActivityInfo;
import cn.com.ctop.kuaishou.modules.batch.mapper.KuaiShouActivityItemListMapper;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaiShouActivityItemListService;
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.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

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

/**
 * 快分销-招商商品列表
 *
 * @author jeecg-boot
 * 2023-01-10
 * @version V1.0
 */
@Slf4j
@Service
public class KuaiShouActivityItemListServiceImpl extends ServiceImpl<KuaiShouActivityItemListMapper, KuaiShouActivityItemList> implements IKuaiShouActivityItemListService {
    private static String orderUrl = "https://cps.kwaixiaodian.com/distribute/pc/investment/activity/item/list";
    @Autowired
    private ISendMessageService sendMessageService;
    @Autowired
    private KuaiShouActivityItemListMapper activityItemListMapper;

    @Override
    public void getActivityItemList(String cookie, Integer offset, Long activityId, Integer activityStatus, Map<Long, Integer> itemMap) throws Exception {
        Map<String, Object> params = new HashMap<>();
        params.put("limit", 1000);
        params.put("offset", offset);
        params.put("activityId", activityId);

        Map<String, String> headers = new HashMap<>();
        headers.put("Cookie", cookie);
        String resultStr = HttpUtils.KuaiShouttpGetRequest(orderUrl, 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;
        }
        JSONArray dataArray = result.getJSONArray("data");
        if (Check.isNull(dataArray)) {
            log.error("快分销招商商品数据返回为data数据为空");
            return;
        }
        List<KuaiShouActivityItemList> activityInfoList = new ArrayList<>();
        for (int i = 0; i < dataArray.size(); i++) {
            JSONObject jsonObject = dataArray.getJSONObject(i);
            KuaiShouActivityItemList item = new KuaiShouActivityItemList();
            Long itemId = jsonObject.getLong("itemId");
            item.setItemId(itemId);
            item.setItemTitle(jsonObject.getString("itemTitle"));
            item.setItemImgUrl(jsonObject.getString("itemImgUrl"));
            item.setItemLinkUrl(jsonObject.getString("itemLinkUrl"));
            item.setItemStock(jsonObject.getLong("itemStock"));
            item.setItemVolume(jsonObject.getString("itemVolume"));
            item.setItemPrice(jsonObject.getLong("itemPrice"));
            item.setItemCategoryName(jsonObject.getString("itemCategoryName"));
            item.setItemLeafCategoryName(jsonObject.getString("itemLeafCategoryName"));
            item.setItemCommissionRate(jsonObject.getLong("itemCommissionRate"));
            item.setInvestmentPromotionRate(jsonObject.getLong("investmentPromotionRate"));
            item.setItemApplyTime(DateUtils.temp13ToDate(jsonObject.getLong("itemApplyTime")));
            item.setItemAuditStatus(jsonObject.getInteger("itemAuditStatus"));
            item.setSellerNickName(filterSupplement(jsonObject.getString("sellerNickName")));
            item.setReason(jsonObject.getString("reason"));
            item.setSellerId(jsonObject.getLong("sellerId"));
            JSONArray contactList = jsonObject.getJSONArray("contactList");
            if (!Check.isNull(contactList)) {
                JSONObject contacJson = contactList.getJSONObject(0);
                item.setContactId(contacJson.getLong("contactId"));
                item.setContactName(contacJson.getString("contactName"));
                item.setContactType(contacJson.getString("contactType"));
                item.setContactStatus(contacJson.getInteger("contactStatus"));
                item.setContactDetail(contacJson.getLong("contactDetail"));
                item.setContactCreateTime(DateUtils.temp13ToDate(contacJson.getLong("createTime")));
                item.setContactUpdateTime(DateUtils.temp13ToDate(contacJson.getLong("updateTime")));
            }

            Integer itemStatus = jsonObject.getInteger("itemStatus");
            Integer itemAuditStatus = jsonObject.getInteger("itemAuditStatus"); // 5 失效
            item.setItemStatus(itemStatus);
            item.setActivityShowContactTypeList(jsonObject.getString("activityShowContactTypeList"));
            item.setIdentity(jsonObject.getInteger("identity"));
            item.setCooperationBeginTime(DateUtils.temp13ToDate(jsonObject.getLong("cooperationBeginTime")));
            item.setCooperationEndTime(DateUtils.temp13ToDate(jsonObject.getLong("cooperationEndTime")));
            item.setShareLink(jsonObject.getString("shareLink"));
            item.setCooperationStatus(jsonObject.getInteger("cooperationStatus"));
            item.setActivityId(jsonObject.getLong("activityId"));
            item.setPreActivityId(jsonObject.getLong("preActivityId"));
            item.setInvestmentRemiseRate(jsonObject.getLong("investmentRemiseRate"));
            item.setApplyAuthStatus(jsonObject.getInteger("applyAuthStatus"));
            item.setActivityType(jsonObject.getInteger("activityType"));
            item.setSampleApplyType(jsonObject.getString("sampleApplyType"));
            if (activityStatus == 4) { // 招商活动结束
                Integer status = itemMap.get(itemId);
                if (!Check.isNull(status)) {
                    if (status != 4) {
                        if (itemId != 21003732814123L && itemId != 21586733492341L) {
                            activityItemListMapper.updateItemStatusByItem(itemId, 4); // 招商活动失效，修改商品状态为活动结束

                        }
                    }
                }

            } else if (activityStatus == 3) { // 招商活动正常
                Integer status = itemMap.get(itemId);
                if (!Check.isNull(status)) { // 0 下架 1在售
                    if (itemStatus == 0 || itemAuditStatus == 5) {
                        if (itemId != 21003732814123L && itemId != 21586733492341L) {
                            activityItemListMapper.updateItemStatusByItem(itemId, 5); // 商品失效
                        }
                    } else {
                        activityItemListMapper.updateItemStatusByItem(itemId, 2); // 商品在售
                    }
                }
            }
            activityInfoList.add(item);
        }
        if (!Check.isNull(activityInfoList)) {
            activityItemListMapper.replace(activityInfoList);
        }
        log.info("快分销招商商品数据更新数量:{}", activityInfoList.size());
        if (dataArray.size() >= 1000) {
            getActivityItemList(cookie, offset + 1000, activityId, activityStatus, itemMap);
        }
    }

    @Override
    public Map<Long, Long> getItemMap() {
        Map<Long, Long> returnMap = new HashMap<>();
        List<JSONObject> list = activityItemListMapper.itemList();
        if (!Check.isNull(list)) {
            for (int i = 0; i < list.size(); i++) {
                JSONObject jsonObject = list.get(i);
                returnMap.put(jsonObject.getLong("itemId"), jsonObject.getLong("itemCommissionRate"));
            }
        }

        return returnMap;
    }

    @Override
    public Map<Long, Long> getMgsItemList() {
        Map<Long, Long> returnMap = new HashMap<>();
        List<JSONObject> list = activityItemListMapper.getMgsItemList();
        if (!Check.isNull(list)) {
            for (int i = 0; i < list.size(); i++) {
                JSONObject jsonObject = list.get(i);
                returnMap.put(jsonObject.getLong("itemId"), jsonObject.getLong("itemCommissionRate"));
            }
        }

        return returnMap;
    }

    @Override
    public Map<Long, Long> getRocketItemList() {
        Map<Long, Long> returnMap = new HashMap<>();
        List<JSONObject> list = activityItemListMapper.getRocketItemList();
        if (!Check.isNull(list)) {
            for (int i = 0; i < list.size(); i++) {
                JSONObject jsonObject = list.get(i);
                returnMap.put(jsonObject.getLong("itemId"), jsonObject.getLong("itemCommissionRate"));
            }
        }

        return returnMap;
    }

    @Override
    public Map<Long, Long> getYufuItemList() {
        Map<Long, Long> returnMap = new HashMap<>();
        List<JSONObject> list = activityItemListMapper.getYufuItemList();
        if (!Check.isNull(list)) {
            for (int i = 0; i < list.size(); i++) {
                JSONObject jsonObject = list.get(i);
                returnMap.put(jsonObject.getLong("itemId"), jsonObject.getLong("itemCommissionRate"));
            }
        }

        return returnMap;
    }

    @Override
    public Map<Long, Long> getYuXiuItemList() {
        Map<Long, Long> returnMap = new HashMap<>();
        List<JSONObject> list = activityItemListMapper.getYuXiuItemList();
        if (!Check.isNull(list)) {
            for (int i = 0; i < list.size(); i++) {
                JSONObject jsonObject = list.get(i);
                returnMap.put(jsonObject.getLong("itemId"), jsonObject.getLong("itemCommissionRate"));
            }
        }

        return returnMap;
    }

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