package com.ruoyi.dk.service.impl;

import cn.dev33.satoken.secure.BCrypt;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.component.core.exception.ServiceException;
import com.ruoyi.component.mybatis.core.page.PageQuery;
import com.ruoyi.component.satoken.utils.LoginHelper;
import com.ruoyi.component.tenant.helper.TenantHelper;
import com.ruoyi.dk.domain.BorrowLog;
import com.ruoyi.dk.domain.Customer;
import com.ruoyi.dk.domain.CustomerInfo;
import com.ruoyi.dk.dto.admin.resp.CustomerAdminResp;
import com.ruoyi.dk.dto.app.req.CustomerRegisterReq;
import com.ruoyi.dk.mapper.BorrowLogMapper;
import com.ruoyi.dk.mapper.CustomerMapper;
import com.ruoyi.dk.service.CustomerInfoService;
import com.ruoyi.dk.service.CustomerService;
import com.ruoyi.component.core.exception.CustomException;
import com.ruoyi.component.core.util.MessageUtils;
import com.ruoyi.system.domain.vo.SysTenantVo;
import com.ruoyi.system.service.ISysTenantService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

@Service
public class CustomerServiceImpl extends ServiceImpl<CustomerMapper, Customer> implements CustomerService {
    @Autowired
    private CustomerInfoService customerInfoService;
    @Resource
    private BorrowLogMapper borrowLogMapper;
    @Autowired
    private ISysTenantService sysTenantService;
    @Override
    public Customer getCustomerByName(String mobile) {
        return this.getOne(Wrappers.lambdaQuery(Customer.class)
                .eq(Customer::getPhoneNumber,mobile)
                .last("limit 1"));
    }

    @Override
    public void register(CustomerRegisterReq register) {
        String phoneNumber = register.getPhoneNumber();
        Customer customer = this.getCustomerByName(phoneNumber);
        if(customer != null){
            throw new CustomException(MessageUtils.message("dk.user.already.having"));
        }
        SysTenantVo vo = sysTenantService.queryByTenantId(TenantHelper.getTenantId());
        if(vo == null){
            throw new ServiceException("未找到对应的平台错误");
        }
        customer = new Customer();
        customer.setUserCode(generateUserCode(vo.getPrefix()));
        customer.setPhoneNumber(phoneNumber);
        customer.setNickName(MessageUtils.message("dk.user.name")+phoneNumber.substring(phoneNumber.length() - 4));
        customer.setPassword(BCrypt.hashpw(register.getPassword()));
        this.save(customer);
        CustomerInfo customerInfo = new CustomerInfo();
        customerInfo.setCustomerId(customer.getId());
        customerInfoService.save(customerInfo);
    }

    private String generateUserCode(String prefix) {
        String userCode = prefix + "-" + RandomUtil.randomNumbers(6);
        boolean exists = this.exists(Wrappers.lambdaQuery(Customer.class).eq(Customer::getUserCode, userCode));
        if (exists) {
            this.generateUserCode(prefix);
        }
        return userCode;
    }

    @Override
    public boolean updatePwd(Long id, String password,boolean logout) {
        boolean update = this.update(Wrappers.lambdaUpdate(Customer.class)
                .eq(Customer::getId, id)
                .set(Customer::getPassword, BCrypt.hashpw(password)));
        if(update && logout){
            LoginHelper.logoutApp(id);
        }
        return update;
    }

    @Override
    public void borrowAmount(Long customerId, BigDecimal totalLoanMoney,BigDecimal totalRepayment) {
        baseMapper.incsAmount(customerId,totalLoanMoney,totalRepayment);
    }

    @Override
    public boolean withdraw(Long customerId, Double withdrawAmount) {
        baseMapper.withdraw(customerId,withdrawAmount);
        BorrowLog borrowLog = new BorrowLog();
        borrowLog.setWithdrawAccount(withdrawAmount);
        borrowLog.setCustomerId(customerId);
        borrowLogMapper.insert(borrowLog);
        this.update(Wrappers.lambdaUpdate(Customer.class)
                .eq(Customer::getId,customerId)
                .set(Customer::getWithdrawFlag,1));
        return true;
    }

    @Override
    public void dk(Long customerId){
        this.update(Wrappers.lambdaUpdate(Customer.class)
                .eq(Customer::getId,customerId)
                .set(Customer::getLoansFlag,1));
    }

    @Override
    public IPage<CustomerAdminResp> pageAdmin(PageQuery pageQuery, CustomerAdminResp bo) {
        return baseMapper.pageAdmin(pageQuery.build(),bo);
    }

    @Override
    public void loginOut(Long id) {
        LoginHelper.logoutApp(id);
    }
}
