package cn.pluss.platform.officialGoods.exchange.impl;

import cn.pluss.platform.api.Result;
import cn.pluss.platform.api.ResultGenerator;
import cn.pluss.platform.constants.Constant;
import cn.pluss.platform.entity.*;
import cn.pluss.platform.exception.MsgException;
import cn.pluss.platform.mapper.*;
import cn.pluss.platform.merchant.MerchantBaseInfoService;
import cn.pluss.platform.merchant.MerchantRateNewService;
import cn.pluss.platform.merchantStore.MerchantStoreService;
import cn.pluss.platform.officialGoods.exchange.OfficialGoodsExchangeService;
import cn.pluss.platform.pay.PayService;
import cn.pluss.platform.systemConfig.SystemConfigService;
import cn.pluss.platform.systemInfo.SystemInfoService;
import cn.pluss.platform.userIntegralUse.UserIntegralUseService;
import cn.pluss.platform.util.StringUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Djh
 * @since 2020-10-09
 */
@Service
@Transactional
public class OfficialGoodsExchangeServiceImpl extends ServiceImpl<OfficialGoodsExchangeMapper, OfficialGoodsExchange> implements OfficialGoodsExchangeService {

    @Resource
    private UserAddressMapper userAddressMapper;

    @Resource
    private MerchantTransferCashMapper merchantTransferCashMapper;

    @Setter(onMethod_ = {@Autowired, @Qualifier("ysPayOldService")})
    private PayService ysPayOldService;

    @Resource
    private MerchantRateNewService merchantRateNewService;

    @Resource
    private MerchantOrderMapper merchantOrderMapper;

    @Resource
    private MerchantChannelStatusMapper merchantChannelStatusMapper;

    @Resource
    private MerchantBaseInfoService merchantBaseInfoService;

    @Resource
    private MerchantStoreService merchantStoreService;

    @Autowired
    private SystemConfigService systemConfigService;

    @Autowired
    private UserIntegralUseService userIntegralUseService;


    /**
     * 兑换记录
     *
     * @param goods
     * @param userApp
     * @return
     */
    @Override
    public Result exchange(OfficialGoods goods, UserApp userApp, Integer aid) {

        JSONObject result = new JSONObject();
        UserAddress userAddress = userAddressMapper.selectById(aid);
        if (userAddress == null) {
            return ResultGenerator.genFailResult("收货地址信息异常！");
        }
        String orderNumber = "YS_" + StringUtil.getBillno();
        Integer isPostage = goods.getIsPostage();
        Integer deductRule = goods.getDeductRule();
        OfficialGoodsExchange goodsExchange = new OfficialGoodsExchange();
        goodsExchange.setGoodId(goods.getId());
        goodsExchange.setUserId(userApp.getUserId());
        goodsExchange.setCreateTime(new Date());
        goodsExchange.setAddress(userAddress.getAreaName() + userAddress.getAddress());
        goodsExchange.setPhone(userAddress.getPhone());
        goodsExchange.setUserName(userAddress.getName());
        goodsExchange.setPrice(goods.getGoodPrice());
        goodsExchange.setName(goods.getGoodName());
        goodsExchange.setOrderNumber(orderNumber);

        UserIntegralUse integralUse = new UserIntegralUse();
        integralUse.setName(goods.getGoodName());
        integralUse.setUserId(userApp.getUserId());
        integralUse.setIntegral(goods.getGoodPrice());
        integralUse.setHandleTime(new Date());
        integralUse.setCreateTime(new Date());
        integralUse.setOrderNumber(orderNumber);
        if (isPostage == 1 && deductRule == 0) {
            goodsExchange.setStatus(1);
            integralUse.setStatus("2");
        } else {
            goodsExchange.setStatus(0);
            String merchantCode = systemConfigService.querySystemConfigValue(Constant.SYSTEM_MERCHANT_KEY);
            if (StringUtil.isEmpty(merchantCode)) {
                merchantCode = Constant.DEFUALT_CASHIER_MERCHANT;
            }
            MerchantBaseInfo merchant = merchantBaseInfoService.getMerchantBaseInfoByMerchantCode(merchantCode);
            MsgException.checkNull(merchant, "商户数据异常！");
            MerchantStore store = merchantStoreService.getStoreByMerchantCode(merchantCode);
            MsgException.checkNull(store, "门店信息异常！");
            MerchantChannelStatus channel = merchantChannelStatusMapper.getByMerchantCode(merchantCode, 4);
            MsgException.checkNull(channel, "通道信息异常！");
            MerchantOrder order = new MerchantOrder();
            order.setOrderNumber(orderNumber);
            order.setOrderType("7");
            order.setMerchantCode(merchantCode);
            order.setMerchantName(merchant.getAlias());
            order.setPayTypeCode(Constant.PAY_TYPE_ALIPAY);
            order.setPayTypeName(Constant.PAY_TYPE_NAME_ALIPAY);
            order.setStoreId(store.getStoreId());
            order.setStoreName(store.getStoreName());
            order.setAlias(merchant.getMerchantName());
            order.setConsumeFee(goods.getPostageFee().add(goods.getDeductValue()).doubleValue());
            order.setToken(userApp.getToken());
            order.setCreateDt(new Date());
            order.setStatus("5");
            BigDecimal rate = merchantRateNewService.getMchRate(merchantCode, Constant.PAY_TYPE_ALIPAY, goods.getPostageFee().doubleValue());
            order.calcRateAndFee(rate);
            order.setAisleSwitch(channel.getChannel() + "");
            try {
                merchantOrderMapper.insert(order);
                String respones = ysPayOldService.tradePayWap(order, channel);
                System.out.printf("respones=============" + respones);
                result.put("result", respones);
            } catch (Exception e) {
                e.printStackTrace();
                MsgException.throwException("系统异常！");
            }
            integralUse.setStatus("1");
        }
        userIntegralUseService.save(integralUse);
        this.baseMapper.insert(goodsExchange);
        return ResultGenerator.genSuccessResult("操作成功！", result);
    }

    @Override
    public Result<Object> exchange(OfficialGoods goods, UserApp userApp) {
        JSONObject result = new JSONObject();
        String orderNumber = "YS_" + StringUtil.getBillno();
        Integer isPostage = goods.getIsPostage();
        Integer deductRule = goods.getDeductRule();
        OfficialGoodsExchange goodsExchange = new OfficialGoodsExchange();
        goodsExchange.setGoodId(goods.getId());
        goodsExchange.setUserId(userApp.getUserId());
        goodsExchange.setAddress(goods.getAddress());
        goodsExchange.setCreateTime(new Date());
        goodsExchange.setPhone("");
        goodsExchange.setUserName("");
        goodsExchange.setPrice(goods.getGoodPrice());
        goodsExchange.setName(goods.getGoodName());
        goodsExchange.setOrderNumber(orderNumber);

        UserIntegralUse integralUse = new UserIntegralUse();
        integralUse.setName(goods.getGoodName());
        integralUse.setUserId(userApp.getUserId());
        integralUse.setIntegral(goods.getGoodPrice());
        integralUse.setHandleTime(new Date());
        integralUse.setCreateTime(new Date());
        integralUse.setOrderNumber(orderNumber);

        if (isPostage == 1 && deductRule == 0) {
            goodsExchange.setStatus(1);
            integralUse.setStatus("2");
        } else {
            goodsExchange.setStatus(0);
            String merchantCode = systemConfigService.querySystemConfigValue(Constant.SYSTEM_MERCHANT_KEY);
            if (StringUtil.isEmpty(merchantCode)) {
                merchantCode = Constant.DEFUALT_CASHIER_MERCHANT;
            }

            MerchantBaseInfo merchant = merchantBaseInfoService.getMerchantBaseInfoByMerchantCode(merchantCode);
            MsgException.checkNull(merchant, "商户数据异常！");
            MerchantStore store = merchantStoreService.getStoreByMerchantCode(merchantCode);
            MsgException.checkNull(store, "门店信息异常！");
            MerchantChannelStatus channel = merchantChannelStatusMapper.getByMerchantCode(merchantCode, 4);
            MsgException.checkNull(channel, "通道信息异常！");
            MerchantOrder order = new MerchantOrder();
            order.setOrderNumber(orderNumber);
            order.setOrderType("7");
            order.setMerchantCode(merchantCode);
            order.setMerchantName(merchant.getAlias());
            order.setPayTypeCode(Constant.PAY_TYPE_ALIPAY);
            order.setPayTypeName(Constant.PAY_TYPE_NAME_ALIPAY);
            order.setStoreId(store.getStoreId());
            order.setStoreName(store.getStoreName());
            order.setAlias(merchant.getMerchantName());
            order.setConsumeFee(goods.getPostageFee().add(goods.getDeductValue()).doubleValue());
            order.setToken(userApp.getToken());
            order.setCreateDt(new Date());
            order.setStatus("5");
            BigDecimal rate = merchantRateNewService.getMchRate(merchantCode, Constant.PAY_TYPE_ALIPAY, goods.getPostageFee().doubleValue());
            order.calcRateAndFee(rate);
            order.setAisleSwitch(channel.getChannel() + "");
            try {
                merchantOrderMapper.insert(order);
                String response = ysPayOldService.tradePayWap(order, channel);
                result.put("result", response);
            } catch (Exception e) {
                e.printStackTrace();
                MsgException.throwException("系统异常！");
            }
            integralUse.setStatus("1");
        }
        userIntegralUseService.save(integralUse);
        this.baseMapper.insert(goodsExchange);
        return ResultGenerator.genSuccessResult("操作成功！", result);
    }
}
