/*
 * 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.TfCarMaintenanceMapper;
import com.tofly.gpsboot.service.car.TfCarMaintenanceService;
import com.tofly.gpsboot.service.comm.IFileInfoService;
import com.tofly.pojo.car.TfCarMaintenance;
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("tfCarMaintenanceService")
public class TfCarMaintenanceServiceImpl extends ServiceImpl<TfCarMaintenanceMapper, TfCarMaintenance> implements TfCarMaintenanceService {

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

    @Autowired
    private IFileInfoService fileInfoService;

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

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

    @Override
    public boolean removeCarMaintenanceByIds(String ids) {
        List<Long> idList = Arrays.stream(ids.split(Constant.CSV)).map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
        idList.forEach(info ->{
            TfCarMaintenance 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;
    }
}
