package com.ylx.massage.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ylx.common.exception.ServiceException;
import com.ylx.massage.domain.TConsumptionLog;
import com.ylx.massage.domain.TJs;
import com.ylx.massage.domain.TTxRecord;
import com.ylx.massage.domain.TWxUser;
import com.ylx.massage.enums.TTxRecordEnum;
import com.ylx.massage.mapper.TTxRecordMapper;
import com.ylx.massage.service.TConsumptionLogService;
import com.ylx.massage.service.TJsService;
import com.ylx.massage.service.TTxRecordService;
import com.ylx.massage.service.TWxUserService;
import com.ylx.massage.utils.OrderNumberGenerator;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;


/**
 * 提现表 服务实现类
 */
@Service
public class TTxRecordServiceImpl extends ServiceImpl<TTxRecordMapper, TTxRecord> implements TTxRecordService {

    @Resource
    private TWxUserService wxUserService;

    @Resource
    private OrderNumberGenerator orderNumberGenerator;

    @Resource
    private TConsumptionLogService consumptionLogService;

    @Resource
    private TJsService jsService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public TTxRecord applicationCash(TTxRecord record) {
        if (StringUtils.isBlank(record.getcOpenId())) {
            throw new ServiceException("OpenID不能为空");
        }
        LambdaQueryWrapper<TTxRecord> tTxRecordLambdaQueryWrapper = new LambdaQueryWrapper<>();
        tTxRecordLambdaQueryWrapper.eq(TTxRecord::getcOpenId, record.getcOpenId())
                .eq(TTxRecord::getnStatus, TTxRecordEnum.PASS_ING.getCode());
        List<TTxRecord> list = this.list(tTxRecordLambdaQueryWrapper);
        if (CollectionUtil.isNotEmpty(list)) {
            throw new ServiceException("提现申请正在审核中，请勿重复申请");
        }
        if (StringUtils.isBlank(record.getOpeningBank())) {
            throw new ServiceException("开户行不能为空");
        }
        if (StringUtils.isBlank(record.getBankAccount())) {
            throw new ServiceException("银行账号不能为空");
        }

        TWxUser user = wxUserService.getByOpenId(record.getcOpenId());
        if (null == record.getdPrice() || record.getdPrice().compareTo(BigDecimal.ZERO) <= 0) {
            throw new ServiceException("提现金额不能为空");
        }

        if (record.getdPrice().compareTo(user.getdBalance()) > 0) {
            throw new ServiceException("提现金额不能大于钱包余额");
        }
        if (record.getdPrice().compareTo(user.getGetAmount()) > 0) {
            throw new ServiceException("提现金额不能大于可提现金额");
        }
        LambdaQueryWrapper<TJs> mhCompanyLambdaQueryWrapper = new LambdaQueryWrapper<>();
        mhCompanyLambdaQueryWrapper.eq(TJs::getcOpenId, record.getcOpenId());
        TJs js = jsService.getOne(mhCompanyLambdaQueryWrapper);

        record.setDeptId(js.getDeptId());
        record.setDeptName(js.getCity());
        record.setcName(js.getcName());
        record.setcPhone(js.getcPhone());
        record.setnStatus(TTxRecordEnum.PASS_ING.getCode());
        record.setDtCreateTime(LocalDateTime.now());
        record.setCashNo(orderNumberGenerator.generateNextOrderNumber(OrderNumberGenerator.KEY_PREFIX_CASH));
        this.save(record);
        return record;
    }

    @Override
    public Object auditing(TTxRecord record) {
        boolean b = this.updateById(record);
        TTxRecord byId = this.getById(record.getcId());
        if (Objects.equals(record.getnStatus(), TTxRecordEnum.PASS.getCode())) {
            extracted(byId);
        }
        return b;
    }

    private void extracted(TTxRecord record) {
        UpdateWrapper<TWxUser> businessUpdateWrapper = new UpdateWrapper<>();
        businessUpdateWrapper.lambda().eq(TWxUser::getcOpenid, record.getcOpenId());
        businessUpdateWrapper.lambda().setSql(" d_balance = d_balance - " + record.getdPrice());
        businessUpdateWrapper.lambda().setSql(" get_amount = get_amount - " + record.getdPrice());
        wxUserService.update(businessUpdateWrapper);

        //余额记录
        TConsumptionLog tConsumptionLog = new TConsumptionLog();
        tConsumptionLog.setAmount(record.getdPrice().negate());
        tConsumptionLog.setBillNo(record.getCashNo());
        tConsumptionLog.setOpenId(record.getcOpenId());
        tConsumptionLog.setBillType(4);
        tConsumptionLog.setNote("提现");
        consumptionLogService.save(tConsumptionLog);
    }
}
