package com.loan.system.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import com.loan.system.domain.dto.CollateralDTO;
import com.loan.system.domain.entity.Collateral;
import com.loan.system.domain.vo.CollateralVO;
import com.loan.system.repository.CollateralRepository;
import com.loan.system.service.CollateralService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Service
public class CollateralServiceImpl implements CollateralService {
    private final CollateralRepository collateralRepository;

    @Autowired
    public CollateralServiceImpl(CollateralRepository collateralRepository) {
        this.collateralRepository = collateralRepository;
    }
    @Override
    public List<CollateralVO> findByCaseId(Long caseId) {
        return BeanUtil.copyToList(collateralRepository.findByCaseIdAndIsDelete(caseId,false), CollateralVO.class);
    }

    @Override
    public Collateral findCollateralByNameAndCaseId(String collateralName, Long caseId, boolean isDelete) {
        return collateralRepository.findCollateralByNameAndCaseId(collateralName, caseId, isDelete);
    }

    @Override
    public Collateral saveCollateral(CollateralDTO collateralDTO) {
        Collateral collateral = BeanUtil.copyProperties(collateralDTO, Collateral.class);
        collateral.setIsDelete( false);
        collateral.setCreateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        collateral.setUpdateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));

        return collateralRepository.save(collateral);
    }

    @Override
    public void updateCollateralById(Long id, CollateralDTO collateralDTO, boolean isDelete) {
        Collateral collateral = BeanUtil.copyProperties(collateralDTO, Collateral.class);
        collateral.setUpdateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        collateralRepository.updateCollateralById(id,collateral,isDelete);
    }

    @Override
    public void deleteAllByCaseId(Long caseId) {
        collateralRepository.deleteAllByCaseId(caseId);
    }
    @Override
    public void logic_delete(Long id) {
        collateralRepository.deleteById(id);
    }

    @Override
    public void updateCollateralStatusByid(Long id,String  status){
        collateralRepository.updateCollateralStatusByid(id,status);
    }
}
