/**
 * 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.SettledPlatform;
import com.jeeplus.test.wdt.merchantCompany.service.SettledPlatformService;
import com.jeeplus.test.wdt.merchantCompany.service.dto.SettledPlatformDTO;
import com.jeeplus.test.wdt.merchantCompany.service.mapstuct.SettledPlatformWrapper;

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

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

public class ExcelSettledPlatformListDTOConverter implements Converter <List <SettledPlatformDTO>> {

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

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

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

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

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


}

