/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.test.core.excel.converter;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.google.common.collect.Lists;
import com.jeeplus.test.wdt.merchantCompany.domain.MerchantProduct;
import com.jeeplus.test.wdt.merchantCompany.service.MerchantProductService;
import com.jeeplus.test.wdt.merchantCompany.service.dto.MerchantProductDTO;
import com.jeeplus.test.wdt.merchantCompany.service.mapstuct.MerchantProductWrapper;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 入驻产品类型转换
 *
 * @author jeeplus
 * @version 2016-03-10
 */

public class ExcelMerchantProductListDTOConverter implements Converter <List <MerchantProductDTO>> {

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

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

    @Override
    public List <MerchantProductDTO> convertToJavaData(ReadCellData <?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {

        List <MerchantProductDTO> postList = Lists.newArrayList ( );
        String val = cellData.getStringValue ( );
        for (String postName : StrUtil.split ( val, "," )) {
            MerchantProductDTO postDTO = MerchantProductWrapper.INSTANCE.toDTO ( SpringUtil.getBean ( MerchantProductService.class ).lambdaQuery ( ).eq ( MerchantProduct::getName, postName ).one ( ) );
            postList.add ( postDTO );
        }
        return postList.size ( ) > 0 ? postList : null;
    }

    @Override
    public WriteCellData <?> convertToExcelData(List <MerchantProductDTO> postDTOList, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
        List <String> postNames = postDTOList.stream ( ).map ( postDTO -> postDTO.getName ( ) ).collect ( Collectors.toList ( ) );
        return new WriteCellData <> ( StrUtil.join ( ",", postNames ) );
    }


}

