package com.liquidnet.service.goblin.util;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.type.TypeReference;
import com.liquidnet.commons.lang.util.CollectionUtil;
import com.liquidnet.commons.lang.util.CurrentUtil;
import com.liquidnet.commons.lang.util.HttpUtil;
import com.liquidnet.commons.lang.util.JsonUtils;
import com.liquidnet.service.base.ResponseDto;
import com.liquidnet.service.base.constant.MQConst;
import com.liquidnet.service.candy.param.BackCouponParam;
import com.liquidnet.service.candy.vo.CandyCouponVo;
import com.liquidnet.service.erp.constant.ErpEnum;
import com.liquidnet.service.erp.param.OrderListParam;
import com.liquidnet.service.erp.param.TradeListParam;
import com.liquidnet.service.goblin.dto.GoblinQueueBizIntegralDto;
import com.liquidnet.service.goblin.dto.vo.GoblinGoodsSkuInfoVo;
import com.liquidnet.service.goblin.dto.vo.GoblinOrderSkuVo;
import com.liquidnet.service.goblin.dto.vo.GoblinStoreOrderVo;
import com.liquidnet.service.goblin.param.GoblinNowOrderListParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class GoblinOrderUtils {

    @Value("${liquidnet.service.candy.url}")
    private String candyUrl;
    @Autowired
    GoblinRedisUtils redisUtils;
    @Autowired
    QueueUtils queueUtils;

    public void backCoupon(String uCouponId, String uid) {
        try {
            BackCouponParam param = BackCouponParam.getNew();
            param.setuCouponIds(uCouponId);
            param.setUid(uid);

            MultiValueMap<String, String> header = CollectionUtil.linkedMultiValueMapStringString();
            header.add("Authorization", "Bearer " + CurrentUtil.getToken());
            header.add("Accept", "application/json;charset=UTF-8");
            ArrayList<BackCouponParam> params = new ArrayList();
            params.add(param);
            String jsonString = JSON.toJSONString(params);
            String returnData = HttpUtil.postRaw(candyUrl + "/candy-coupon/useBack", jsonString, header);
        } catch (Exception e) {
            log.error("回退券ERROR:{}", e);
        }
    }

    public CandyCouponVo getCouponDetails(String uCouponId, String uid) {
        try {
            MultiValueMap<String, String> header = CollectionUtil.linkedMultiValueMapStringString();
            header.add("Authorization", "Bearer " + CurrentUtil.getToken());
            header.add("Accept", "application/json;charset=UTF-8");

            MultiValueMap<String, String> params = CollectionUtil.linkedMultiValueMapStringString();
            params.add("uCouponIds", uCouponId);
            params.add("uid", uid);
            String returnData = HttpUtil.post(candyUrl + " /candy-coupon/receive/ListById", params, header);
            ResponseDto<List<CandyCouponVo>> innerReturnVo = JsonUtils.fromJson(returnData, new TypeReference<ResponseDto<List<CandyCouponVo>>>() {
            });
            if (innerReturnVo.getData().size() > 0) {
                return innerReturnVo.getData().get(0);
            } else {
                return null;
            }
        } catch (Exception e) {
            log.error("回退券ERROR:{}", e);
            CandyCouponVo vo = CandyCouponVo.getNew();
            vo.setUcouponId(uCouponId);
            vo.setTitle("");
            return vo;
        }
    }

    public void integral(String uid, BigDecimal price, String content, int type) {
        if (price.intValue() > 0) {
            GoblinQueueBizIntegralDto goblinQueueBizIntegralDto = GoblinQueueBizIntegralDto.getNew();
            goblinQueueBizIntegralDto.setUid(uid);
            goblinQueueBizIntegralDto.setScore(price);
            goblinQueueBizIntegralDto.setContent(content);
            goblinQueueBizIntegralDto.setType(type);
            queueUtils.sendMsgByRedis(MQConst.GoblinQueue.BIZ_INTEGRAL.getKey(), goblinQueueBizIntegralDto.toJson());
        }
    }

    // NFT判断是否售罄
    public HashMap<String, Integer> getIsStock(String listId, String skuId, String unbox, String soldoutStatus, List<String> skuIdList) {
        HashMap<String, Integer> returnMap = CollectionUtil.mapStringInteger();
        Integer isStock = 0;
        Integer totalStock = 0;
        if (null == soldoutStatus || soldoutStatus.equals("0")) {// 未设置售罄 查询库存
            int surplusStock = 0;
            if (unbox.equals("0")) {// 不是盲盒
                surplusStock = redisUtils.getSkuStock(listId, skuId);
            } else {
                for (String skuIdItem : skuIdList) {// 盲盒计算所有sku库存总数
                    if (skuIdItem.equals(skuId)) {// 过滤自己
                        continue;
                    }
                    HashMap<String, Object> map = redisUtils.getGoodsSkuInfoVo(LocalDateTime.now(), skuIdItem);
                    GoblinGoodsSkuInfoVo itemVo = (GoblinGoodsSkuInfoVo) map.get("vo");
//                    String listId2 = (String) map.get("listId");
//                    surplusStock += redisUtils.getSkuAllStatusStock(itemVo, listId2);
                    surplusStock += redisUtils.getSkuAllStatusStock(itemVo, listId);
                    totalStock += redisUtils.getSkuTotalStock(itemVo);
                }
            }
            if (surplusStock > 0) {
                isStock = 1;
            }
        }
        returnMap.put("isStock", isStock);
        returnMap.put("totalStock", totalStock);
        return returnMap;
    }

    public List<TradeListParam> getErpOrder(String orderId) {
        List<TradeListParam> listOrder = ObjectUtil.tradeListParam();

        TradeListParam tradeListParam = TradeListParam.getNew();
        GoblinStoreOrderVo orderVo = redisUtils.getGoblinOrder(orderId);
        List<String> orderSkuIds = orderVo.getOrderSkuVoIds();
        List<OrderListParam> listOrderSku = ObjectUtil.orderListParam();
        String warehouseNo = "";
        //配置sku维度数据
        for (String orderSkuId : orderSkuIds) {
            OrderListParam orderSkuParam = OrderListParam.getNew();
            GoblinOrderSkuVo orderSkuVo = redisUtils.getGoblinOrderSkuVo(orderSkuId);
            orderSkuParam.setOid(orderSkuVo.getOrderSkuId());
            orderSkuParam.setNum(BigDecimal.valueOf(orderSkuVo.getNum()));
            orderSkuParam.setPrice(orderSkuVo.getSkuPrice());
            orderSkuParam.setStatus(ErpEnum.WdtStatus.STATUS_UN_SEND.WdtStatus());
            orderSkuParam.setRefund_status(0);
            orderSkuParam.setGoods_id(orderSkuVo.getSpuId());
            orderSkuParam.setSpec_id(orderSkuVo.getSkuId());
            orderSkuParam.setGoods_no(orderSkuVo.getSpuErpCode());
            orderSkuParam.setSpec_no(orderSkuVo.getSkuErpCode());
            orderSkuParam.setGoods_name(orderSkuVo.getSpuName());
            orderSkuParam.setAdjust_amount(BigDecimal.ZERO);
            orderSkuParam.setDiscount(BigDecimal.ZERO);
            orderSkuParam.setShare_discount(orderSkuVo.getPriceVoucher());
            warehouseNo = orderSkuVo.getWarehouseNo();
            listOrderSku.add(orderSkuParam);
        }
        //配置订单维度数据
        tradeListParam.setOrder_list(listOrderSku);
        tradeListParam.setTid(orderVo.getOrderCode());
        tradeListParam.setTrade_status(ErpEnum.WdtStatus.STATUS_UN_SEND.WdtStatus());
        tradeListParam.setPay_status(2);
        tradeListParam.setDelivery_term(1);
        tradeListParam.setTrade_time(orderVo.getCreatedAt());
        tradeListParam.setPay_time(orderVo.getPayTime());
        tradeListParam.setBuyer_nick(orderVo.getUserName());
        tradeListParam.setPay_id(orderVo.getPayCode());
        tradeListParam.setReceiver_name(orderVo.getOrderAttrVo().getExpressContacts());
        String[] address = orderVo.getOrderAttrVo().getExpressAddress().split(" ");
        if (address.length > 0) {
            tradeListParam.setReceiver_province(address[0]);
        }
        if (address.length > 1) {
            tradeListParam.setReceiver_city(address[1]);
        }
        if (address.length > 2) {
            tradeListParam.setReceiver_district(address[2]);
        }
        tradeListParam.setReceiver_address(orderVo.getOrderAttrVo().getExpressAddress());
        tradeListParam.setReceiver_mobile(orderVo.getOrderAttrVo().getExpressPhone());
        tradeListParam.setPost_amount(orderVo.getPriceExpress());
        tradeListParam.setExt_cod_fee(BigDecimal.ZERO);
        tradeListParam.setOther_amount(BigDecimal.ZERO);
        tradeListParam.setPaid(orderVo.getPriceActual());
        tradeListParam.setWarehouse_no(warehouseNo);
        listOrder.add(tradeListParam);

        return listOrder;
    }

}
