package com.gree.mall.miniapp.logic.material.withdrawal;

import com.gree.mall.miniapp.bean.user.CurrentCompanyWechat;
import com.gree.mall.miniapp.exception.RemoteServiceException;
import com.gree.mall.miniapp.logic.common.CommonLogic;
import com.gree.mall.miniapp.plus.entity.WorkerBank;
import com.gree.mall.miniapp.plus.service.WorkerBankService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Slf4j
@RequiredArgsConstructor
@Service
public class WorkerBankLogic {

    private final WorkerBankService workerBankService;
    private final CommonLogic commonLogic;


    public List<WorkerBank> list(){
        CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat();
        List<WorkerBank> list = workerBankService.lambdaQuery().eq(WorkerBank::getWorkerId, currentCompanyWechat.getUserId()).list();
        return list;
    }
    /**
     * 保存银行卡
     * @param workerBank
     */
    public void save(WorkerBank workerBank){
        CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat();
        Integer count = workerBankService.lambdaQuery()
                .ne(StringUtils.isNotBlank(workerBank.getId()),WorkerBank::getId,workerBank.getId())
                .eq(WorkerBank::getWorkerId, currentCompanyWechat.getUserId())
                .eq(WorkerBank::getBankNo, workerBank.getBankNo())
                .count();
        if(count > 0){
            throw new RemoteServiceException("请勿重复绑定相同的银行卡");
        }
        if(workerBank.getIdcard().length() != 18){
            throw new RemoteServiceException("请填写正确的身份证号");
        }
        workerBank.setWorkerId(currentCompanyWechat.getUserId());
        workerBank.setWorkerName(currentCompanyWechat.getUser().getNickName());
        workerBank.setIdcard(currentCompanyWechat.getUser().getIdCard());
        workerBank.setCreateTime(new Date());
        workerBank.setCreateBy(currentCompanyWechat.getUser().getNickName());
        workerBank.insertOrUpdate();
    }

    /**
     * 删除银行卡
     * @param id
     */
    public void delete(String id){
        workerBankService.removeById(id);
    }

    /**
     * 银行卡详情
     * @param id
     * @return
     */
    public WorkerBank detail(String id){
        return workerBankService.getById(id);
    }
}
