<template>
  <el-form
      ref="formRef"
      :disabled="disabled"
      :inline="inline"
      :label-width="labelWidth + 'px'"
      :model="modelValue"
      :rules="rules"
      :size="size"
  >
    <el-row>
      <el-col :span="24">
        <!--        :show-message="false"-->
        <el-form-item label="所属领域:" prop="industrys">
          <el-row justify="space-between" type="flex">
            <el-col :span="6">
              <el-form-item>
                <el-select
                    v-model="fields[0]"
                    placeholder="请选择"
                    value-key="id"
                    @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]"
                  :disabled="levelII.length === 0"
                  placeholder="请选择"
                  value-key="id"
                  @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]"
                  :disabled="levelIII.length === 0"
                  placeholder="请选择"
                  value-key="id"
              >
                <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="!disabled"
                @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 name="FieldOptions" setup>
// import { industry } from "@/api/config";
import {listSysIndustry} from "@/api/platform/industry";
import {ElMessage} from "element-plus";
import {reactive, ref, toRefs, watch} from "vue";

const props = defineProps({
  modelValue: Object,
  labelWidth: {
    type: Number,
    default: 120,
  },
  disabled: {
    type: Boolean,
    default: false,
  },
  inline: {
    type: Boolean,
    default: true,
  },
  size: {
    type: String,
    default: "default",
  },
});
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("请选择领域类型");
  // 移除校验
  formRef.value.clearValidate();
  industrysTags.value.push(fields.value);
  modelValue.value.industrys.push(fields.value.join("-"));
  fields.value = [];
  levelII.value = [];
  levelIII.value = [];
  // for (let i = 0; i < industrysTags.value.length; i++) {
  //   modelValue.value.industrys.push("");
  //   const item = industrysTags.value[i];
  //   for (let j = 0; j < item.length; j++) {
  //     const item2 = item[j];
  //     if (modelValue.value.industrys[i] == "") {
  //       modelValue.value.industrys[i] = item2.id;
  //     } else {
  //       modelValue.value.industrys[i] =
  //         modelValue.value.industrys[i] + "-" + item2.id;
  //     }
  //   }
  // }
  // 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 () => {
  console.log(modelValue.value.industrys)
  try {
    return await formRef.value.validate();
  } catch (error) {
    return false;
  }
};

getIndustryTreeData();
fields.value = []
watch(
    modelValue,
    (newVal) => {
      modelValue.value.industrys = [];
      // console.log(modelValue.value.industry ? 1 : 0);
      let industrysList = modelValue.value.industry
          ? modelValue.value.industry.split(",")
          : [];
      modelValue.value.industrys.push(...industrysList);
      for (const field of industrysList) {
        industrysTags.value.push(field.split("-").map((el) => parseInt(el)));
      }
      // let _key = [];
      // let _value = [];
      // for (let i = 0; i < newVal.industrys.length; i++) {
      //   const item = newVal.industrys[i];
      //   _key.push(item.key);
      //   _value.push(item.value);
      // }
      // newVal.industrys = _key;
      // let keyObj = [];
      // for (let i = 0; i < _key.length; i++) {
      //   keyObj.push([]);
      //   let array = _key[i].split("-");
      //   for (let j = 0; j < array.length; j++) {
      //     keyObj[i].push({
      //       id: array[j],
      //     });
      //   }
      // }
      // for (let i = 0; i < _value.length; i++) {
      //   let array = _value[i].split(">");
      //   for (let j = 0; j < array.length; j++) {
      //     keyObj[i][j]["name"] = array[j];
      //   }
      // }
      // industrysTags.value = keyObj;
    },
    {immediate: true}
);

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

<!-- <script>
export default {
  watch: {
    value(newVal, oldVal) {
      let _key = [];
      let _value = [];
      for (let i = 0; i < newVal.industrys.length; i++) {
        const item = newVal.industrys[i];
        _key.push(item.key);
        _value.push(item.value);
      }
      newVal.industrys = _key;

      let keyObj = [];
      for (let i = 0; i < _key.length; i++) {
        keyObj.push([]);
        let array = _key[i].split("-");
        for (let j = 0; j < array.length; j++) {
          keyObj[i].push({
            id: array[j],
          });
        }
      }
      for (let i = 0; i < _value.length; i++) {
        let array = _value[i].split(">");
        for (let j = 0; j < array.length; j++) {
          keyObj[i][j]["name"] = array[j];
        }
      }
      industrysTags.value = keyObj;
    },
  },
};
</script> -->
<style lang="scss" scoped>
.e_tag {
  .el-tag {
    margin-right: 10px;
  }
}
</style>
