package com.sien.common.service.impl;
import cn.hutool.captcha.generator.RandomGenerator;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.binarywang.wxpay.bean.order.WxPayMpOrderResult;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.sien.common.entity.DonationRecord;
import com.sien.common.mapper.DonationRecordMapper;
import com.sien.common.param.DonationRecordPageParam;
import com.sien.common.param.app.DonationRecordAdd;
import com.sien.common.service.AppUserService;
import com.sien.common.service.DonationRecordService;
import com.sien.common.vo.AppUserQueryVo;
import com.sien.common.vo.DonationRankAndTotal;
import com.sien.common.vo.DonationRecordQueryVo;
import io.geekidea.springbootplus.framework.common.api.ApiResult;
import io.geekidea.springbootplus.framework.common.service.impl.BaseServiceImpl;
import io.geekidea.springbootplus.framework.core.pagination.PageInfo;
import io.geekidea.springbootplus.framework.core.pagination.Paging;
import io.geekidea.springbootplus.framework.shiro.jwt.JwtToken;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;

/**
 * 捐款记录 服务实现类
 *
 * @author hewei
 * @since 2021-02-25
 */
@Slf4j
@Service
public class DonationRecordServiceImpl extends BaseServiceImpl<DonationRecordMapper, DonationRecord> implements DonationRecordService {

    private static final String BODY = "四恩慈善会-捐款";

    private static final String http = "http";

    @Autowired
    private DonationRecordMapper donationRecordMapper;

    @Autowired
    private WxPayService wxService;

    @Autowired
    HttpServletRequest req;

    @Autowired
    private AppUserService appUserService;

    @Override
    public DonationRankAndTotal getDonationRankAndTotal(Long userId) {
        return donationRecordMapper.getDonationRankAndTotal(userId);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean saveDonationRecord(DonationRecord donationRecord) throws Exception {
        return super.save(donationRecord);
    }


    @Override
    public ApiResult<WxPayMpOrderResult> add(DonationRecordAdd donationRecordAdd) throws Exception {

        JwtToken jwtToken = (JwtToken) SecurityUtils.getSubject().getPrincipal();
        AppUserQueryVo appUserById = appUserService.getAppUserById(jwtToken.getUserId());

        WxPayUnifiedOrderRequest wxPayUnifiedOrderRequest = new WxPayUnifiedOrderRequest();

        String openid = appUserById.getWechatOpenId();
        String spbillCreateIp = req.getRemoteAddr();
        int totalFee = donationRecordAdd.getMoney().intValue() * 100;

        DonationRecord donationRecord = new DonationRecord();
//        donationRecord.setId(0L);
        donationRecord.setFkUserId(jwtToken.getUserId());
        donationRecord.setMoney(donationRecordAdd.getMoney());
        donationRecord.setPurpose(donationRecordAdd.getPurpose());
        donationRecord.setWay(donationRecordAdd.getWay());
//        donationRecord.setRemark("");
//        donationRecord.setCreateTime(new Date());
//        donationRecord.setUpdateTime(new Date());
        donationRecord.setIsReplace(donationRecordAdd.getIsReplace());


        WxPayMpOrderResult order = getWxPayMpOrderResult(wxPayUnifiedOrderRequest, BODY, openid, spbillCreateIp, totalFee, http);

        return ApiResult.ok(order);
    }

    private WxPayMpOrderResult getWxPayMpOrderResult(WxPayUnifiedOrderRequest wxPayUnifiedOrderRequest, String body, String openid, String spbillCreateIp, int totalFee, String http) {
        wxPayUnifiedOrderRequest.setBody(body);

        // 商户系统内部的订单号,32个字符内、可包含字母, 其他说明见商户订单号
        wxPayUnifiedOrderRequest.setOutTradeNo(new RandomGenerator(32).generate());

        //订单总金额，单位为分，详见支付金额
        wxPayUnifiedOrderRequest.setTotalFee(totalFee);

        // APP和网页支付提交用户端ip
        wxPayUnifiedOrderRequest.setSpbillCreateIp(spbillCreateIp);

        // 接收微信支付异步通知回调地址，通知url必须为直接可访问的url，不能携带参数。
        wxPayUnifiedOrderRequest.setNotifyUrl(http);

        wxPayUnifiedOrderRequest.setOpenid(openid);
        String jsapi = "JSAPI";
        wxPayUnifiedOrderRequest.setTradeType(jsapi);

        WxPayMpOrderResult order = null;
        try {
            order = this.wxService.createOrder(wxPayUnifiedOrderRequest);
        } catch (WxPayException e) {
            e.printStackTrace();
        }
        return order;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateDonationRecord(DonationRecord donationRecord) throws Exception {
        return super.updateById(donationRecord);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deleteDonationRecord(Long id) throws Exception {
        return super.removeById(id);
    }

    @Override
    public DonationRecordQueryVo getDonationRecordById(Long id) throws Exception {
        return donationRecordMapper.getDonationRecordById(id);
    }

    @Override
    public Paging<DonationRecordQueryVo> getDonationRecordPageList(DonationRecordPageParam donationRecordPageParam) throws Exception {
        Page<DonationRecordQueryVo> page = new PageInfo<>(donationRecordPageParam, OrderItem.desc(getLambdaColumn(DonationRecord::getCreateTime)));
        IPage<DonationRecordQueryVo> iPage = donationRecordMapper.getDonationRecordPageList(page, donationRecordPageParam);
        return new Paging<DonationRecordQueryVo>(iPage);
    }

}
