package com.ruoyi.invest.service.impl;

import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.IdWorker;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.invest.domain.AccountsDealRecord;
import com.ruoyi.invest.domain.InstallmentHistory;
import com.ruoyi.invest.domain.InstallmentHistoryDetail;
import com.ruoyi.invest.domain.dto.InstallmentHistoryDetailDto;
import com.ruoyi.invest.domain.vo.AccountsVo;
import com.ruoyi.invest.domain.vo.InstallmentHistoryDetailVo;
import com.ruoyi.invest.domain.vo.InstallmentHistoryVo;
import com.ruoyi.invest.mapper.AccountsDealRecordMapper;
import com.ruoyi.invest.mapper.AccountsMapper;
import com.ruoyi.invest.mapper.InstallmentHistoryDetailMapper;
import com.ruoyi.invest.mapper.InstallmentHistoryMapper;
import com.ruoyi.invest.service.IInstallmentHistoryDetailService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 分期历史明细Service业务层处理
 *
 * @author tianyongbao
 * @date 2024-03-23
 */
@Service
public class InstallmentHistoryDetailServiceImpl implements IInstallmentHistoryDetailService
{
    @Resource
    private InstallmentHistoryDetailMapper installmentHistoryDetailMapper;
    @Resource
    private AccountsMapper accountsMapper;
    @Resource
    private AccountsDealRecordMapper accountsDealRecordMapper;

    @Resource
    private InstallmentHistoryMapper installmentHistoryMapper;

    /**
     * 查询分期历史明细
     *
     * @param id 分期历史明细主键
     * @return 分期历史明细
     */
    @Override
    public InstallmentHistoryDetailVo selectInstallmentHistoryDetailById(Long id)
    {
        return installmentHistoryDetailMapper.selectInstallmentHistoryDetailById(id);
    }

    /**
     * 查询分期历史明细列表
     *
     * @param installmentHistoryDetailDto 分期历史明细
     * @return 分期历史明细
     */
    @Override
    public List<InstallmentHistoryDetailVo> selectInstallmentHistoryDetailList(InstallmentHistoryDetailDto installmentHistoryDetailDto)
    {
        return installmentHistoryDetailMapper.selectInstallmentHistoryDetailList(installmentHistoryDetailDto);
    }

    /**
     * 新增分期历史明细
     *
     * @param installmentHistoryDetail 分期历史明细
     * @return 结果
     */
    @Override
    public int insertInstallmentHistoryDetail(InstallmentHistoryDetail installmentHistoryDetail)
    {
        installmentHistoryDetail.setCreateBy(SecurityUtils.getUsername());
        installmentHistoryDetail.setCreateTime(DateUtils.getNowDate());
        installmentHistoryDetail.setId(IdWorker.getId());
        //应还款金额=本金加利息
        installmentHistoryDetail.setCurrentAmount(installmentHistoryDetail.getPrincipal()+installmentHistoryDetail.getInterest());
        return installmentHistoryDetailMapper.insertInstallmentHistoryDetail(installmentHistoryDetail);
    }

    /**
     * 修改分期历史明细
     *
     * @param installmentHistoryDetail 分期历史明细
     * @return 结果
     */
    @Override
    public int updateInstallmentHistoryDetail(InstallmentHistoryDetail installmentHistoryDetail)
    {
        installmentHistoryDetail.setUpdateBy(SecurityUtils.getUsername());
        installmentHistoryDetail.setUpdateTime(DateUtils.getNowDate());
        //如果是已入账，更新主表已还期数。
        if("1".equals(installmentHistoryDetail.getPostingState())){
            //更新主表已还期数
            InstallmentHistoryVo historyVo=installmentHistoryMapper.selectInstallmentHistoryById(installmentHistoryDetail.getInstallmentHistoryId());
            InstallmentHistory his=new InstallmentHistory();
            his.setRepaidPeriod(historyVo.getRepaidPeriod()+1);
            his.setId(historyVo.getId());
            his.setUpdateTime(new Date());
            installmentHistoryMapper.updateInstallmentHistory(his);
        }
        //如果是信用卡分期
        if(installmentHistoryDetail.getType().equals("2")){
            //已入账
            Calendar cal1 = Calendar.getInstance();
            cal1.setTime(installmentHistoryDetail.getRepaymentDate());
            Calendar cal2 = Calendar.getInstance();
            cal2.setTime(new Date());
            long diffInMillis = cal2.getTimeInMillis() - cal1.getTimeInMillis();
            int daysDiff = Long.valueOf(TimeUnit.MILLISECONDS.toDays(diffInMillis)).intValue();
            //入账日期小于一个月的
            if("1".equals(installmentHistoryDetail.getPostingState())&&daysDiff<31){

                //信用卡账户余额计算
                AccountsVo creditAccount=accountsMapper.selectAccountsById(installmentHistoryDetail.getBankCardLendId());
                creditAccount.setBalance(creditAccount.getBalance()-installmentHistoryDetail.getInterest());
                creditAccount.setAvailableLimit(creditAccount.getBalance()+creditAccount.getCreditLimit());
                creditAccount.setUpdateTime(installmentHistoryDetail.getUpdateTime());
                accountsMapper.updateAccounts(creditAccount);

                //信用卡消费记录明细
                AccountsDealRecord creditDeal=new AccountsDealRecord();
                creditDeal.setTransferRecordId(installmentHistoryDetail.getId());
                creditDeal.setAccountId(creditAccount.getAccountId());
                creditDeal.setId(IdWorker.getId());
                //支出金额
                creditDeal.setAmount(installmentHistoryDetail.getInterest());
                //实时余额
                creditDeal.setCurrentBalance(creditAccount.getBalance());
                //1储蓄卡，2 信用卡，3 网贷，4 人情，5 投资账户
                creditDeal.setType("2");
                //1 收入，2 支出，3 转账，4 借贷
                creditDeal.setDealType("2");
                //分期利息支出
                creditDeal.setDealCategory("10");
                creditDeal.setName(creditAccount.getName()+"（"+ StringUtils.getLastNumberChars(4,creditAccount.getCode()+"）"));
                creditDeal.setRemark("分期利息");
                creditDeal.setCreateBy(SecurityUtils.getUsername());
                creditDeal.setCreateTime(installmentHistoryDetail.getUpdateTime());
                accountsDealRecordMapper.insertAccountsDealRecord(creditDeal);


                //信用卡消费记录明细，应还本金
                AccountsDealRecord creditDealPrinciple=new AccountsDealRecord();
                creditDealPrinciple.setTransferRecordId(installmentHistoryDetail.getId());
                creditDealPrinciple.setAccountId(creditAccount.getAccountId());
                creditDealPrinciple.setId(IdWorker.getId());
                //支出金额
                creditDealPrinciple.setAmount(installmentHistoryDetail.getPrincipal());
                //实时余额
                creditDealPrinciple.setCurrentBalance(creditAccount.getBalance());
                //1储蓄卡，2 信用卡，3 网贷，4 人情，5 投资账户
                creditDealPrinciple.setType("2");
                //1 收入，2 支出，3 转账，4 借贷
                creditDealPrinciple.setDealType("2");
                //分期利息支出
                creditDealPrinciple.setDealCategory("10");
                creditDealPrinciple.setName(creditAccount.getName()+"（"+ StringUtils.getLastNumberChars(4,creditAccount.getCode()+"）"));
                creditDealPrinciple.setRemark("应还本金");
                creditDealPrinciple.setCreateBy(SecurityUtils.getUsername());
                creditDealPrinciple.setCreateTime(installmentHistoryDetail.getUpdateTime());
                accountsDealRecordMapper.insertAccountsDealRecord(creditDealPrinciple);

            }
        }
        //应还款金额=本金加利息
        installmentHistoryDetail.setCurrentAmount(installmentHistoryDetail.getPrincipal()+installmentHistoryDetail.getInterest());
        return installmentHistoryDetailMapper.updateInstallmentHistoryDetail(installmentHistoryDetail);
    }

    /**
     * 批量删除分期历史明细
     *
     * @param ids 需要删除的分期历史明细主键
     * @return 结果
     */
    @Override
    public int deleteInstallmentHistoryDetailByIds(Long[] ids)
    {
        return installmentHistoryDetailMapper.removeInstallmentHistoryDetailByIds(ids);
    }

    /**
     * 删除分期历史明细信息
     *
     * @param id 分期历史明细主键
     * @return 结果
     */
    @Override
    public int deleteInstallmentHistoryDetailById(Long id)
    {
        return installmentHistoryDetailMapper.removeInstallmentHistoryDetailById(id);
    }
}
