package com.pj.api.open.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.pj.current.config.SystemObject;
import com.pj.current.task.Task;
import com.pj.project.tb_business_car.TbBusinessCar;
import com.pj.project.tb_business_car.TbBusinessCarService;
import com.pj.project4sp.uploadfile.UploadConfig;
import com.pj.utils.ImageUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import java.io.File;

@Slf4j
public class CoverBase64ToImageTask extends Task {
    private String carId;
    private String imageData;
    private int inOrOut;

    public CoverBase64ToImageTask(String id, long delayInMilliseconds, String carId, String imageData, int inOrOut) {
        super(id, delayInMilliseconds);
        this.carId = carId;
        this.imageData = imageData;
        this.inOrOut = inOrOut;
    }

    @Override
    public void run() {
        UploadConfig uploadConfig = SpringUtil.getBean(UploadConfig.class);
        TbBusinessCarService tbBusinessCarService = SpringUtil.getBean(TbBusinessCarService.class);
        String flieTypeFolder = "/channel/";
        String currDateFolder = DateUtil.today();
        String fileName = RandomUtil.randomString(32) + ".jpg";
        String imgFilePath = new File(uploadConfig.rootFolder).getAbsolutePath() + "/" +
                uploadConfig.httpPrefix + flieTypeFolder + currDateFolder + "/";
        if (!FileUtil.exist(imgFilePath)){
            FileUtil.mkdir(imgFilePath);
        }
        // 对外暴露的http路径
        String httpUrl = SystemObject.config.getDomain() + uploadConfig.httpPrefix + flieTypeFolder + currDateFolder + "/" + fileName;
        ImageUtils.generateImage(imageData, imgFilePath + fileName);
        TbBusinessCar tbBusinessCar = tbBusinessCarService.getById(carId);
        if (tbBusinessCar != null) {
            if (inOrOut == 1) {
                tbBusinessCar.setInImage(httpUrl);
            } else {
                tbBusinessCar.setOutImage(httpUrl);
            }
        }
        tbBusinessCarService.updateById(tbBusinessCar);
    }
}
