package com.ruoyi.frequency.givewallerecord.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.page.PageResult;
import com.ruoyi.controller.req.WalletPageReq;
import com.ruoyi.controller.resp.WalletPageResp;
import com.ruoyi.enums.WalletDetailEnums;
import com.ruoyi.enums.user.UserEnums;
import com.ruoyi.frequency.customer.mapper.CustomerMapper;
import com.ruoyi.response.ResponseData;
import com.ruoyi.utils.BusinessUtil;
import com.ruoyi.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.code.PublicCommon;
import com.ruoyi.frequency.givewallerecord.mapper.GiveWalletRecordMapper;
import com.ruoyi.frequency.givewallerecord.entity.GiveWalletRecord;
import com.ruoyi.frequency.givewallerecord.service.GiveWalletRecordService;

/**
 * 抵用金钱包记录Service业务层处理
 *
 * @author liwenlong
 * @date 2024-05-18
 */
@Service
public class GiveWalletRecordServiceImpl extends ServiceImpl<GiveWalletRecordMapper, GiveWalletRecord>  implements GiveWalletRecordService
{
    @Autowired
    private GiveWalletRecordMapper giveWalletRecordMapper;

    /**
     * 查询抵用金钱包记录
     *
     * @param id 抵用金钱包记录主键
     * @return 抵用金钱包记录
     */
    @Override
    public GiveWalletRecord selectGiveWalletRecordById(Long id)
    {
        return giveWalletRecordMapper.selectGiveWalletRecordById(id);
    }

    /**
     * 查询抵用金钱包记录列表
     *
     * @param giveWalletRecord 抵用金钱包记录
     * @return 抵用金钱包记录
     */
    @Override
    public List<GiveWalletRecord> selectGiveWalletRecordList(GiveWalletRecord giveWalletRecord)
    {
        return giveWalletRecordMapper.selectGiveWalletRecordList(giveWalletRecord);
    }

    /**
     * 新增抵用金钱包记录
     *
     * @param giveWalletRecord 抵用金钱包记录
     * @return 结果
     */
    @Override
    public int insertGiveWalletRecord(GiveWalletRecord giveWalletRecord)
    {
        giveWalletRecord.setCreateData();
        return giveWalletRecordMapper.insert(giveWalletRecord);
    }

    /**
     * 修改抵用金钱包记录
     *
     * @param giveWalletRecord 抵用金钱包记录
     * @return 结果
     */
    @Override
    public int updateGiveWalletRecord(GiveWalletRecord giveWalletRecord)
    {
        giveWalletRecord.setUpdateData();
        return giveWalletRecordMapper.updateGiveWalletRecord(giveWalletRecord);
    }

    /**
     * 批量删除抵用金钱包记录
     *
     * @param ids 需要删除的抵用金钱包记录主键
     * @return 结果
     */
    @Override
    public int deleteGiveWalletRecordByIds(Long[] ids,Integer delFlag)
    {
        this.lambdaUpdate().set(GiveWalletRecord::getDelFlag,delFlag).in(GiveWalletRecord::getId,ids).update();
        return ids.length;
    }

    @Autowired
    private CustomerMapper customerMapper;


    @Override
    public void updateGiveBalance(UserVo userVo, WalletDetailEnums walletDetailEnums, Long objectId, BigDecimal updatePrice, Integer status) {
        if (updatePrice.compareTo(BigDecimal.ZERO) == 0 || ObjectUtil.equal(PublicCommon.Wallet.到账取消, status)) {
            return;
        }

        switch (userVo.getUserType()) {
            case 1:
                if (updatePrice.compareTo(BigDecimal.ZERO) == 1) {
                    customerMapper.addGiveBalance(userVo.getUserId(), updatePrice);
                } else {
                    boolean subBalance = customerMapper.subGiveBalance(userVo.getUserId(), updatePrice.negate());
                    if (!subBalance) {
                        throw new CustomException(220, "抵用金不足");
                    }
                }
                break;
            case 2:
                break;
            case 3:
                break;
            default:
                throw new IllegalStateException("Unexpected value: " + userVo.getUserType());
        }
        //添加钱包记录
        addGiveWalletRecord(userVo, objectId, updatePrice, walletDetailEnums, null, status);
    }

    @Override
    public ResponseData<WalletPageResp> giveWalletPage(WalletPageReq req, UserVo userVo) {
        Page<WalletPageResp> page =  this.baseMapper.giveWalletPage(new Page<>(req.getPageNo(), req.getPageSize()), req, userVo);

        if (page.getRecords().size() > 0) {
            page.getRecords().stream().forEach(s -> {
                if (ObjectUtil.isNotEmpty(s.getRecordType())) {
                    s.setRecord(WalletDetailEnums.getName(s.getRecordType()));
                }
            });
        }

        // 查询分页结果
        return ResponseData.success(new PageResult<>(page));
    }

    @Autowired
    private BusinessUtil businessUtil;

    /**
     * 增加余额记录
     *
     * @param userVo            用户
     * @param walletDetailEnums 类型名称
     * @param orderId           订单id
     * @param price             金额
     */
    public void addGiveWalletRecord(UserVo userVo, Long orderId, BigDecimal price, WalletDetailEnums walletDetailEnums, String remark, Integer status) {
        if (price.setScale(2, BigDecimal.ROUND_HALF_UP).compareTo(new BigDecimal(0)) != 0) {
            GiveWalletRecord giveWalletRecord = new GiveWalletRecord();
            giveWalletRecord.setUserId(userVo.getUserId());
            giveWalletRecord.setUserType(userVo.getUserType());
            giveWalletRecord.setObjectId(orderId);
            giveWalletRecord.setStatus(status);
            giveWalletRecord.setRecordType(walletDetailEnums.getCode());
            giveWalletRecord.setPrice(price);

            if (ObjectUtil.equal(PublicCommon.Wallet.可提现, status)) {
                giveWalletRecord.setCanWithTime(new Date());
            } else if (ObjectUtil.equal(PublicCommon.Wallet.不可提现, status)) {
                giveWalletRecord.setNoWithTime(new Date());
            }

            //获取用户当前余额
            BigDecimal userGiveBalance = businessUtil.getUserGiveBalance(userVo);

            giveWalletRecord.setCurrentBalance(userGiveBalance);
            giveWalletRecord.setRemark(remark);

            this.save(giveWalletRecord);
        }
    }



}
