package cn.stylefeng.team.form.api.parser;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.stylefeng.roses.kernel.file.api.FileInfoApi;
import cn.stylefeng.team.form.api.entity.FormItem;
import cn.stylefeng.team.form.api.parser.base.BaseFormFormat;
import com.alibaba.fastjson.JSON;

import java.util.List;

public class FormUploadFormat implements BaseFormFormat {

    @Override
    public Object formatProcess(FormItem formItem, Object originValue) {

        FileInfoApi fileInfoApi = SpringUtil.getBean(FileInfoApi.class);

        if (formItem == null || originValue == null) {
            return null;
        }

        Boolean itemMultipleChoiceFlag = formItem.getItemMultipleChoiceFlag();
        if (itemMultipleChoiceFlag == null) {
            return null;
        }

        if (!itemMultipleChoiceFlag) {
            return fileInfoApi.getFileUnAuthUrl(Long.valueOf(originValue.toString()));
        }

        StringBuilder result = new StringBuilder();
        List<Long> fileIdList = JSON.parseArray(originValue.toString(), Long.class);
        for (Long fileId : fileIdList) {
            result.append(fileInfoApi.getFileUnAuthUrl(fileId)).append(",");
        }

        return StrUtil.removeSuffix(result.toString(), ",");
    }

}
