package com.cool.store.converter;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.alibaba.fastjson.JSON;
import com.cool.store.vo.order.OrderDeviceConfigItemVO;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @Auther zx_szh
 * @Date 2026/4/3 09:30
 * @Version 1.0
 */
public class ConfigItemListConverter implements Converter<List<OrderDeviceConfigItemVO>> {

    @Override
    public Class<?> supportJavaTypeKey() {
        return List.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }


    @Override
    public List<OrderDeviceConfigItemVO> convertToJavaData(CellData cellData,
                                                           ExcelContentProperty contentProperty,
                                                           GlobalConfiguration globalConfiguration) {
        String cellValue = cellData.getStringValue();
        if (!StringUtils.hasText(cellValue)) {
            return new ArrayList<>();
        }

        // 将 JSON 字符串解析为 List
        return JSON.parseArray(cellValue, OrderDeviceConfigItemVO.class);
    }

    /**
     * 导出 Excel 时：将 List 对象转换为字符串写入单元格
     * 导出时使用
     */
    @Override
    public CellData convertToExcelData(List<OrderDeviceConfigItemVO> value,
                                                    ExcelContentProperty contentProperty,
                                                    GlobalConfiguration globalConfiguration) {
        if (value == null || value.isEmpty()) {
            return new CellData<>("");
        }

        // 将 List 转换为 JSON 字符串
        String jsonString = JSON.toJSONString(value);
        return new CellData<>(jsonString);
    }

}
