<template>
  <el-form
    ref="formRef"
    :model="value"
    :rules="rules"
    :label-width="labelWidth + 'px'"
    :disabled="disabled"
  >
    <el-row>
      <el-col :span="24">
        <el-form-item label="所属领域:" required>
          <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"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-select
                v-model="fields[1]"
                value-key="id"
                placeholder="请选择"
                @change="levelIIChange"
              >
                <el-option
                  v-for="item in levelII"
                  :key="item.id"
                  :label="item.name"
                  :value="item"
                >
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="6">
              <el-select
                v-model="fields[2]"
                value-key="id"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in levelIII"
                  :key="item.id"
                  :label="item.name"
                  :value="item"
                >
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="3">
              <el-button type="primary" @click="fieldAdd">添加</el-button>
            </el-col>
          </el-row>
          <div class="e_tag">
            <el-tag
              v-for="(tag, index) in industrysTags"
              :key="index"
              closable
              @close="handleFieldClose(index)"
            >
              <template v-if="Array.isArray(tag)">
                <span v-for="(item, i) in tag" :key="item.id">
                  {{ 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 { 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 getFieldByParent = (id) => {
  return new Promise((resolve, reject) => {
    industry({ parent_id: id })
      .then(({ code, msg, data }) => {
        if (code == 200) {
          resolve(data);
        } else {
          ElMessage.error(msg);
          reject({ msg, code });
        }
      })
      .catch((error) => {
        reject(error);
      });
  });
};
const levelIChange = async (item) => {
  delete fields.value[1];
  delete fields.value[2];
  levelII.value = await getFieldByParent(item.id);
};
const levelIIChange = async (item) => {
  delete fields.value[2];
  levelIII.value = await getFieldByParent(item.id);
};
// 所属领域添加按钮
const fieldAdd = () => {
  if (!fields.value.length) return ElMessage.error("请选择领域类型");
  modelValue.value.industrys = [];
  industrysTags.value.push(fields.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);
};

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

industry().then((res) => {
  levelI.value = res.data;
});

watch(modelValue, (newVal) => {
  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;
});
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>
