package com.leromro.core.facade;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.leromro.common.core.domain.R;
import com.leromro.common.core.domain.entity.SysUser;
import com.leromro.common.core.redis.RedisCache;
import com.leromro.common.enums.ConstantsKey;
import com.leromro.common.exception.ServiceException;
import com.leromro.common.utils.SecurityUtils;
import com.leromro.core.domain.VolunteerPaymentRecords;
import com.leromro.core.domain.dto.WithdrawPaymentDTO;
import com.leromro.core.service.IVolunteerPaymentRecordsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class VolunteerPaymentRecordsFacade {

    @Autowired
    private IVolunteerPaymentRecordsService volunteerPaymentRecordsService;

    @Autowired
    private RedisCache redisCache;

    /**
     * 打款单验证
     */
    public R payoutCheck(WithdrawPaymentDTO dto) {
        //校验是否有打款权限
        SysUser user = SecurityUtils.getLoginUser().getUser();
        if (user.getDeptId() != 100){
            return R.fail("当前用户没有打款权限");
        }
        //todo 校验短信
        //新增，则校验手机号
        String redisCode = this.redisCache.getCacheObject(ConstantsKey.REDIS_PHONE_CODE.getKey() + "_" + user.getPhonenumber());
        if (StrUtil.isBlank(redisCode)) {
            return R.fail("验证码已过期");
        }
        if (!redisCode.equals(dto.getPayPassword())) {
            return R.fail("验证码错误");
        }
        //查询打款单，查看是否已经打款
        VolunteerPaymentRecords paymentRecords = volunteerPaymentRecordsService.getById(dto.getVolunteerPaymentRecordsId());
        if (ObjectUtil.isNull(paymentRecords)){
            return R.fail("打款单不存在");
        }
        if (!"1".equals(paymentRecords.getPaymentStatus())){
            return R.fail("该打款单状态错误");
        }
        if ("1".equals(paymentRecords.getIsVerified())){
            return R.fail("该打款单已经验证");
        }
        paymentRecords.setIsVerified("1");
        paymentRecords.setPaymentStatus("1");
        paymentRecords.setPaymentTime(new Date());
        volunteerPaymentRecordsService.updateById(paymentRecords);
        //异步执行打款
        volunteerPaymentRecordsService.asyncPayment(dto.getVolunteerPaymentRecordsId());
        return R.ok();
    }
}
