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.opencsv.CSVReader;
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.enums.OssFileEnum;
import com.ruoyi.system.service.OssFileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.Objects;

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

    @Resource
    private OssFileService ossFileService;

    @Resource
    private CustCsvTagMapper custCsvTagMapper;

    private final static ObjectMapper objectMapper = new ObjectMapper();

    @Async
    public void processCsvInBatches(MultipartFile file, String userName, String headId) {
        log.info("开始执行CSV标签更新");
        try{
            InputStreamReader inputStreamReader = new InputStreamReader(file.getInputStream(), "UTF-8");
            CSVReader reader = new CSVReader(new BufferedReader(inputStreamReader));
            String[] headers = reader.readNext(); // 读取标题行
            String[] row;

            while ((row = reader.readNext()) != null) {
                JSONObject jsonObject = new JSONObject();
                String custIdc = null;
                for (int i = 0; i < headers.length; i++) {
                    jsonObject.put(headers[i], row[i]);
                    if (headers[i].equals("身份证")){
                        custIdc = row[i];
                    }
                }
                if (custIdc == null){
                    log.error("------------------------>CSV标签JSON上传出错：身份证为空");
                    continue;
                }
                updateCSVtoOSS(jsonObject, custIdc, userName, headId);
            }
        } catch (Exception e){
            log.error("------------------------>执行CSV标签出错：",e);
            throw new ServiceException("执行CSV标签出错：" + e.getMessage());
        }

    }

    private void updateCSVtoOSS(JSONObject jsonObject, String custIdc, String userName, String headId) {
        String fileId = writeJsonToOss(jsonObject, custIdc, userName);
        LambdaQueryWrapper<CustCsvTag> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CustCsvTag::getCustIdc, custIdc);
        queryWrapper.eq(CustCsvTag::getHeadId, headId);
        CustCsvTag custCsvTag = custCsvTagMapper.selectOne(queryWrapper);
        if (Objects.nonNull(custCsvTag)){
            ossFileService.deleteFileFromOss(custCsvTag.getFileId());
            log.info("删除旧文件：" + custCsvTag.getFileId());
            custCsvTagMapper.deleteById(custCsvTag);
        }
        custCsvTag = new CustCsvTag();
        custCsvTag.setCustIdc(custIdc);
        custCsvTag.setHeadId(headId);
        custCsvTag.setFileId(fileId);
        custCsvTag.setUpdateTime(new Date());
        custCsvTagMapper.insert(custCsvTag);
        log.info("CSV标签JSON保存成功：" + custIdc);
    }

    private String writeJsonToOss(JSONObject jsonObject, String fileNamePrefix, String userName) {
        File tempFile = null;
        try {
            tempFile = File.createTempFile(fileNamePrefix, ".json");
            String originalFileName = fileNamePrefix + ".json";
            objectMapper.writeValue(tempFile, jsonObject);
            return ossFileService.uploadFileToOss(OssFileEnum.CUST_CSV_TAG, tempFile, originalFileName, userName);
        }catch (Exception e){
            log.error("------------------------>CSV标签JSON上传出错：",e);
            throw new ServiceException("CSV标签JSON上传出错：" + e.getMessage());
        }finally {
            tempFile.delete();
        }
    }

    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());
        }
    }

}
