package com.fzm.mall.server.front.order.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fzm.mall.server.front.asset.service.IUserAssetService;
import com.fzm.mall.server.front.enums.CoinNameEnum;
import com.fzm.mall.server.front.goods.model.MarketingCouponCategory;
import com.fzm.mall.server.front.goods.model.MarketingCouponSku;
import com.fzm.mall.server.front.goods.model.vo.CouponVo;
import com.fzm.mall.server.front.goods.model.vo.SkuVo;
import com.fzm.mall.server.front.goods.service.IDistributionTemplateService;
import com.fzm.mall.server.front.goods.service.IGoodSkuPropService;
import com.fzm.mall.server.front.goods.service.IGoodSkuService;
import com.fzm.mall.server.front.goods.service.IMarketingCouponService;
import com.fzm.mall.server.front.order.mapper.OrderMapper;
import com.fzm.mall.server.front.order.model.*;
import com.fzm.mall.server.front.order.mapper.PayMapper;
import com.fzm.mall.server.front.order.model.po.PayRestVO;
import com.fzm.mall.server.front.order.model.vo.OrderSkuVo;
import com.fzm.mall.server.front.order.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fzm.mall.server.front.redis.GoodRedis;
import com.fzm.mall.server.front.redis.OrderRedis;
import com.fzm.mall.server.front.user.service.ICouponService;
import io.netty.util.internal.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * <p>
 * 支付订单结果表 服务实现类
 * </p>
 *
 * @author fzm
 * @since 2021-04-08
 */
@Service
public class PayServiceImpl extends ServiceImpl<PayMapper, Pay> implements IPayService {

    @Autowired
    private IUserAssetService userAssetService;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderRedis orderRedis;

    @Autowired
    private IPayRecordService payRecordService;

    @Autowired
    private IOrderDetailService orderDetailService;

    @Autowired
    private IGoodSkuService goodSkuService;

    @Autowired
    private IDistributionTemplateService distributionTemplateService;

    @Autowired
    private IMarketingCouponService marketingCouponService;

    @Autowired
    private ICouponService iCouponService;

    @Autowired
    private IGoodsCouponService goodsCouponService;

    @Autowired
    private IGoodSkuPropService goodSkuPropService;

    //平台-商户号
    public static final String PLATFORM_MERCHANT_ID = "e3ac4b4a4e65460dbd9f1ec6cbd7a900";

    @Override
    public Pay getByPidAndUid(String pid, String uid) {
        QueryWrapper<Pay> query = new QueryWrapper<>();
        query.eq("pay_id", pid);
        query.eq("uid", uid);
        return getOne(query);
    }

    @Override
    public int pay(String uid, String pid) {
        Pay pay = getByPidAndUid(pid, uid);
        if (pay.getState() == 6 || pay.getState() == 7||pay.getState() ==3) {
            int i = userAssetService.delAsset(uid, pay.getUnpaidAmount(), CoinNameEnum.MALLCOIN.value());
            if (i == 1) {
                pay.setState(1);
                pay.setPaidAmount(pay.getUnpaidAmount());
                pay.setUnpaidAmount(BigDecimal.ZERO);
                pay.setPayTime(System.currentTimeMillis());
                updateById(pay);
                JSONArray array = JSONArray.parseArray(pay.getOidsJson());
                for (Object oid : array) {
                    Order order = orderMapper.getByOid(oid.toString());
                    orderMapper.paySuccess(oid.toString(), System.currentTimeMillis());
                    goodSkuPropService.delSkuProCachByOid(order.getOid());
                    orderRedis.delOrder(oid.toString());
                    /*//支付记录
                    PayRecord payRecord = new PayRecord();
                    payRecord.setPayId(pid);
                    payRecord.setOid(oid.toString());
                    payRecord.setPayTime(System.currentTimeMillis());
                    payRecord.setPayType(pay.getPayType());
                    payRecord.setMerchantId(order.getMerchantId());
                    payRecord.setPayAmount(order.getAmount());
                    payRecord.setState(1);
                    payRecordService.save(payRecord);*/
                }
                return 1;
            } else {
                //资产不足
                return 0;
            }
        } else {
            //订单处于不可支付状态
            return -1;
        }
    }

    @Override
    public Pay getByPid(String message) {
        QueryWrapper<Pay> query = new QueryWrapper<>();
        query.eq("pay_id", message);
        return getOne(query);
    }

    @Override
    public int payDeposit(String uid, String pid) {
        Pay pay = getByPidAndUid(pid, uid);
        if (pay.getState() == 4) {
            int i = userAssetService.delAsset(uid, pay.getUnpaidAmount(), CoinNameEnum.MALLCOIN.value());
            if (i == 1) {
                pay.setState(8);
                pay.setPaidAmount(pay.getUnpaidAmount());

                JSONArray array = JSONArray.parseArray(pay.getOidsJson());
                BigDecimal unPaidAmount = BigDecimal.ZERO;
                for (Object oid : array) {
                    Order order = orderMapper.getByOid(oid.toString());
                    List<OrderDetail> list = orderDetailService.getList(oid.toString());
                    for (OrderDetail orderDetail : list) {
                        unPaidAmount = unPaidAmount.add(orderDetail.getAmount().multiply(new BigDecimal(orderDetail.getNumber())));
                    }
                    orderMapper.paySuccess(oid.toString(), System.currentTimeMillis());
                    orderRedis.delOrder(oid.toString());
                    //支付记录
                    PayRecord payRecord = new PayRecord();
                    payRecord.setPayId(pid);
                    payRecord.setOid(oid.toString());
                    payRecord.setPayTime(System.currentTimeMillis());
                    payRecord.setPayType(pay.getPayType());
                    payRecord.setMerchantId(order.getMerchantId());
                    payRecord.setPayAmount(order.getAmount());
                    payRecord.setState(1);
                    payRecordService.save(payRecord);
                }
                pay.setUnpaidAmount(unPaidAmount.subtract(pay.getPaidAmount()));
                pay.setPayTime(System.currentTimeMillis());
                updateById(pay);
                return 1;
            } else {
                //资产不足
                return 0;
            }
        } else {
            //订单处于不可支付状态
            return -1;
        }
    }

    @Override
    public int payRest(String uid, PayRestVO pid) {
        Pay pay = getByPidAndUid(pid.getPid(), uid);
        PayRecord payRecord = new PayRecord();
        GoodsCoupon goodsCoupon = new GoodsCoupon();
        if (pay.getState() == 8) {
            BigDecimal postfee = BigDecimal.ZERO;
            BigDecimal coupon = BigDecimal.ZERO;
            JSONArray array = JSONArray.parseArray(pay.getOidsJson());
            BigDecimal unPaidAmount = BigDecimal.ZERO;
            for (Object oid : array) {
                Order order = orderMapper.getByOid(oid.toString());
                List<OrderDetail> list = orderDetailService.getList(oid.toString());
                for (OrderDetail orderDetail : list) {
                    SkuVo skuVo = goodSkuService.getSkuVoBySkuId(orderDetail.getSkuId());
                    //不提货
                    if (pid.getDelivery() == 0) {
                        if (StringUtil.isNullOrEmpty(skuVo.getCoinName())) {
                            //只支持立即提货
                            return -2;
                        }
                        order.setDelivery(0);
                    } else {
                        order.setPhone(pid.getPhone());
                        order.setUname(pid.getUname());
                        order.setAddress(pid.getAddress());
                        order.setDelivery(1);
                        postfee = distributionTemplateService.getPrice(skuVo.getTemplateId(), pid.getProvince(), new BigDecimal(orderDetail.getNumber()).multiply(orderDetail.getAmount()), orderDetail.getNumber(), new BigDecimal(orderDetail.getNumber()).multiply(skuVo.getWeight()));
                    }
                    //优惠券
                    Map<String, BigDecimal> merchantCoupon = new HashMap<>();
                    try {
                        List<String> goodsIdCouponVos;
                        List<OrderSkuVo> allSkuVo = new ArrayList<>();
                        OrderSkuVo e = new OrderSkuVo();
                        e.setNum(orderDetail.getNumber());
                        e.setSkuId(orderDetail.getSkuId());
                        allSkuVo.add(e);
                        merchantCoupon = marketingCouponService.getCoupon(uid, pid.getGoodsIdCouponId(), allSkuVo, 1);
                    } catch (Exception e) {
                        throw new RuntimeException("存在无效优惠券!!!");
                    }
                    if(merchantCoupon!=null&&merchantCoupon.get(skuVo.getMerchantId())!=null){

                        goodsCoupon.setCouponId("");
                        goodsCoupon.setGoodsId("");
                        goodsCoupon.setAmount(merchantCoupon.get(skuVo.getMerchantId()));
                        goodsCoupon.setOid(order.getOid());
                        goodsCoupon.setUid(uid);

                    }
                    coupon = merchantCoupon.get(skuVo.getMerchantId());
                }
                orderMapper.paySuccess(oid.toString(), System.currentTimeMillis());
                orderRedis.delOrder(oid.toString());
                //支付记录
                payRecord.setPayId(pid.getPid());
                payRecord.setOid(oid.toString());
                payRecord.setPayTime(System.currentTimeMillis());
                payRecord.setPayType(pay.getPayType());
                payRecord.setMerchantId(order.getMerchantId());
                payRecord.setPayAmount(pay.getUnpaidAmount().add(postfee).subtract(coupon));
                payRecord.setState(1);
            }
            int i = userAssetService.delAsset(uid,pay.getUnpaidAmount().add(postfee).subtract(coupon), CoinNameEnum.MALLCOIN.value());
            if (i == 1) {
                pay.setPaidAmount(pay.getPaidAmount().add(pay.getUnpaidAmount()).add(postfee).subtract(coupon));
                pay.setUnpaidAmount(BigDecimal.ZERO);
                pay.setPayTime(System.currentTimeMillis());
                pay.setState(1);
                updateById(pay);
                goodsCouponService.save(goodsCoupon);
                payRecordService.save(payRecord);
            } else {
                return 0;
            }
        } else {
            //订单处于不可支付状态
            return -1;
        }
        return 1;
    }

    @Override
    public String getGoodsName(Pay pay) {
        JSONArray array = JSONArray.parseArray(pay.getOidsJson());
        StringBuilder sb = new StringBuilder();
        for (Object oid: array) {
            List<OrderDetail> list = orderDetailService.getList(oid.toString());
            for (OrderDetail orderDetail:list) {
                String name = goodSkuService.getGoodsName(orderDetail.getGoodsId());
                sb.append(name+",");
            }
        }
        return sb.substring(0,sb.length()-1);
    }

}
