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.InstallmentHistory;
import com.ruoyi.invest.domain.InstallmentHistoryDetail;
import com.ruoyi.invest.domain.dto.InstallmentHistoryDetailDto;
import com.ruoyi.invest.domain.dto.InstallmentHistoryDto;
import com.ruoyi.invest.domain.vo.InstallmentHistoryDetailVo;
import com.ruoyi.invest.domain.vo.InstallmentHistoryVo;
import com.ruoyi.invest.mapper.InstallmentHistoryDetailMapper;
import com.ruoyi.invest.mapper.InstallmentHistoryMapper;
import com.ruoyi.invest.service.IInstallmentHistoryService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * 网贷及分期历史Service业务层处理
 *
 * @author tianyongbao
 * @date 2024-03-20
 */
@Service
public class InstallmentHistoryServiceImpl implements IInstallmentHistoryService
{
    @Resource
    private InstallmentHistoryMapper installmentHistoryMapper;

    @Resource
    private InstallmentHistoryDetailMapper installmentHistoryDetailMapper;

    /**
     * 查询网贷及分期历史
     *
     * @param id 网贷及分期历史主键
     * @return 网贷及分期历史
     */
    @Override
    public InstallmentHistoryVo selectInstallmentHistoryById(Long id)
    {
        return installmentHistoryMapper.selectInstallmentHistoryById(id);
    }

    /**
     * 查询网贷及分期历史列表
     *
     * @param installmentHistoryDto 网贷及分期历史
     * @return 网贷及分期历史
     */
    @Override
    public List<InstallmentHistoryVo> selectInstallmentHistoryList(InstallmentHistoryDto installmentHistoryDto)
    {
        List<InstallmentHistoryVo> installmentHistoryVoList=installmentHistoryMapper.selectInstallmentHistoryList(installmentHistoryDto);
        //修改名称加卡号
        DecimalFormat decimalFormat = new DecimalFormat("#.##");
        for (InstallmentHistoryVo installmentHistory : installmentHistoryVoList) {
            if(installmentHistory.getBankCode()!=null){
                installmentHistory.setBankNameCode(installmentHistory.getBankName()+"（"+ StringUtils.getLastNumberChars(4,installmentHistory.getBankCode()+"）"));
            }else {
                installmentHistory.setBankNameCode(installmentHistory.getBankName());
            }
            double interest=installmentHistory.getTotalInterest();
            double interestRate=0;
            if(interest>0){
                interestRate=interest/installmentHistory.getInstallmentAmount();
                if(installmentHistory.getPeriod()!=null){
                    interestRate=interestRate*12/installmentHistory.getPeriod();
                }
            }
            interestRate=interestRate*100;
            String calculateInterestRate= decimalFormat.format(interestRate)+"%";
            installmentHistory.setCalculateInterestRate(calculateInterestRate);
        }
        return installmentHistoryVoList;
    }

    /**
     * 新增网贷及分期历史
     *
     * @param installmentHistory 网贷及分期历史
     * @return 结果
     */
    @Override
    public int insertInstallmentHistory(InstallmentHistory installmentHistory)
    {
        installmentHistory.setCreateBy(SecurityUtils.getUsername());
        installmentHistory.setCreateTime(DateUtils.getNowDate());
        installmentHistory.setId(IdWorker.getId());
        if(installmentHistory.getInstallmentDate()!=null){
            //4表示是人情，不需要账单相关
            if(!"4".equals(installmentHistory.getType())){
            Calendar calendarStart = Calendar.getInstance();
            calendarStart.setTime(installmentHistory.getInstallmentDate());
            //如果是信用卡，第一期账单是分期日期，如果是网点，第一期账单是下个月
            if(installmentHistory.getType().equals("2")){
            calendarStart.add(Calendar.MONTH, installmentHistory.getPeriod()-1);
            }else if(installmentHistory.getType().equals("3")){
                calendarStart.add(Calendar.MONTH, installmentHistory.getPeriod());
            }
                installmentHistory.setDueDate(calendarStart.getTime());
            //如果已还期数与分期期数相等，表示已还完
            if(installmentHistory.getPeriod().equals(installmentHistory.getRepaidPeriod())){
                if(installmentHistory.getCloseDate()==null){
                  installmentHistory.setCloseDate(calendarStart.getTime());
                }
            }
                //插入分期明细
                insertInstallmentHistoryDetail(installmentHistory);
            }
        }
        return installmentHistoryMapper.insertInstallmentHistory(installmentHistory);
    }

    /**
     * 新增明细信息
     *
     * @param
     */
    public void insertInstallmentHistoryDetail(InstallmentHistory installmentHistory)
    {
        List<InstallmentHistoryDetail> detailList=new ArrayList<>();
        Long id = installmentHistory.getId();
        DecimalFormat decimalFormat = new DecimalFormat("#.##");
            for (int i=1;i<=installmentHistory.getPeriod();i++)
            {
                InstallmentHistoryDetail detail=new InstallmentHistoryDetail();
                detail.setInstallmentHistoryId(id);
                detail.setId(IdWorker.getId());
                detail.setBankCardLendId(installmentHistory.getBankCardLendId());
                Calendar calendarStart = Calendar.getInstance();
                calendarStart.setTime(installmentHistory.getInstallmentDate());
                //如果是信用卡，第一期账单是分期日期，如果是网点，第一期账单是下个月
                if(installmentHistory.getType().equals("2")){
                    calendarStart.add(Calendar.MONTH, i-1);
                }else if(installmentHistory.getType().equals("3")){
                    calendarStart.add(Calendar.MONTH, i);
                }
                double pricipal=Double.parseDouble(decimalFormat.format(installmentHistory.getInstallmentAmount()/installmentHistory.getPeriod()));
                double interest=Double.parseDouble(decimalFormat.format(installmentHistory.getTotalInterest()/installmentHistory.getPeriod()));
                detail.setPrincipal(pricipal);
                detail.setInterest(interest);
                detail.setCurrentAmount(pricipal+interest);
                detail.setRepaymentDate(calendarStart.getTime());
                detail.setPeriods(i);
                detail.setType(installmentHistory.getType());
                detail.setDelFlag("0");
                detail.setPostingState("0");
                detail.setCreateBy(SecurityUtils.getUsername());
                detail.setCreateTime(DateUtils.getNowDate());
                installmentHistoryDetailMapper.insertInstallmentHistoryDetail(detail);
            }


    }

    /**
     * 修改网贷及分期历史
     *
     * @param installmentHistory 网贷及分期历史
     * @return 结果
     */
    @Override
    public int updateInstallmentHistory(InstallmentHistory installmentHistory)
    {
        installmentHistory.setUpdateBy(SecurityUtils.getUsername());
        installmentHistory.setUpdateTime(DateUtils.getNowDate());
        if(installmentHistory.getInstallmentDate()!=null){
            if(!"4".equals(installmentHistory.getType())){
                Calendar calendarStart = Calendar.getInstance();
                calendarStart.setTime(installmentHistory.getInstallmentDate());
                if(installmentHistory.getType().equals("2")){
                    calendarStart.add(Calendar.MONTH, installmentHistory.getPeriod()-1);
                }else if(installmentHistory.getType().equals("3")){
                    calendarStart.add(Calendar.MONTH, installmentHistory.getPeriod());
                }
                installmentHistory.setDueDate(calendarStart.getTime());
                //如果已还期数与分期期数相等，表示已还完
                if(installmentHistory.getPeriod().equals(installmentHistory.getRepaidPeriod())){
                    if(installmentHistory.getCloseDate()==null){
                        installmentHistory.setCloseDate(calendarStart.getTime());
                    }
                }

              //更新利率信息
               updateInterestRate(installmentHistory);
            }
        }
        return installmentHistoryMapper.updateInstallmentHistory(installmentHistory);
    }

    /**
     * 更新利率
     *
     * @param
     */
    public void updateInterestRate(InstallmentHistory installmentHistory)
    {
        DecimalFormat decimalFormat = new DecimalFormat("#.##");

        InstallmentHistoryDetailDto installmentHistoryDetailDto=new InstallmentHistoryDetailDto();
        installmentHistoryDetailDto.setInstallmentHistoryId(installmentHistory.getId());
        List<InstallmentHistoryDetailVo> detailList=installmentHistoryDetailMapper.selectInstallmentHistoryDetailList(installmentHistoryDetailDto);
        double interest =0;
        double interestRate=0;
        if(detailList.size()>0){
            interest =   detailList.stream().mapToDouble(InstallmentHistoryDetailVo::getInterest).sum();
        }
        if(interest==0){
            interest=installmentHistory.getTotalInterest();
        }
        if(interest>0){
            interestRate=interest/installmentHistory.getInstallmentAmount();
            if(installmentHistory.getPeriod()!=null){
                interestRate=interestRate*12/installmentHistory.getPeriod();
            }
        }
        interestRate=interestRate*100;
        String calculateInterestRate= decimalFormat.format(interestRate)+"%";
        installmentHistory.setCalculateInterestRate(calculateInterestRate);
    }

    /**
     * 批量删除网贷及分期历史
     *
     * @param ids 需要删除的网贷及分期历史主键
     * @return 结果
     */
    @Override
    public int deleteInstallmentHistoryByIds(Long[] ids)
    {
        return installmentHistoryMapper.removeInstallmentHistoryByIds(ids);
    }

    /**
     * 删除网贷及分期历史信息
     *
     * @param id 网贷及分期历史主键
     * @return 结果
     */
    @Override
    public int deleteInstallmentHistoryById(Long id)
    {
        return installmentHistoryMapper.removeInstallmentHistoryById(id);
    }
}
