<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, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { BasicForm, useForm } from '@/components/Form';
  import { accountFormSchema } from './account.data';
  import { getRoleListByPage, userRoles } from '@/api/demo/system';
  import  { Select } from 'ant-design-vue';
  import type { SelectProps } from 'ant-design-vue';

  defineOptions({ name: 'AssignRoleModal' });

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

  const isUpdate = ref(true);
  const rowId = ref('');
  const valueSelect = ref < string[] > ([]);
  const [registerForm, { setFieldsValue, updateSchema, 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({
      page: 1,
      limit: 999
    })
    const arr = []
    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 });
    isUpdate.value = !!data?.isUpdate;

    if (unref(isUpdate)) {
      rowId.value = data.record.id;
      setFieldsValue({
        ...data.record,
      });
    }
  });

  const getTitle = computed(() => (!unref(isUpdate) ? '新增账号' : '编辑账号'));

  async function handleSubmit() {
    try {
      const values = await validate();
      setModalProps({ confirmLoading: true });
      var query = {
        userId: rowId.value,
        roleIds: valueSelect.value
      }
      const data = await userRoles(query)
      // TODO custom api
      closeModal();
      emit('success', { isUpdate: unref(isUpdate), values: { ...values, id: rowId.value } });
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
  onMounted(() => {
    getRole();
  });
</script>