package com.zbkj.service.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zbkj.common.exception.CrmebException;
import com.zbkj.common.model.bcx.BcxSettleBill;
import com.zbkj.common.model.bcx.BcxUserBank;
import com.zbkj.common.page.CommonPage;
import com.zbkj.common.request.BcxUserAddBankCardRequest;
import com.zbkj.common.request.BcxUserEditBankCardRequest;
import com.zbkj.common.request.BcxUserOperateBankCardRequest;
import com.zbkj.common.request.PageParamRequest;
import com.zbkj.common.result.CommonResultCode;
import com.zbkj.common.utils.IdGeneratorSnowflake;
import com.zbkj.service.dao.BcxUserBankDao;
import com.zbkj.service.service.BcxUserBankService;
import com.zbkj.service.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * description：用户绑定银行卡表 服务接口
 * author：linchunpeng
 * date：2023/11/1
 */
@Service
public class BcxUserBankServiceImpl extends ServiceImpl<BcxUserBankDao, BcxUserBank> implements BcxUserBankService {
    
    @Resource
    private BcxUserBankDao dao;
    @Autowired
    private UserService userService;
    @Autowired
    private IdGeneratorSnowflake snowflake;


    /**
     * description：获取银行卡列表
     * author：linchunpeng
     * date：2023/11/1
     */
    @Override
    public PageInfo<BcxUserBank> getPage(PageParamRequest pageParamRequest) {
        Integer userId = userService.getUserId();
        LambdaQueryWrapper<BcxUserBank> lqw = Wrappers.lambdaQuery();
        lqw.eq(BcxUserBank::getUid, userId);
        lqw.orderByAsc(BcxUserBank::getCreateTime);
        Page<BcxSettleBill> page = PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        List<BcxUserBank> bankList = dao.selectList(lqw);
        return CommonPage.copyPageInfo(page, bankList);
    }

    /**
     * description：绑定银行卡
     * author：linchunpeng
     * date：2023/11/1
     */
    @Override
    @Transactional
    public Boolean bindBankCard(BcxUserAddBankCardRequest request) {
        Integer userId = userService.getUserId();
        BcxUserBank exist = this.getByBankCardNo(request.getBankCardNo());
        if (exist != null) {
            throw new CrmebException(CommonResultCode.ERROR.setMessage("该银行卡号已经被绑定，请重新输入"));
        }
        BcxUserBank userBank = new BcxUserBank();
        BeanUtils.copyProperties(request, userBank);
        userBank.setId(snowflake.snowflakeId());
        userBank.setUid(userId);
        userBank.setStatus(1);
        userBank.setCreateTime(new Date());
        userBank.setUpdateTime(new Date());
        //判断是否默认，是，还需要请修改该用户的其他银行为非默认，不是，判断有没有其他银行卡，没有需要强制默认
        checkDefault(userId, userBank);
        this.save(userBank);
        return true;
    }



    /**
     * description：编辑银行卡
     * author：linchunpeng
     * date：2023/11/1
     */
    @Override
    @Transactional
    public Boolean editBankCard(BcxUserEditBankCardRequest request) {
        Integer userId = userService.getUserId();
        BcxUserBank exist = this.getByBankCardNo(request.getBankCardNo());
        if (exist != null && exist.getId().longValue() != request.getId().longValue()) {
            throw new CrmebException(CommonResultCode.ERROR.setMessage("该银行卡号已经被绑定，请重新输入"));
        }
        BcxUserBank userBank = this.getById(request.getId());
        if (userBank == null) {
            throw new CrmebException(CommonResultCode.ERROR.setMessage("要修改的银行卡不存在"));
        }
        if (userBank.getUid().intValue() != userId.intValue()) {
            throw new CrmebException(CommonResultCode.ERROR.setMessage("只能修改自己的银行卡"));
        }
        BeanUtils.copyProperties(request, userBank);
        userBank.setUpdateTime(new Date());
        //判断是否默认，是，还需要请修改该用户的其他银行为非默认，不是，判断有没有其他银行卡，没有需要强制默认
        checkDefault(userId, userBank);
        this.updateById(userBank);
        return true;
    }

    /**
     * description：设置默认银行卡
     * author：linchunpeng
     * date：2023/11/1
     */
    @Override
    @Transactional
    public Boolean setBankCardDefault(BcxUserOperateBankCardRequest request) {
        Integer userId = userService.getUserId();
        BcxUserBank userBank = this.getById(request.getId());
        if (userBank == null) {
            throw new CrmebException(CommonResultCode.ERROR.setMessage("要设置的银行卡不存在"));
        }
        if (userBank.getUid().intValue() != userId.intValue()) {
            throw new CrmebException(CommonResultCode.ERROR.setMessage("只能设置自己的银行卡"));
        }
        userBank.setIsDefault(1);
        userBank.setUpdateTime(new Date());
        //还需要请修改该用户的其他银行为非默认
        checkDefault(userId, userBank);
        this.updateById(userBank);
        return true;
    }

    /**
     * description：解绑银行卡
     * author：linchunpeng
     * date：2023/11/1
     */
    @Override
    @Transactional
    public Boolean unbindBankCard(BcxUserOperateBankCardRequest request) {
        Integer userId = userService.getUserId();
        BcxUserBank userBank = this.getById(request.getId());
        if (userBank == null) {
            throw new CrmebException(CommonResultCode.ERROR.setMessage("要删除的银行卡不存在"));
        }
        if (userBank.getUid().intValue() != userId.intValue()) {
            throw new CrmebException(CommonResultCode.ERROR.setMessage("只能删除自己的银行卡"));
        }
        if (userBank.getIsDefault() == 1) {
            //要删除的是默认的，需要随机指定其他银行卡为默认
            List<BcxUserBank> bankList = this.getByUid(userId);
            if (CollectionUtil.isNotEmpty(bankList)) {
                //不是要删除的这条银行卡
                Optional<BcxUserBank> bcxUserBankOptional = bankList.stream().filter(bank -> bank.getId().longValue() != userBank.getId().longValue()).findFirst();
                if (bcxUserBankOptional.isPresent()) {
                    BcxUserBank bcxUserBank = bcxUserBankOptional.get();
                    bcxUserBank.setIsDefault(1);
                    bcxUserBank.setUpdateTime(new Date());
                    this.updateById(bcxUserBank);
                }
            }
        }
        this.removeById(userBank.getId());
        return true;
    }

    /**
     * description：根据银行卡号查询
     * author：linchunpeng
     * date：2023/11/1
     */
    private BcxUserBank getByBankCardNo(String bankCardNo) {
        LambdaQueryWrapper<BcxUserBank> lqw = Wrappers.lambdaQuery();
        lqw.eq(BcxUserBank::getBankCardNo, bankCardNo);
        return dao.selectOne(lqw);
    }

    /**
     * description：根据银行卡号查询
     * author：linchunpeng
     * date：2023/11/1
     */
    private List<BcxUserBank> getByUid(Integer uid) {
        LambdaQueryWrapper<BcxUserBank> lqw = Wrappers.lambdaQuery();
        lqw.eq(BcxUserBank::getUid, uid);
        return dao.selectList(lqw);
    }

    /**
     * description：判断是否默认，是，还需要请修改该用户的其他银行为非默认，不是，判断有没有其他银行卡，没有需要强制默认
     * author：linchunpeng
     * date：2023/11/1
     */
    private void checkDefault(Integer userId, BcxUserBank userBank) {
        List<BcxUserBank> bankList = this.getByUid(userId);
        //判断是否默认
        if (userBank.getIsDefault() == 1) {
            //是，还需要请修改该用户的其他银行为非默认
            if (CollectionUtil.isNotEmpty(bankList)) {
                for (BcxUserBank bcxUserBank : bankList) {
                    bcxUserBank.setIsDefault(0);
                }
            }
            this.updateBatchById(bankList);
        } else {
            //不是，判断有没有其他银行卡，没有需要强制默认
            if (CollectionUtil.isEmpty(bankList)) {
                userBank.setIsDefault(1);
            }
        }
    }
}