<template>
  <div id="pro-dictionary">
    <!--单选-->
    <template v-if="type === 'radio'">
      <a-radio-group @change="changeRadio" :value="modelValue">
        <a-radio v-for="d in data" :key="d" :value="d.value">{{
          d.label
        }}</a-radio>
      </a-radio-group>
    </template>
    <!--下拉选-->
    <template v-if="type === 'select'">
      <a-select @change="changeSelect" :value="modelValue">
        <a-select-option v-for="d in data" :key="d" :value="d.value">{{
          d.label
        }}</a-select-option>
      </a-select>
    </template>
    <!--多选-->
    <template v-if="type === 'checkbox'">
      <a-checkbox-group @change="changeCheckbox" :value="modelValue">
        <a-checkbox v-for="d in data" :key="d" :value="d.value">{{
          d.label
        }}</a-checkbox>
      </a-checkbox-group>
    </template>
    <!--键值对转换-->
    <template v-if="type === 'text'">
      <template v-for="d in data" :key="d">
        <span v-if="d.value ==  modelValue">{{d.label}}</span>
      </template>
    </template>
    <!--tag标签-->
    <template v-if="type === 'tag'">
      <template v-for="d in data" :key="d">
        <a-tag v-if="d.value ==  modelValue" :color='d.color'>
          {{d.label}}
        </a-tag>
      </template>
    </template>
  </div>
</template>
<script>
  import {
    ref
  } from "vue";
  import {
    list
  } from '../../../api/module/dictData.js';
  import {
    useStore
  } from 'vuex';
  export default {
    name: "pro-dictionary",
    props: {
      modelValue: {
        type: [String, Boolean, Array, Number],
        require: true,
      },
      code: {
        type: String,
        require: true,
      },
      type: {
        type: String,
        require: true,
      },
    },
    setup(props, context) {
      const data = ref([]);
      const store = useStore();

      /**
       * 从服务端获取下拉字典数据，并对数据进行格式化
       * @param code 字典值
       * @returns []
       */
      // const getDictData = async function(code) {
      //   await list({ code: code }).then((response) => {
      //     console.log("获取字典", code)
      //     var dict = response.data.map(item => {
      //       let { id, label, value, color, code, remark } = item
      //       return { id, label, text: label, value, color, code, remark };
      //     });
      //     store.dispatch("user/addDictData", { "code": code, "value": dict });
      //     return dict;
      //   });
      // };
      const getDictData = async function(code) {
        try {
          const response = await list({ code: code });
          var dict = response.data.map(item => {
            let { id, label, value, color, code: dictCode, remark } = item;
            return { id, label, text: label, value, color, dictCode, remark };
          });
          store.dispatch("user/addDictData", { "code": code, "value": dict });
          return dict;
        } catch (error) {
          console.error('获取字典数据失败:', error);
          throw error; 
        }
      };

      /**
       * 从本地获取缓存的字典数据，单本地不存在时，从远端获取
       * @param code
       * @returns {{label: *, value: string}[]}
       */
      const getListData = async function(code) {
        if (code && code.length > 0) {
          let dictData = store.getters.dict;//lngth > 0 ? store.getters.dict : store.getters.dictData;
          if (dictData && dictData.length > 0) {
            const index = dictData.findIndex(item => item.code === code);
            if (index != -1) {
              return dictData[index].value;
            } else {
              console.log("dictionary 没有 第一次添加", code)
              return await getDictData(code)
            }
          } else {
             console.log("dictionary 字典未初始化 从后端获取", code)
            return await getDictData(code);
          }
        } else {
          return [];
        }
      };

      const dictInit = async function(code) {
        data.value = await getListData(code);
      };
      dictInit(props.code);
      const changeSelect = function(value) {
        context.emit("update:modelValue", value);
      };

      const changeRadio = function(value) {
        context.emit("update:modelValue", value.target.value);
      };

      const changeCheckbox = function(value) {
        context.emit("update:modelValue", value);
      }

      return {
        data,
        changeCheckbox,
        changeSelect,
        changeRadio,
        getListData
      };
    },
  };
</script>
