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

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.stylefeng.roses.kernel.dict.api.DictApi;
import cn.stylefeng.team.form.api.entity.FormItem;
import cn.stylefeng.team.form.api.entity.FormItemSelect;
import cn.stylefeng.team.form.api.enums.DictValueEnum;
import cn.stylefeng.team.form.api.parser.base.BaseFormFormat;
import com.alibaba.fastjson.JSON;

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

public class FormCheckBoxFormat implements BaseFormFormat {

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

        DictApi dictApi = SpringUtil.getBean(DictApi.class);

        if (!(originValue instanceof String)) {
            return null;
        }

        List<String> dictValues = JSON.parseArray(originValue.toString(), String.class);

        ArrayList<String> finalDictNameList = new ArrayList<>();

        FormItemSelect formItemSelect = formItem.getFormItemSelect();
        if (formItemSelect == null) {
            return null;
        }
        Integer valueType = formItemSelect.getDictValueType();
        if (valueType == null) {
            return null;
        }

        if (DictValueEnum.DICT_ID.getValueType().equals(valueType)) {
            for (String dictId : dictValues) {
                String dictName = dictApi.getDictNameByDictId(Long.valueOf(dictId));
                finalDictNameList.add(dictName);
            }
        }

        if (DictValueEnum.DICT_CODE.getValueType().equals(valueType)) {
            for (String dictCode : dictValues) {
                String dictName = dictApi.getDictName(formItemSelect.getDictTypeId(), dictCode);
                finalDictNameList.add(dictName);
            }
        }

        return StrUtil.join(",", finalDictNameList);
    }

}
