/*
 * Author: wangjian
 * 生成ServiceImpl
 */
package com.tofly.gpsboot.service.car.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tofly.gpsboot.common.Constant;
import com.tofly.gpsboot.mapper.car.TfCarInsuranceMapper;
import com.tofly.gpsboot.service.car.TfCarInsuranceService;
import com.tofly.gpsboot.service.comm.IFileInfoService;
import com.tofly.pojo.car.TfCarInsurance;
import com.tofly.pojo.comm.FileInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 车辆车险记录表
 *
 * @author JF
 * @date Mon Nov 25 00:00:00 CST 2024
 */
@Service("tfCarInsuranceService")
public class TfCarInsuranceServiceImpl extends ServiceImpl<TfCarInsuranceMapper, TfCarInsurance> implements TfCarInsuranceService {

    @Value("${xrty.ftp.carInsurancePath}")
    private String carInsurancePath;

    @Autowired
    private IFileInfoService fileInfoService;

    @Override
    public boolean saveCarInsurance(List<MultipartFile> fileList, TfCarInsurance carInsurance) {
        if (fileList != null && fileList.size() != 0) {
            List<FileInfo> annexFileInfo = fileInfoService.saveFileInfoList(fileList, carInsurancePath, "TF_CAR_INSURANCE");
            carInsurance.setAnnex(JSON.toJSONString(annexFileInfo));
        }
        // 对象入库
        this.save(carInsurance);
        return true;
    }

    @Override
    public boolean updateCarInsurance(List<MultipartFile> fileList, TfCarInsurance carInsurance) {
        TfCarInsurance query = this.getById(carInsurance.getId());
        String agoAnnexFileInfo = query.getAnnex();
        String newAnnex = fileInfoService.getNewAnnex(carInsurance.getAnnex(), fileList, agoAnnexFileInfo, carInsurancePath, "TF_CAR_INSURANCE");
        carInsurance.setAnnex(newAnnex);
        return this.updateById(carInsurance);
    }

    @Override
    public boolean removeCarInsuranceByIds(String ids) {
        List<Long> idList = Arrays.stream(ids.split(Constant.CSV)).map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
        idList.forEach(info ->{
            TfCarInsurance carInsurance = this.getById(info);
            String annex = carInsurance.getAnnex();
            if (StringUtils.isNotBlank(annex)) {
                List<FileInfo> fileInfoList = JSON.parseArray(annex, FileInfo.class);
                fileInfoService.removeFileInfoList(fileInfoList);
            }
        });
        this.removeByIds(idList);
        return true;
    }
}
