<template>
  <el-form
    :model="formParams"
    :rules="rules"
    ref="formRef"
    label-placement="left"
    :label-width="100"
    require-mark-placement="left"
  >
    <el-divider border-style="dashed" class="mt-0 mb-10">基本设置</el-divider>

    <el-form-item label="上级权限" prop="parentId">
      <el-tree-select
        rowKey="key"
        :data="permissionTree"
        clearable
        check-strictly
        v-model="formParams.parentId"
      />
    </el-form-item>

    <el-row :gutter="24">
      <!-- 权限名称 -->
      <el-col :span="12">
        <el-form-item prop="permissionName">
          <template #label>
            <div class="flex items-center">
              <el-tooltip trigger="hover">
                <el-icon :size="18" class="mr-1 text-gray-400 cursor-pointer">
                  <QuestionCircleOutlined />
                </el-icon>
                <template #content>
                  权限名称 对应 权限标识 `中文名称`
                </template>
              </el-tooltip>
              <span>权限名称</span>
            </div>
          </template>
          <el-input placeholder="权限名称" v-model="formParams.permissionName" />
        </el-form-item>
      </el-col>

      <!-- 权限标识 -->
      <el-col :span="12">
        <el-form-item prop="permissionCode">
          <template #label>
            <div class="flex items-center">
              <el-tooltip trigger="hover">
                <el-icon :size="18" class="mr-1 text-gray-400 cursor-pointer">
                  <QuestionCircleOutlined />
                </el-icon>
                <template #content>
                  权限标识，也是权限字符，比如 `system:menu:list`
                </template>
              </el-tooltip>
              <span>权限标识</span>
            </div>
          </template>
          <el-input placeholder="权限标识" v-model="formParams.permissionCode" />
        </el-form-item>
      </el-col>
    </el-row>

    <el-row :gutter="24">
      <el-col :span="12">
        <el-form-item label="显示排序" prop="orderNum">
          <el-input-number placeholder="显示排序" v-model="formParams.orderNum" class="w-full" />
        </el-form-item>
      </el-col>
    </el-row>

    <el-form-item v-if="isShowSubmit">
      <el-button type="primary" :loading="subLoading" @click="formSubmit">保存修改</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
  import { ref, computed } from 'vue';
  import { ElMessage, FormInstance, FormRules } from 'element-plus';
  import { addPermission, updatePermission } from '@/api/system/permission';
  import { QuestionCircleOutlined } from '@vicons/antd';
  import { PermissionItem } from '@/types/permission/type';

  const emit = defineEmits(['change']);

  const props = defineProps({
    permissionList: {
      type: Array,
      defalut: () => [],
    },
    isShowSubmit: {
      type: Boolean,
      defalut: false,
    },
  });

  const formRef = ref<FormInstance>();
  const subLoading = ref(false);

  const defaultFormParams: PermissionItem = {
    id: null,
    parentId: null,
    permissionCode: '',
    permissionName: '',
    orderNum: 0,
  };

  const formParams = ref({ ...defaultFormParams });

  const permissionTree = computed(() => {
    // 可根据需要是否需要嵌套这个 避免出现选择器出现 0 的情况
    return [
      {
        label: '顶级目录',
        value: -1, // 约定顶级目录是 -1.
        children: props.permissionList || [],
      },
    ];
  });

  const rules: FormRules = {
    parentId: {
      required: true,
      message: '上级目录',
      trigger: 'change',
    },
    permissionName: {
      required: true,
      message: '权限名称',
      trigger: 'blur',
    },
    permissionCode: {
      required: true,
      message: '权限标识',
      trigger: 'blur',
    },
  };

  function setData(data: PermissionItem) {
    formParams.value = data;
    formRef.value?.resetFields();
  }

  function formSubmit() {
    subLoading.value = true;
    formRef.value?.validate((valid) => {
      if (valid) {
        if (!formParams.value.id) {
          addPermission(formParams.value)
            .then(() => {
              subLoading.value = false;
              ElMessage.success('添加成功');
              handleReset();
              emit('change');
            })
            .catch(() => {
              subLoading.value = false;
            });
        } else {
          updatePermission(formParams.value)
            .then(() => {
              subLoading.value = false;
              ElMessage.success('修改成功');
              handleReset();
              emit('change');
            })
            .catch(() => {
              subLoading.value = false;
            });
        }
      } else {
        subLoading.value = false;
        ElMessage.error('请填写完整信息');
      }
    });
  }

  function handleReset() {
    formRef.value?.resetFields();
    formParams.value = Object.assign(formParams.value, defaultFormParams);
  }

  defineExpose({
    formSubmit,
    handleReset,
    setData,
  });
</script>

<style lang="scss" sctep>
  .submit-form-item {
    margin-left: 100px;
  }
</style>
