package com.ruixuan.isc.service.impl;


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

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.kuaishou.merchant.open.api.KsMerchantApiException;
import com.kuaishou.merchant.open.api.client.AccessTokenKsMerchantClient;
import com.kuaishou.merchant.open.api.common.utils.GsonUtils;
import com.kuaishou.merchant.open.api.request.distribution.OpenDistributionInvestmentActivityItemDetailRequest;
import com.kuaishou.merchant.open.api.request.distribution.OpenDistributionPublicCategoryListRequest;
import com.kuaishou.merchant.open.api.response.distribution.OpenDistributionInvestmentActivityItemDetailResponse;
import com.kuaishou.merchant.open.api.response.distribution.OpenDistributionPublicCategoryListResponse;
import com.ruixuan.common.utils.Check;
import com.ruixuan.common.utils.KsHttpUtils;
import com.ruixuan.isc.constants.KuaiShouConstants;
import com.ruixuan.isc.entity.KuaishouAccessToken;
import com.ruixuan.isc.entity.KuaishouItemList;
import com.ruixuan.isc.entity.KuaishouItemCategory;
import com.ruixuan.isc.mapper.KuaishouItemListMapper;
import com.ruixuan.isc.mapper.SupplyChainMapper;
import com.ruixuan.isc.service.IKuaishouItemListService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * 【请填写功能名称】Service业务层处理
 *
 * @author ruoyi
 * @date 2023-02-03
 */
@Service
@Slf4j
public class KuaishouItemListServiceImpl implements IKuaishouItemListService {
    @Autowired
    private KuaishouItemListMapper kuaishouItemListMapper;
    private static List<JSONObject> categoryIds;
    @Autowired
    private SupplyChainMapper supplyChainMapper;


    @Override
    public List<KuaishouItemList> getItemList(Map<String, Object> requestMap) {
        List<KuaishouItemList> itemList = kuaishouItemListMapper.getItemList(requestMap);
        Map<Long, JSONObject> dataMap = new HashMap<>();
        if (!Check.isNull(itemList)) {
            Map<Long, Long> map = new HashMap<>();
            for (KuaishouItemList item : itemList) {
                map.put(item.getItemId(), item.getItemId());
            }
            List<JSONObject> itemInfoList = kuaishouItemListMapper.selectItemInfo(map);
            for (int i = 0; i < itemInfoList.size(); i++) {
                JSONObject jsonObject = itemInfoList.get(i);
                dataMap.put(jsonObject.getLong("itemId"), jsonObject);
            }
        }
        if (!Check.isNull(itemList)) {
            for (KuaishouItemList item : itemList) {
                Long itemId = item.getItemId();
                JSONObject jsonObject = dataMap.get(itemId);
                if (!Check.isNull(jsonObject)) {
                    item.setValidAmount(jsonObject.getLong("validAmount"));
                    item.setValidOrderNum(jsonObject.getLong("validOrderNum"));
                }
            }
        }
        return itemList;
    }

    @Override
    public JSONObject getItemDetail(Long regId, Long activityId, Long itemId, KuaishouAccessToken accessToken) throws Exception {
        // 调用爬虫信息
        JSONObject invaliItemDetail = getInvaliItemDetail(regId, activityId, itemId);
        JSONObject returnJson = new JSONObject();
        AccessTokenKsMerchantClient client = new AccessTokenKsMerchantClient(KuaiShouConstants.KFX_URL, accessToken.getAppKey(), accessToken.getAppSecret());
        OpenDistributionInvestmentActivityItemDetailRequest request = new OpenDistributionInvestmentActivityItemDetailRequest();
        request.setAccessToken(accessToken.getAccessToken());
        request.setApiMethodVersion(1L);
        request.setActivityId(activityId);
        List<Long> item = new ArrayList<>();
        item.add(itemId);
        request.setItemId(item);
        OpenDistributionInvestmentActivityItemDetailResponse response = client.execute(request);
        JSONObject json = JSONObject.parseObject(GsonUtils.toJSON(response));
        if (Check.isNull(json)) {
            throw new Exception("获取商品信息出错，请重新提交");
        }
        Integer code = json.getInteger("code");
        Integer subCode = json.getInteger("sub_code");
        if (code == 1 && subCode == 1) {
            JSONArray data = json.getJSONArray("data");
            if (Check.isNull(data)) {
                returnJson.put("code", 500);
                returnJson.put("message", "数据查询失败");
                return returnJson;
            }
            JSONObject itemJson = data.getJSONObject(0);
            Long categoryId = itemJson.getLong("categoryId");
            JSONObject categoryInfo = getCategoryInfo(categoryId);
            if (!Check.isNull(categoryInfo)) {
                itemJson.put("categoryName", categoryInfo.getString("categoryName"));
                itemJson.put("categoryId", categoryInfo.getString("categoryId"));
            }
            itemJson.put("detailUrl", "https://app.kwaixiaodian.com/merchant/shop/detail?id=" + itemId);
            if (!Check.isNull(invaliItemDetail)) {
                JSONObject invaliJSon = invaliItemDetail.getJSONObject("itemJson");
                if (!Check.isNull(invaliJSon)) {
                    itemJson.put("postArea", invaliJSon.getString("postArea"));
                    itemJson.put("deliveryRate", invaliJSon.getString("deliveryRate"));
                    itemJson.put("regimentalPromotionRate", invaliJSon.getLong("regimentalPromotionRate"));
                    itemJson.put("commissionRate", invaliJSon.getLong("commissionRate"));
                }
            }
            returnJson.put("judgeStatus", 1);
            returnJson.put("itemJson", itemJson);
            returnJson.put("code", 0);
            returnJson.put("message", "查询成功");
        } else if (code != 1) { // 商品下线
            return invaliItemDetail;
        } else {
            returnJson.put("code", 500);
            returnJson.put("message", "数据查询失败");
        }
        log.info("获取商品信息回，活动ID：{},商品ID：{}，数据：{}", activityId, itemId, returnJson);
        return returnJson;
    }


    private JSONObject getInvaliItemDetail(Long regId, Long activityId, Long itemId) throws Exception {
        JSONObject returnJson = new JSONObject();
        String cookie = supplyChainMapper.getCookie(regId);
        Map<String, Object> params = new HashMap<>();
        params.put("limit", 20);
        params.put("offset", 0);
        params.put("activityId", activityId);
        params.put("itemId", itemId);
        Map<String, String> headers = new HashMap<>();
        headers.put("Cookie", cookie);
        String resultStr = KsHttpUtils.KuaiShouttpGetRequest("https://cps.kwaixiaodian.com/distribute/pc/investment/activity/item/list", params, headers);
        JSONObject result = JSONObject.parseObject(resultStr);
        if (Check.isNull(result)) {
            log.error("快分销招商商品数据返回为空");
            returnJson.put("code", -1);
            returnJson.put("message", "获取商品信息为空");
            return returnJson;
        }
        Integer code = result.getInteger("result");
        if (code != 1) {
            log.info("快分销招商商品数据返回异常：", resultStr);
            returnJson.put("code", -1);
            returnJson.put("message", "增加快手商品信息抓取失败，请联系技术人员");
            return returnJson;
        }
        JSONArray dataArray = result.getJSONArray("data");
        if (Check.isNull(dataArray)) {
            log.error("快分销招商商品数据返回为data数据为空");
            returnJson.put("code", -1);
            returnJson.put("message", "快分销招商商品数据返回为data数据为空");
            return returnJson;
        }
        JSONObject itemJson = dataArray.getJSONObject(0);
        itemJson.put("detailUrl", "https://app.kwaixiaodian.com/merchant/shop/detail?id=" + itemId);
        String itemCategoryName = itemJson.getString("itemCategoryName");
        if (!Check.isNull(itemCategoryName)) {
            String[] split = itemCategoryName.split(">");
            if (!Check.isNull(split)) {
                String categoryName = split[0];
                Long categoryId = kuaishouItemListMapper.getIdByName(categoryName);
                if (!Check.isNull(categoryId)) {
                    itemJson.put("categoryId", categoryId);
                }
            }
        }
        itemJson.put("commissionRate", itemJson.getLong("itemCommissionRate"));
        itemJson.put("regimentalPromotionRate", itemJson.getLong("investmentPromotionRate"));
        JSONObject otherInfo = getOtherInfo(itemId, cookie);
        if (!Check.isNull(otherInfo)) {
            itemJson.put("postArea", otherInfo.getString("postArea"));
            itemJson.put("deliveryRate", otherInfo.getString("deliveryRate"));
            itemJson.put("itemDescUrls", otherInfo.getJSONArray("itemDescUrls"));
            itemJson.put("itemGalleryUrls", otherInfo.getJSONArray("itemGalleryUrls"));
        }
        returnJson.put("judgeStatus", 2);
        returnJson.put("itemJson", itemJson);
        returnJson.put("code", 0);
        returnJson.put("message", "查询成功");
        return returnJson;
    }


    private JSONObject getOtherInfo(Long itemId, String cookie) throws Exception {
        JSONObject returnJson = new JSONObject();
        Map<String, Object> params = new HashMap<>();
        params.put("itemId", itemId);
        Map<String, String> headers = new HashMap<>();
        headers.put("Cookie", cookie);
        String resultStr = KsHttpUtils.KuaiShouttpGetRequest("https://app.kwaixiaodian.com/rest/app/grocery/product/self/detail", params, headers);
        JSONObject result = JSONObject.parseObject(resultStr);
        if (!Check.isNull(result)) {
            JSONObject productDetail = result.getJSONObject("productDetail");
            if (!Check.isNull(productDetail)) {
                JSONObject expressTemplate = productDetail.getJSONObject("expressTemplate");
                if (!Check.isNull(expressTemplate)) {
                    String sendProvinceName = expressTemplate.getString("sendProvinceName");
                    String sendCityName = expressTemplate.getString("sendCityName");
                    if (Check.isNull(sendCityName)) {
                        returnJson.put("postArea", sendProvinceName);
                    } else {
                        returnJson.put("postArea", sendProvinceName + "-" + sendCityName);
                    }
                }
                JSONObject expressInfo = productDetail.getJSONObject("expressInfo");
                if (!Check.isNull(expressInfo)) {
                    String deliveryDesc = expressInfo.getString("deliveryDesc");
                    returnJson.put("deliveryRate", deliveryDesc);
                }
                // itemDescUrls 商品详情图
                JSONArray itemDescUrls = productDetail.getJSONArray("detailImageUrls");
                if (!Check.isNull(itemDescUrls)) {
                    returnJson.put("itemDescUrls", itemDescUrls);
                }
                // 轮播图
                JSONArray itemGalleryUrls = productDetail.getJSONArray("imageUrls");
                if (!Check.isNull(itemGalleryUrls)) {
                    returnJson.put("itemGalleryUrls", itemGalleryUrls);
                }
            }
        }
        return returnJson;
    }

    private JSONObject getCategoryInfo(Long categoryId) {
        if (Check.isNull(categoryId)) {
            return null;
        }
        JSONObject returnJson = new JSONObject();
        StringBuffer stringBuffer = new StringBuffer();
        KuaishouItemCategory category = kuaishouItemListMapper.getCategoryInfo(categoryId);
        if (Check.isNull(category)) {
            return null;
        }
        KuaishouItemCategory secondCategory = new KuaishouItemCategory();
        KuaishouItemCategory thirdCategory = new KuaishouItemCategory();
        KuaishouItemCategory fourthCategory = new KuaishouItemCategory();
        Long id = null;
        if (category.getCategorySort() == 1) {
            id = categoryId;
            stringBuffer.append(category.getCategoryName());
        } else if (category.getCategorySort() == 2) {
            secondCategory = kuaishouItemListMapper.getCategoryInfo(category.getParentId());
            stringBuffer.append(secondCategory.getCategoryName()).append(">").append(category.getCategoryName());
            id = secondCategory.getCategoryId();
        } else if (category.getCategorySort() == 3) {
            secondCategory = kuaishouItemListMapper.getCategoryInfo(category.getParentId());
            thirdCategory = kuaishouItemListMapper.getCategoryInfo(secondCategory.getParentId());
            stringBuffer.append(thirdCategory.getCategoryName()).append(">").append(secondCategory.getCategoryName()).append(">").append(category.getCategoryName());
            id = thirdCategory.getCategoryId();
        } else if (category.getCategorySort() == 4) {
            secondCategory = kuaishouItemListMapper.getCategoryInfo(category.getParentId());
            thirdCategory = kuaishouItemListMapper.getCategoryInfo(secondCategory.getParentId());
            fourthCategory = kuaishouItemListMapper.getCategoryInfo(thirdCategory.getParentId());
            stringBuffer.append(fourthCategory.getCategoryName()).append(">").append(thirdCategory.getCategoryName()).append(">").append(secondCategory.getCategoryName()).append(">").append(category.getCategoryName());
            id = fourthCategory.getCategoryId();
        }

        returnJson.put("categoryName", stringBuffer.toString());
        returnJson.put("categoryId", id);
        return returnJson;


    }

    @Override
    public KuaishouItemList getItemInfoByItemId(Long itemId) {
        return kuaishouItemListMapper.getItemInfoByItemId(itemId);
    }

    @Override
    public void insertItem(KuaishouItemList kuaishouItemList) {
        Long relateId = kuaishouItemListMapper.selectMaxRelateId();
        kuaishouItemList.setRelateId(relateId + 1);
        kuaishouItemListMapper.insertItem(kuaishouItemList);
        kuaishouItemListMapper.insertItemBindUser(kuaishouItemList.getItemId(), kuaishouItemList.getUserId(), kuaishouItemList.getUserName());
    }

    @Override
    public int updateKuaishouItemList(KuaishouItemList kuaishouItemList) {
        return kuaishouItemListMapper.updateKuaishouItemList(kuaishouItemList);
    }

    @Override
    public int deleteKuaishouItemListByItemIds(Long[] itemIds) {
        return kuaishouItemListMapper.deleteKuaishouItemListByItemIds(itemIds);
    }

    @Override
    public int addCategoryId() throws KsMerchantApiException {
        String url = "https://openapi.kwaixiaodian.com";
        String appKey = "ks665688320292774929";
        String signSecret = "8e21f5bc03b6d2dc63e6256225dac00b";
        String accessToken = "ChFvYXV0aC5hY2Nlc3NUb2tlbhJgT28Jn3uMkkU0sSjL_30Jd2X6QCz4B2bs9IsMrIJe1S3J4PhjkaBYIU13FGpBlmy73rx7X-cyNUuuOxKeOloFQeQFZ2Ka8jm_HwDYtqoaoVVm-Y06ILVaPrfs6SjVB84QGhL_b_zNSCZFGYoK2F52yMh0D74iILO5AYTiyqLP-3W1aZ-dql11qIkyhjgvYLXyoNplPgoNKAUwAQ";
        AccessTokenKsMerchantClient client = new AccessTokenKsMerchantClient(url, appKey, signSecret);
        OpenDistributionPublicCategoryListRequest request = new OpenDistributionPublicCategoryListRequest();
        request.setAccessToken(accessToken);
        request.setApiMethodVersion(1L);
        OpenDistributionPublicCategoryListResponse response = client.execute(request);
        JSONObject jsonObject = JSONObject.parseObject(GsonUtils.toJSON(response));
        JSONArray data = jsonObject.getJSONArray("data");
        List<KuaishouItemCategory> adds = new ArrayList<>();

        for (int i = 0; i < data.size(); i++) {
            JSONObject first = data.getJSONObject(i);
            KuaishouItemCategory firstCategory = new KuaishouItemCategory();
            firstCategory.setCategoryId(first.getLong("categoryId"));
            firstCategory.setCategoryName(first.getString("categoryName"));
            firstCategory.setCategorySort(1);
            firstCategory.setParentId(1L);
            Long firstCategoryId = first.getLong("categoryId");
            adds.add(firstCategory);
            JSONArray secondChildCategory = first.getJSONArray("childCategory");
            if (!Check.isNull(secondChildCategory)) {
                for (int j = 0; j < secondChildCategory.size(); j++) {
                    JSONObject second = secondChildCategory.getJSONObject(j);
                    KuaishouItemCategory secondCategory = new KuaishouItemCategory();
                    secondCategory.setParentId(firstCategoryId);
                    secondCategory.setCategoryId(second.getLong("categoryId"));
                    secondCategory.setCategoryName(second.getString("categoryName"));
                    secondCategory.setCategorySort(2);
                    Long secondCategoryId = second.getLong("categoryId");
                    adds.add(secondCategory);
                    JSONArray thirdChildCategory = second.getJSONArray("childCategory");
                    if (!Check.isNull(thirdChildCategory)) {
                        for (int k = 0; k < thirdChildCategory.size(); k++) {
                            JSONObject third = thirdChildCategory.getJSONObject(k);
                            KuaishouItemCategory thirdCategory = new KuaishouItemCategory();
                            thirdCategory.setParentId(secondCategoryId);
                            thirdCategory.setCategoryId(third.getLong("categoryId"));
                            thirdCategory.setCategoryName(third.getString("categoryName"));
                            thirdCategory.setCategorySort(3);
                            Long thirdCategoryId = third.getLong("categoryId");
                            adds.add(thirdCategory);
                            JSONArray fourthChildCategory = third.getJSONArray("childCategory ");
                            if (!Check.isNull(fourthChildCategory)) {
                                for (int l = 0; l < fourthChildCategory.size(); l++) {
                                    JSONObject fourth = fourthChildCategory.getJSONObject(l);
                                    KuaishouItemCategory fourthCategory = new KuaishouItemCategory();
                                    fourthCategory.setParentId(thirdCategoryId);
                                    fourthCategory.setCategoryId(fourth.getLong("categoryId"));
                                    fourthCategory.setCategoryName(fourth.getString("categoryName"));
                                    fourthCategory.setCategorySort(4);
                                    adds.add(fourthCategory);
                                }
                            }
                        }
                    }
                }

            }


        }
        kuaishouItemListMapper.batchCategory(adds);
        System.err.println(jsonObject);
        return 0;
    }

    @Override
    public List<JSONObject> getCategoryIds() {
        if (Check.isNull(categoryIds)) {
            categoryIds = kuaishouItemListMapper.getCategoryIds();
        }
        return categoryIds;
    }

    @Override
    public void updateCount(Long itemId, Integer sampleCount, Integer userCount) {
        kuaishouItemListMapper.updateCount(itemId, sampleCount, userCount);
    }

    @Override
    public List<Long> getActivityIds(Long userId) {
        return kuaishouItemListMapper.getActivityIds(userId);
    }

    @Override
    public Integer getSampleCount(Long itemId) {
        return kuaishouItemListMapper.getSampleCount(itemId);
    }

    @Override
    public void removeById(Long itemId) {
        kuaishouItemListMapper.removeById(itemId);
    }

    @Override
    public void batchItemProcess(JSONArray itemIds, Integer status, Long examineId, String examineName) {
        kuaishouItemListMapper.batchItemProcess(itemIds, status, examineId, examineName);
    }

    @Override
    public List<JSONObject> getRegimental() {
        return kuaishouItemListMapper.getRegimental();
    }

    @Override
    public List<JSONObject> getListByRelateId(Long relateId) {
        return kuaishouItemListMapper.getListByRelateId(relateId);
    }

    @Override
    public Long selectMaxRelateId() {
        return kuaishouItemListMapper.selectMaxRelateId();
    }


}

