<template>
  <el-form
    ref="formRef"
    :model="modelValue"
    :rules="rules"
    :label-width="labelWidth + 'px'"
    :disabled="disabled"
  >
    <el-row>
      <el-col :span="24">
        <el-form-item label="所属领域:" required :show-message="false">
          <el-row type="flex" justify="space-between">
            <el-col :span="6">
              <el-form-item prop="industrys">
                <el-select
                  v-model="fields[0]"
                  value-key="id"
                  placeholder="请选择"
                  @change="levelIChange"
                >
                  <el-option
                    v-for="item in levelI"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-select
                v-model="fields[1]"
                value-key="id"
                placeholder="请选择"
                :disabled="levelII.length === 0"
                @change="levelIIChange"
              >
                <el-option
                  v-for="item in levelII"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="6">
              <el-select
                v-model="fields[2]"
                value-key="id"
                :disabled="levelIII.length === 0"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in levelIII"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="3">
              <el-button type="primary" @click="fieldAdd">添加</el-button>
              <!-- <el-button type="primary" @click="check">验证</el-button> -->
            </el-col>
          </el-row>
          <div class="e_tag">
            <el-tag
              v-for="(tag, index) in industrysTags"
              :key="index"
              closable
              @close="handleFieldClose(index)"
            >
              {{ getFieldNameById(tag) }}
              <!-- <template v-if="Array.isArray(tag)">
                <span v-for="(item, i) in tag" :key="item">
                  {{ item.name }}
                  <span v-if="tag.length != i + 1">></span>
                </span>
              </template>
              <template v-else>
                <span>{{ tag }}</span>
              </template> -->
            </el-tag>
          </div>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
</template>
<script setup name="FieldOptions">
// import { industry } from "@/api/config";
import { listSysIndustry } from "@/api/config";
import { ElMessage } from "element-plus";
import { toRefs, watch } from "vue";

const props = defineProps({
  modelValue: Object,
  labelWidth: {
    type: Number,
    default: 120,
  },
  disabled: {
    type: Boolean,
    default: false,
  },
});
const { modelValue, labelWidth, disabled } = toRefs(props);
const formRef = ref(null);
const levelI = ref([]); // I级数据
const levelII = ref([]); // II级数据
const levelIII = ref([]); // III级数据
const fields = ref([]); // 当前下拉框选中的集合
const industrysTags = ref([]); // 点击添加按钮后临时存储的数据集合
const data = reactive({
  rules: {
    industrys: [
      {
        type: "array",
        required: true,
        message: "请选择并添加",
        trigger: "change",
      },
    ],
  },
});
const { rules } = toRefs(data);

// 获取领域树形列表
const getIndustryTreeData = async () => {
  const { data } = await listSysIndustry();
  levelI.value = data;
};

const levelIChange = async (item) => {
  delete fields.value[1];
  delete fields.value[2];
  levelII.value = levelI.value.find((el) => {
    return el.id === item;
  }).children;
};

const levelIIChange = async (item) => {
  delete fields.value[2];
  levelIII.value = levelII.value.find((el) => el.id === item).children;
};

// 根据id获取领域名称
// TODO:如果领域已经被删除，则显示未知领域
const getFieldNameById = (ids) => {
  if (levelI.value.length === 0) {
    return;
  }
  let fieldNameList = [];
  let subFieldList = [];
  for (let i = 0; i < ids.length; i++) {
    const id = ids[i];
    if (fieldNameList.length === 0) {
      subFieldList = levelI.value.find((el) => el.id == id)?.children;
      fieldNameList.push(levelI.value.find((el) => id === el.id)?.name);
    } else {
      fieldNameList.push(subFieldList.find((el) => id === el.id)?.name);
      subFieldList = subFieldList.find((el) => el.id == id)?.children;
    }
  }
  return fieldNameList.join(">");
};

// 所属领域添加按钮
const fieldAdd = () => {
  if (!fields.value.length) return ElMessage.error("请选择领域类型");
  industrysTags.value.push(fields.value);
  if (!modelValue.value.industrys) modelValue.value.industrys = [];
  modelValue.value.industrys.push(fields.value.join("-"));
  fields.value = [];
  levelII.value = [];
  levelIII.value = [];
};

const handleFieldClose = (index) => {
  industrysTags.value.splice(index, 1);
  modelValue.value.industrys.splice(index, 1);
  formRef.value.validate();
};

const validateForm = async () => {
  try {
    return await formRef.value.validate();
  } catch (error) {
    return false;
  }
};

getIndustryTreeData();

watch(modelValue, (newVal) => {
  modelValue.value.industrys = [];
  industrysTags.value = [];
  modelValue.value.industrys.push(...modelValue.value.industry.split(","));
  for (const field of modelValue.value.industry.split(",")) {
    industrysTags.value.push(field.split("-").map((el) => parseInt(el)));
  }
});

defineExpose({
  validateForm,
});
</script>

<style lang="scss" scoped>
.e_tag {
  .el-tag {
    margin-right: 10px;
  }
}
</style>
