package com.liquidnet.service.order.utils;

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.base.SqlMapping;
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.candy.vo.CandyUseResultVo;
import com.liquidnet.service.goblin.dto.vo.GoblinUseResultVo;
import com.liquidnet.service.goblin.dto.vo.GoblinUserCouponVo;
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.Arrays;
import java.util.HashMap;
import java.util.List;

@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
    QueueUtils queueUtils;
    @Autowired
    GoblinRedisUtils redisUtils;
    @Autowired
    GoblinMongoUtils goblinMongoUtils;

    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);
            return null;
        }
    }

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

    public GoblinUseResultVo useStoreCoupon(String ucouponId, String content, BigDecimal totalPrice, String spuId, String uid) {
        try {
            List<GoblinUserCouponVo> voList = redisUtils.getUserCouponVos(uid);
            GoblinUseResultVo returnVo = GoblinUseResultVo.getNew();
            returnVo.setValue(BigDecimal.ZERO);
            returnVo.setCouType("-1");
            for (GoblinUserCouponVo vo : voList) {
                if (vo.getUcouponId().equals(ucouponId)) {
                    //判断券状态 和 触发金额
                    if ((vo.getState().equals(1)) && vo.getTriggers().compareTo(totalPrice) <= 0) {
                        if (vo.getUseScope().equals("0")) {
                            if (vo.getType().equals("1")) {//代金券
                                returnVo.setValue(vo.getValFace());
                                returnVo.setCouType(vo.getType());
                            } else if (vo.getType().equals("2")) {//折扣
                                BigDecimal tempPrice = totalPrice.multiply(vo.getDiscount()).setScale(2, BigDecimal.ROUND_HALF_UP);
                                if (tempPrice.compareTo(vo.getDeduction()) > 0) {
                                    tempPrice = vo.getDeduction();
                                }
                                returnVo.setValue(tempPrice);
                                returnVo.setCouType(vo.getType());
                            } else if (vo.getType().equals("3") && vo.getTriggers().compareTo(totalPrice) <= 0) {//满减
                                returnVo.setValue(vo.getValMinus());
                                returnVo.setCouType(vo.getType());
                            }
                            vo.setState(5);
                            vo.setUsedFor(content);
                            goblinMongoUtils.changeCouponVos(vo.getUcouponId(), vo);
                            queueUtils.sendMsgByRedis(MQConst.GoblinQueue.SQL_COUPON.getKey(),
                                    SqlMapping.get("goblin_user_coupon.updateState", vo.getState(), vo.getUsedFor(), LocalDateTime.now(), vo.getUcouponId()));
                            break;
                        } else {
                            List<String> spuIds = redisUtils.getStoreCouponSpuIds(vo.getStoreCouponId());
                            if (spuId == null) {
                                continue;
                            }
                            //判断是否在可用商品内
                            List<String> spuList = Arrays.asList(spuId.split(","));
                            for (String item : spuIds) {
                                if (spuList.contains(item)) {
                                    if (vo.getType().equals("1")) {//代金券
                                        returnVo.setValue(vo.getValFace());
                                        returnVo.setCouType(vo.getType());
                                    } else if (vo.getType().equals("2")) {//折扣
                                        BigDecimal tempPrice = totalPrice.multiply(vo.getDiscount()).setScale(2, BigDecimal.ROUND_HALF_UP);
                                        if (tempPrice.compareTo(vo.getDeduction()) > 0) {
                                            tempPrice = vo.getDeduction();
                                        }
                                        returnVo.setValue(tempPrice);
                                        returnVo.setCouType(vo.getType());
                                    } else if (vo.getType().equals("3") && vo.getTriggers().compareTo(totalPrice) <= 0) {//满减
                                        returnVo.setValue(vo.getValMinus());
                                        returnVo.setCouType(vo.getType());
                                    }
                                    vo.setState(5);
                                    vo.setUsedFor(content);
                                    goblinMongoUtils.changeCouponVos(vo.getUcouponId(), vo);
                                    queueUtils.sendMsgByRedis(MQConst.GoblinQueue.SQL_COUPON.getKey(),
                                            SqlMapping.get("goblin_user_coupon.updateState", vo.getState(), vo.getUsedFor(), LocalDateTime.now(), vo.getUcouponId()));
                                }
                                break;
                            }
                        }
                    }
                    break;
                }
            }
            if (!returnVo.getCouType().equals("-1")) {
                redisUtils.setUserCouponVos(uid, voList);
            }
            return returnVo;
        }catch (Exception e){
            log.error("店铺券错误:{}",e);
            return null;
        }
    }

    public Boolean backStoreCoupon(List<com.liquidnet.service.goblin.param.BackCouponParam> params) {
        try {
            for (com.liquidnet.service.goblin.param.BackCouponParam item : params) {
                List<GoblinUserCouponVo> voList = redisUtils.getUserCouponVos(item.getUid());
                for (GoblinUserCouponVo vo : voList) {
                    if (vo.getUcouponId().equals(item.getuCouponIds())) {
                        if (LocalDateTime.now().isBefore(vo.getDuedAt())) {
                            vo.setState(1);
                            vo.setUsedFor("");
                            redisUtils.setUserCouponVos(item.getUid(), voList);
                            goblinMongoUtils.changeCouponVos(vo.getUcouponId(), vo);
                            queueUtils.sendMsgByRedis(MQConst.GoblinQueue.SQL_COUPON.getKey(),
                                    SqlMapping.get("goblin_user_coupon.updateState", vo.getState(), vo.getUsedFor(), LocalDateTime.now(), vo.getUcouponId()));
                        }
                        break;
                    }
                }
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public Integer getMember(String uid) {
        return redisUtils.getMember(uid);
    }
}
