<template>
  <BasicModal v-bind="$attrs" @register="registerModal" title="分配角色" @ok="handleSubmit">
    <BasicForm @register="registerForm">
      <template #selectB="{ model, field }">
        <Select
          :options="roleList"
          mode="multiple"
          v-model:value="model[field]"
          @change="valueSelect = model[field]"
          allowClear
        />
      </template>
    </BasicForm>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { onMounted, ref } from 'vue';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { BasicForm, useForm } from '@/components/Form';
  import { getRoleListByPage, userRoles, getUserRoles } from '@/api/demo/system';
  import { Select } from 'ant-design-vue';
  import type { SelectProps } from 'ant-design-vue';
  import { useMessage } from '@/hooks/web/useMessage';

  const { createMessage } = useMessage();
  defineOptions({ name: 'AssignRoleModal' });

  const emit = defineEmits(['success', 'register']);

  const rowId = ref('');
  const valueSelect = ref<string[]>([]);
  const [registerForm, { setFieldsValue, resetFields, validate }] = useForm({
    labelWidth: 100,
    baseColProps: { span: 24 },
    schemas: [
      {
        field: 'roleIds',
        // component: 'Select',
        label: '角色',
        slot: 'selectB',
        defaultValue: [],
        // colProps: {
        //   span: 8,
        // },
        required: true,
      },
    ],
    showActionButtonGroup: false,
    actionColOptions: {
      span: 23,
    },
  });
  const roleList = ref<SelectProps['options']>([]);
  async function getRole() {
    var data = await getRoleListByPage();
    const arr: any[] = [];
    data.items.forEach((element) => {
      arr.push({
        label: element.name,
        value: element.id,
      });
    });
    roleList.value = arr;
  }
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    resetFields();
    setModalProps({ confirmLoading: false });
    if (data) {
      rowId.value = data.record.id;
      getRole();
      getRoles();
    }
  });
  async function getRoles() {
    if (!rowId.value) {
      return;
    }
    const data = await getUserRoles({
      userId: rowId.value,
    });
    setFieldsValue({
      roleIds: data,
    });
  }
  async function handleSubmit() {
    try {
      const values = await validate();
      setModalProps({ confirmLoading: true });
      var query = {
        userId: rowId.value,
        roleIds: valueSelect.value,
      };
      const data = await userRoles(query);
      if (data) {
        // TODO custom api
        closeModal();
        emit('success');
        return createMessage.success('成功');
      } else {
        return createMessage.error('失败');
      }
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
  onMounted(() => {
    getRole();
    getRoles();
  });
</script>
