package com.ruoyi.ibs.customerselect.service;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.ibs.customerselect.domain.CustCsvTag;
import com.ruoyi.ibs.customerselect.mapper.CustCsvTagMapper;
import com.ruoyi.system.service.OssFileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @Author 吴凯程
 * @Date 2025/11/27
 **/
@Service
@Slf4j
@EnableAsync
public class CustCsvTagService {

    private final static ObjectMapper objectMapper = new ObjectMapper();
    @Resource
    private OssFileService ossFileService;
    @Resource
    private CustCsvTagMapper custCsvTagMapper;

    public JSONObject getCsvTagJson(String custIdc) {
        LambdaQueryWrapper<CustCsvTag> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CustCsvTag::getCustIdc, custIdc);
        queryWrapper.eq(CustCsvTag::getHeadId, SecurityUtils.getHeadId());
        CustCsvTag custCsvTag = custCsvTagMapper.selectOne(queryWrapper);
        if (Objects.isNull(custCsvTag)){
            return null;
        }
        MultipartFile fileFromOss = ossFileService.getFileFromOss(custCsvTag.getFileId());
        try {
            return objectMapper.readValue(fileFromOss.getBytes(), JSONObject.class);
        } catch (Exception e) {
            log.error("------------------------>CSV标签JSON读取出错：",e);
            throw new ServiceException("CSV标签JSON读取出错：" + e.getMessage());
        }
    }

}
