package com.bohuikeji.delivery.backstage.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bohuikeji.delivery.backstage.constants.discountConst;
import com.bohuikeji.delivery.backstage.constants.payConst;
import com.bohuikeji.delivery.backstage.entity.*;
import com.bohuikeji.delivery.backstage.entity.discount.TDiscountMall;
import com.bohuikeji.delivery.backstage.entity.discount.TDiscountPattern;
import com.bohuikeji.delivery.backstage.entity.discount.TDiscountPay;
import com.bohuikeji.delivery.backstage.entity.discount.TDiscountRecord;
import com.bohuikeji.delivery.backstage.entity.wx.TWxUser;
import com.bohuikeji.delivery.backstage.listener.pay.PayTimoutListener;
import com.bohuikeji.delivery.backstage.mapper.TDiscountPayMapper;
import com.bohuikeji.delivery.backstage.pay.PayServices;
import com.bohuikeji.delivery.backstage.service.*;
import com.bohuikeji.frame.module.admin.component.MqTool;
import com.bohuikeji.frame.module.admin.entity.back.APIEntity;
import com.bohuikeji.frame.module.admin.entity.vo.AliReturnPayVo;
import com.bohuikeji.frame.module.admin.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.time.Duration;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
/**
 * <p>
 * 支付交易信息表 服务实现类
 * </p>
 *
 * @author 10552
 * @since 2019-12-27
 */
@Service
@Slf4j
public class TDiscountPayImpl extends ServiceImpl<TDiscountPayMapper, TDiscountPay> implements ITDiscountPayService {
    @Autowired
    ITDiscountMallService discountMallService;
    @Autowired
    ITCustomerService customerService;
    @Autowired
    ITDiscountPayService discountPayService;
    @Autowired
    ITDiscountRecordService discountRecordService;
    @Autowired
    ITDiscountPatternService discountPatternService;
    @Autowired
    IWxUserService wxUserService;
    @Autowired
    MqTool mqTool;


    @Override
    public APIEntity getPayByDis(TDiscountMall discountMall, Integer customerId, HttpServletRequest request) throws Exception {
        TCustomer customer = customerService.getById(customerId);
        String openId = null;
        //创建预支付订单
        TDiscountPay discountPay =discountPayService.createBeforePay(discountMall,customer.getCustomerId(),"购买优惠","客户支付", payConst.getway(discountMall.getType()));
        if("JSAPI".equals(discountMall.getType())){
            openId = customer.getOpenId();
        }
        if("aliClient".equals(discountMall.getType())){
            TWxUser wxUser = wxUserService.getOne(new QueryWrapper<TWxUser>().eq("user_id",customer.getCustomerId()).eq("wx_app_type","ALICLIENT"));
            if(wxUser == null){
                return APIEntity.fail("请用户授权");
            }
            openId = wxUser.getWxUserOpenid();
        }
        if("kuaiShou".equals(discountMall.getType())){
            TWxUser wxUser = wxUserService.getOne(new QueryWrapper<TWxUser>().eq("user_id",customer.getCustomerId()).eq("wx_app_type","KUAISHOU"));
            if(wxUser == null){
                return APIEntity.fail("请用户授权");
            }
            openId = wxUser.getWxUserOpenid();
        }
        String payNum = discountPay.getPayNum();
        JSONObject object = payConst.getObject(discountMall.getType(),payNum,openId,discountMall.getDisPrice(),request);
        return object==null?APIEntity.fail("客户调起"+payConst.getway(discountMall.getType())+"支付错误"):APIEntity.success(object);
    }

    @Override
    public TDiscountRecord handleDiscountService(JSONObject jsonObject, AliReturnPayVo req, TDiscountPay discountPay, Integer disId, Integer customerId) throws Exception {
        TDiscountRecord discountRecord = new TDiscountRecord();
        TDiscountMall discountMall =null;
        if(disId==null){
            discountPayService.updateById(PayServices.getDisPaySrevice(jsonObject,req,discountPay));
            discountMall = discountMallService.getById(discountPay.getDisId());
            discountRecord.setCustomerId(discountPay.getPlayerId());
        }else {
            discountMall = discountMallService.getById(disId);
            discountRecord.setCustomerId(customerId);
        }
        if("会员卡".equals(discountMall.getDisType())){
            discountRecord.setUsageStatus("使用中");
            discountRecord.setBeginDate(LocalDate.now());
            discountRecord.setEndDate(discountConst.getEndDate(discountMall.getDisName()));
            TDiscountPattern discountPattern = discountPatternService.getOne(new QueryWrapper<TDiscountPattern>().eq("description","展示模板").eq("receive_method",discountMall.getReceiveMethod()).eq("pattern_type",discountMall.getConsType()));
            discountRecord.setUrlPicture(discountConst.getMemberDisUrl(discountMall,discountPattern));
        }else {
            discountRecord.setUsageStatus("未使用");
            discountRecord.setBeginDate(discountMall.getBeginDate());
            discountRecord.setEndDate(discountMall.getEndDate());
            discountRecord.setUrlPicture(discountMall.getUrlPicture());
        }
        discountRecord.setDisId(discountMall.getDisId());
        discountRecord.setConsType(discountMall.getConsType());
        discountRecord.setDisValue(discountMall.getDisValue());
        discountRecord.setCollectionTime(LocalDateTime.now());
        discountRecord.setDisType(discountMall.getDisType());
        discountRecord.setDisRemark(discountMall.getDisRemark());
        discountRecord.setUseExplain(discountMall.getUseExplain());
        discountRecord.setStartAmount(discountMall.getStartAmount());
        discountRecord.setReceiveMethod(discountMall.getReceiveMethod());
        discountRecord.setGrantType(discountMall.getGrantType());
        if(discountRecordService.save(discountRecord)){
            discountMall.setReceiveNum(discountMall.getReceiveNum()+1);
            discountMallService.updateById(discountMall);
        }
        return discountRecord;
    }

    /**
     * 订单业务创建预支付单（微信，支付宝）
     * @return
     */
    @Override
    public TDiscountPay createBeforePay(TDiscountMall discountMall, Integer customerId, String scenario, String payMethod, String payWay) {
        TDiscountPay discountPay=new TDiscountPay();
        discountPay.setPayStatus("待付款");
        discountPay.setPlayerId(customerId);
        discountPay.setDisId(discountMall.getDisId());
        discountPay.setDisType(discountMall.getDisType());
        discountPay.setPayNum(NumberUtils.get("YH"));
        discountPay.setCreateTime(LocalDateTime.now());
        discountPay.setPayScenario(scenario);
        discountPay.setPayMethod(payMethod);
        discountPay.setPayWay(payWay);
        this.save(discountPay);
        mqTool.sendDelayMsg(discountPay.getPayNum(), PayTimoutListener.class, Duration.ofHours(3));
        return discountPay;
    }
}
