<template>
  <a-button type="primary" @click="handleClick">
    <template #icon><icon-plus /></template>
    新建
  </a-button>
  <a-modal
    width="600px"
    :visible="visible"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <template #title>新建角色</template>
    <a-form ref="userCreateRef" :model="createData" :style="{ width: '500px' }">
      <a-form-item
        field="name"
        label="角色名"
        :validate-trigger="['change', 'input']"
        :rules="[{ required: true, message: '角色名不能为空' }]"
      >
        <a-input v-model="createData.name" />
      </a-form-item>
      <a-form-item
        field="permissions"
        label="权限"
        :rules="[{ type: 'array', minLength: 1, message: '请至少选择一个' }]"
        :validate-trigger="['change']"
      >
        <a-checkbox-group
          v-for="i in permOptions"
          :key="i.id"
          v-model="createData.roles"
          direction="vertical"
        >
          <a-checkbox :value="i">{{ i.name }}</a-checkbox>
        </a-checkbox-group>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script lang="ts" setup>
  import useVisible from '@/hooks/visible';
  import { queryRoles } from '@/api/role';
  import { CreateRecord, create } from '@/api/user';
  import { ref } from 'vue';
  import { FormInstance } from '@arco-design/web-vue/es/form';
  import { Message } from '@arco-design/web-vue';
  import { SelectOptionData } from '@arco-design/web-vue/es/select/interface';
  import { computedAsync } from '@vueuse/core';
  import { listDepts, queryDepts } from '@/api/dept';

  const { visible, setVisible } = useVisible(false);

  const userCreateRef = ref<FormInstance>();

  const createData = ref<CreateRecord>({
    username: '',
    name: '',
    phone: '',
    email: '',
    enableState: '',
    dept: undefined,
    roles: [],
  });

  const permOptions = computedAsync(async () => {
    // const res = await queryPermissions();
    // return res.data.content;
  });

  const emit = defineEmits(['refresh']);
  const handleClick = () => {
    setVisible(true);
  };
  const handleSubmit = async () => {
    const valid = await userCreateRef.value?.validate();
    if (!valid) {
      const res = await create(createData.value);
      if (res.status === 200) {
        Message.success({
          content: '新增成功',
          duration: 5 * 1000,
        });
      }
      emit('refresh');
      userCreateRef.value?.resetFields();
      setVisible(false);
    }
  };
  const handleCancel = async () => {
    userCreateRef.value?.resetFields();
    setVisible(false);
  };
</script>

<style scoped></style>
