<script setup lang="ts">
import { ref } from "vue";
const ruleFormRef = ref();
const formRules = ref({
  pid: [{ required: true, message: "所属父级为必填项", trigger: "change" }],
  name: [{ required: true, message: "角色名称为必填项", trigger: "blur" }],
  rules: [{ required: true, message: "权限列表为必填项", trigger: "change" }],
  status: [{ required: true, message: "状态为必填项", trigger: "change" }]
});
const props = defineProps(["formInline", "higherMenuOptions", "treeData"]);
const treeRef = ref(null)
const newFormInline = ref(
  props.formInline
    ? props.formInline
    : {
      name: "",
      rules: "",
      status: 'normal',
      pid: ''
    }
);

function getRef() {
  return ruleFormRef.value;
}
const changeCheck = (data) => {
  // console.log()
  const rulesList = treeRef.value.getCheckedKeys()
  newFormInline.value.rules = rulesList.length ? rulesList.join(',') : ''
  newFormInline.value.name = newFormInline.value.name.replace(/[^\u4e00-\u9fa5\u3000-\u303f\uff00-\uffef]/g, '');
  // console.log(newFormInline.value.rules)
}
if (newFormInline.value.rules) {
  let list = newFormInline.value.rules.split(',').map(ele => {
    return +ele
  })
  console.log()
  setTimeout(() => {
    treeRef.value.setCheckedKeys(list)
  }, 100)
}
defineExpose({ getRef });
</script>

<template>
  <el-form ref="ruleFormRef" :model="newFormInline" :rules="formRules" label-width="120px">
    <el-form-item label="所属父级" prop="pid">
      <el-cascader v-model="newFormInline.pid" class="w-full" :options="higherMenuOptions" :props="{
        value: 'id',
        label: 'name',
        emitPath: false,
        checkStrictly: true
      }" clearable filterable placeholder="请选择上级角色">
        <template #default="{ node, data }">
          <span v-html="data.name"></span>
          <span v-if="!node.isLeaf"> ({{ data.childlist.length }}) </span>
        </template>
      </el-cascader>
    </el-form-item>
    <el-form-item label="角色名称" prop="name">
      <el-input v-model="newFormInline.name" clearable placeholder="请输入角色名称" />
    </el-form-item>
    <!-- {{ treeData }} -->
    <el-form-item label="权限" prop="rules">
      <el-tree :data="treeData" ref="treeRef" show-checkbox node-key="id" @check-change="changeCheck" :props="{
        children: 'childlist',
        label: 'title'
      }">
      </el-tree>
    </el-form-item>
    <el-form-item label="状态" prop="status">
      <el-radio-group v-model="newFormInline.status">
        <el-radio label="正常" value="normal" />
        <el-radio label="隐藏" value="hidden" />
      </el-radio-group>
    </el-form-item>
  </el-form>
</template>
