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.adam.dto.vo.AdamRscPolymer01Vo;
import com.liquidnet.service.base.ResponseDto;
import com.liquidnet.service.candy.param.BackCouponParam;
import com.liquidnet.service.candy.vo.CandyCouponVo;
import com.liquidnet.service.candy.vo.CandyUseResultVo;
import com.sun.org.apache.xpath.internal.operations.Bool;
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.util.ArrayList;
import java.util.HashMap;

@Component
@Slf4j
public class GoblinOrderUtils {

    @Value("${liquidnet.service.adam.url}")
    private String adamUrl;
    @Value("${liquidnet.service.candy.url}")
    private String candyUrl;
    @Value("${liquidnet.service.stone.url}")
    private String stoneUrl;
    @Autowired
    GoblinRedisUtils redisUtils;

    public AdamRscPolymer01Vo adamAddressEnterMember(String uid, String enterIds, String addressId) {
        try {
            MultiValueMap<String, String> header = CollectionUtil.linkedMultiValueMapStringString();
            header.add("Accept", "application/json;charset=UTF-8");
            MultiValueMap<String, String> params = CollectionUtil.linkedMultiValueMapStringString();
            params.add("addressId", addressId);
            params.add("entersIds", enterIds);
            params.add("uid", uid);
            String resultData = HttpUtil.post(adamUrl + "/adam/rsc/inquire/of_buy_ticket", params, header);
            ResponseDto<AdamRscPolymer01Vo> vo = JsonUtils.fromJson(resultData, new TypeReference<ResponseDto<AdamRscPolymer01Vo>>() {
            });
            if (null != vo.getData()) {
                return vo.getData();
            } else {
                return null;
            }
        } catch (Exception e) {
            log.error("获取用户信息,e:{}", e);
            e.printStackTrace();
            return null;
        }
    }

    //判断 数量限购
    public String judgeOrderLimit(String uid, String skuId, int number, int limitCount) {
        int buyCount = redisUtils.getSkuCountByUid(uid, skuId);
        if (buyCount + number > limitCount) {
            return "已超出限购数量";
        } else {
            int a = redisUtils.incrSkuCountByUid(uid, skuId, number);
            return "";
        }
    }

    //判断指定人群购买
    public Boolean judgeOrderRose(Boolean isMember, String skuId, String mobile, int buyFactor) {
        Boolean result = false;
        switch (buyFactor) {
            case 0:
                result = true;
                break;
            case 1:
                result = isMember;
                break;
            case 2:
                result = redisUtils.getSkuCanBuyByUid(mobile, skuId);
                break;
        }
        return result;
    }

    /**
     * 使用优惠券
     *
     * @param uCouponId  券id
     * @param content    消费内容
     * @param totalPrice 订单总价
     * @return
     */
    public HashMap<String, Object> useCoupon(String uCouponId, String content, BigDecimal totalPrice, String spuId, String uid) {
        HashMap<String, Object> hashMap = CollectionUtil.mapStringObject();
        try {
            MultiValueMap<String, String> params = CollectionUtil.linkedMultiValueMapStringString();
            params.add("uCouponId", uCouponId);
            params.add("content", content);
            params.add("totalPrice", totalPrice.toString());
            params.add("goodId", spuId);
            params.add("performanceId", "null");
            params.add("timeId", "null");
            params.add("ticketId", "null");
            params.add("uid", uid);
            MultiValueMap<String, String> header = CollectionUtil.linkedMultiValueMapStringString();
            header.add("Authorization", "Bearer " + CurrentUtil.getToken());
            header.add("Accept", "application/json;charset=UTF-8");
            log.debug("url=" + candyUrl + "/candy-coupon/use");
            String returnData = HttpUtil.post(candyUrl + "/candy-coupon/use", params, header);
            ResponseDto<CandyUseResultVo> innerReturnVo = JsonUtils.fromJson(returnData, new TypeReference<ResponseDto<CandyUseResultVo>>() {
            });
            CandyUseResultVo candyUseResultVo = innerReturnVo.getData();
            Integer type = candyUseResultVo.getCouType();
            BigDecimal value = candyUseResultVo.getValue();
            BigDecimal voucher = BigDecimal.ZERO;
            switch (type) {
                case -1:
                    voucher = BigDecimal.valueOf(-1);
                    break;
                case 1:
                    voucher = voucher.add(value);
                    break;
                case 2:
                    voucher = voucher.add(value);
                    break;
                case 3:
                    voucher = voucher.add(totalPrice);
                    break;
                case 4:
                    voucher = totalPrice.subtract(totalPrice.multiply(value));
                    break;
                default:
                    voucher = BigDecimal.ZERO;
                    break;
            }
            hashMap.put("type", type);
            hashMap.put("voucher", voucher.setScale(2, BigDecimal.ROUND_HALF_UP));
            return hashMap;
        } catch (Exception e) {
            log.error("用券ERROR:{}", e);
            hashMap.put("type", -1);
            hashMap.put("voucher", 0);
            return hashMap;
        }
    }

    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) {
        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);
            String returnData = HttpUtil.post(candyUrl + " /candy-coupon/receive/ListById", params, header);
            ResponseDto<CandyCouponVo> innerReturnVo = JsonUtils.fromJson(returnData, new TypeReference<ResponseDto<CandyCouponVo>>() {
            });
            return innerReturnVo.getData();
        } catch (Exception e) {
            log.error("回退券ERROR:{}", e);
            CandyCouponVo vo = CandyCouponVo.getNew();
            vo.setUcouponId(uCouponId);
            vo.setTitle("");
            return vo;
        }
    }

    public void doTask(String uid, BigDecimal price) {
        try {
            MultiValueMap<String, String> header = CollectionUtil.linkedMultiValueMapStringString();
            header.add("Accept", "application/json;charset=UTF-8");
            MultiValueMap<String, String> params = CollectionUtil.linkedMultiValueMapStringString();
            params.add("score", price.intValue() + "");
            params.add("content", "购买商品:");
            params.add("uid", uid);
            String resultData = HttpUtil.post(stoneUrl + "/user/logs/in2111", params, header);
        } catch (Exception e) {
            log.error("添加积分失败,e:{}", e);
            e.printStackTrace();
        }
    }

    public void desTask(String uid, BigDecimal price) {
        try {
            MultiValueMap<String, String> header = CollectionUtil.linkedMultiValueMapStringString();
            header.add("Accept", "application/json;charset=UTF-8");
            MultiValueMap<String, String> params = CollectionUtil.linkedMultiValueMapStringString();
            params.add("score", price.intValue() + "");
            params.add("content", "购买商品:");
            params.add("uid", uid);
            String resultData = HttpUtil.post(stoneUrl + "/user/logs/de2111", params, header);
        } catch (Exception e) {
            log.error("添加积分失败,e:{}", e);
            e.printStackTrace();
        }
    }
}
