package com.slodon.b2b2c.model.system;

import com.slodon.b2b2c.core.config.DomainUrlUtil;
import com.slodon.b2b2c.core.constant.PayConst;
import com.slodon.b2b2c.core.exception.MallException;
import com.slodon.b2b2c.core.response.PagerInfo;
import com.slodon.b2b2c.dao.read.system.BillTransferReadMapper;
import com.slodon.b2b2c.dao.write.system.BillTransferWriteMapper;
import com.slodon.b2b2c.starter.entity.SlodonPayRequest;
import com.slodon.b2b2c.starter.entity.cpcn.TxPayRequest;
import com.slodon.b2b2c.starter.pay.SlodonPay;
import com.slodon.b2b2c.system.example.BillTransferExample;
import com.slodon.b2b2c.system.pojo.BillTransfer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import payment.api.util.GUIDGenerator;

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

/**
 * 结算转账记录表model
 */
@Component
@Slf4j
public class BillTransferModel {
    @Resource
    private BillTransferReadMapper billTransferReadMapper;

    @Resource
    private BillTransferWriteMapper billTransferWriteMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private SlodonPay slodonPay;

    /**
     * 新增结算转账记录表
     *
     * @param billTransfer 结算转账记录信息
     * @return
     */
    public Integer saveBillTransfer(BillTransfer billTransfer) {
        int count = billTransferWriteMapper.insert(billTransfer);
        if (count == 0) {
            throw new MallException("添加结算转账记录表失败，请重试");
        }
        return count;
    }

    /**
     * 根据transferId删除结算转账记录表
     *
     * @param transferId transferId
     * @return
     */
    public Integer deleteBillTransfer(Integer transferId) {
        if (StringUtils.isEmpty(transferId)) {
            throw new MallException("请选择要删除的数据");
        }
        int count = billTransferWriteMapper.deleteByPrimaryKey(transferId);
        if (count == 0) {
            log.error("根据transferId：" + transferId + "删除结算转账记录表失败");
            throw new MallException("删除结算转账记录表失败,请重试");
        }
        return count;
    }

    /**
     * 根据transferId更新结算转账记录表
     *
     * @param billTransfer 结算转账记录信息
     * @return
     */
    public Integer updateBillTransfer(BillTransfer billTransfer) {
        if (StringUtils.isEmpty(billTransfer.getTransferId())) {
            throw new MallException("请选择要修改的数据");
        }
        int count = billTransferWriteMapper.updateByPrimaryKeySelective(billTransfer);
        if (count == 0) {
            log.error("根据transferId：" + billTransfer.getTransferId() + "更新结算转账记录表失败");
            throw new MallException("更新结算转账记录表失败,请重试");
        }
        return count;
    }

    /**
     * 根据transferId获取结算转账记录表详情
     *
     * @param transferId transferId
     * @return
     */
    public BillTransfer getBillTransferByTransferId(Integer transferId) {
        return billTransferReadMapper.getByPrimaryKey(transferId);
    }

    /**
     * 根据条件获取结算转账记录表列表
     *
     * @param example 查询条件信息
     * @param pager   分页信息
     * @return
     */
    public List<BillTransfer> getBillTransferList(BillTransferExample example, PagerInfo pager) {
        List<BillTransfer> billTransferList;
        if (pager != null) {
            pager.setRowsCount(billTransferReadMapper.countByExample(example));
            billTransferList = billTransferReadMapper.listPageByExample(example, pager.getStart(), pager.getPageSize());
        } else {
            billTransferList = billTransferReadMapper.listByExample(example);
        }
        return billTransferList;
    }

    /**
     * 执行转账
     * 此处加事务处理，防止重复打款或未打款情况
     *
     * @param transferAmount 转账金额
     * @param billSn 结算单号
     * @param storeId 店铺id
     */
    @Transactional
    public void transfer(BigDecimal transferAmount, String billSn, Long storeId) throws Exception {
        //查询该结算单是否已转账
        BillTransferExample billTransferExample = new BillTransferExample();
        billTransferExample.setBillSn(billSn);
        List<BillTransfer> billTransfers = billTransferWriteMapper.listByExample(billTransferExample);
        if (!CollectionUtils.isEmpty(billTransfers)){
            //已转账
            return;
        }

        SlodonPayRequest request = new SlodonPayRequest();
        request.setPayMethod(PayConst.METHOD_ZJ);
        request.setPayType("balance");
        request.setPaySn(billSn);
        request.setPayAmount(transferAmount);
        request.setNotifyUrl(DomainUrlUtil.SLD_ADMIN_URL);

        TxPayRequest txPayRequest = new TxPayRequest();
        txPayRequest.setInstitutionId(stringRedisTemplate.opsForValue().get("zj_pay_institution_id"));
        txPayRequest.setTxSn(GUIDGenerator.genGUID());
        txPayRequest.setPayerUserId("admin");//支付方为平台
        txPayRequest.setPayeeUserId(storeId.toString());//收款方为店铺
        txPayRequest.setHasSubsequentSplit("1");//无后续分账
        txPayRequest.setPaymentWay("00");
        txPayRequest.setGoodsName(stringRedisTemplate.opsForValue().get("basic_site_name"));
        request.setTxPayRequest(txPayRequest);

        //保存转账记录
        BillTransfer billTransfer = new BillTransfer();
        billTransfer.setBillSn(billSn);
        billTransfer.setStoreId(storeId);
        billTransfer.setTxSn(txPayRequest.getTxSn());
        billTransfer.setTransferAmount(transferAmount);
        billTransfer.setCreateTime(new Date());
        billTransferWriteMapper.insert(billTransfer);

        //转账
        slodonPay.unitePay(request);
    }
}