<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="tenantAdminFormDrawer"
    showFooter
    :title="getTitle"
    width="60%"
    @ok="handleSubmit"
  >
    <BasicForm @register="tenantAdminForm" />
  </BasicDrawer>
</template>
<script lang="ts">
  import { computed, defineComponent, ref, unref } from 'vue';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
  import { saveTenantAdmin } from '/@/api/tenant/tenantApi';
  import { UserDTO } from '/@/api/tenant/tenantInfo';
  import { ChineseRegexp, EmailRegexp, emailRule, phoneRule } from '/@/utils/rules';
  import { chineseAndEnlishRule } from '/@/utils/rules';

  export default defineComponent({
    name: 'TenantAdminFormDrawer',
    components: {
      BasicDrawer,
      BasicForm,
    },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);
      const tenantId = ref('');
      const isJudgeUserNameExist: any = ref([]);
      const formSchema: FormSchema[] = [
        {
          field: 'id',
          label: 'id:',
          show: false,
          component: 'Input',
          componentProps: {
            maxLength: 36,
            placeholder: '请输入id',
          },
        },
        {
          field: 'username',
          label: '账号',
          component: 'Input',
          componentProps: {
            maxLength: 255,
            placeholder: '请输入账号',
          },
          dynamicRules: ({ values }) => {
            try {
              const findUserName = isJudgeUserNameExist.value.find((f) => {
                if (f) {
                  return f.username == values.username;
                }
              });
              return [
                {
                  required: true,
                  validator(_, value) {
                    return new Promise((resolve, reject) => {
                      if (value == '' || value === undefined) {
                        reject('请输入账号');
                      } else if (ChineseRegexp.test(value)) {
                        reject('账号不能含有中文');
                      } else if (EmailRegexp.test(value)) {
                        reject('账号不能为电子邮箱格式');
                      } else if (findUserName && value == findUserName?.username) {
                        console.log(1111111111);
                        reject('账号已存在');
                        return;
                      } else {
                        resolve();
                      }
                    });
                  },
                },
              ];
            } catch {}
          },
        },
        {
          field: 'realName',
          label: '真实名字',
          required: true,
          component: 'Input',
          componentProps: {
            maxLength: 255,
            placeholder: '请输入真实名字',
          },
          rules: chineseAndEnlishRule,
        },
        {
          field: 'phoneNumber',
          label: '电话号码',
          required: true,
          component: 'Input',
          rules: phoneRule,
        },
        {
          field: 'email',
          label: '邮件',
          component: 'Input',
          rules: emailRule,
        },
        {
          field: 'enabled',
          label: '状态',
          required: true,
          component: 'RadioButtonGroup',
          defaultValue: true,
          componentProps: {
            options: [
              { label: '启用', value: true },
              { label: '停用', value: false },
            ],
          },
        },
      ];
      const [tenantAdminForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
        labelWidth: 100,
        schemas: formSchema,
        showActionButtonGroup: false,
        baseColProps: { lg: 24, md: 24 },
      });
      const [tenantAdminFormDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(
        async (data) => {
          await resetFields();
          isUpdate.value = !!data?.isUpdate;
          tenantId.value = data?.tenantId;
          isJudgeUserNameExist.value = data.judgeExistUserName;
          if (unref(isUpdate)) {
            await updateSchema({ field: 'username', componentProps: { disabled: true } });
            await setFieldsValue({
              ...data.record,
            });
          } else {
            await updateSchema({ field: 'username', componentProps: { disabled: false } });
          }
        }
      );
      const getTitle = computed(() => (!unref(isUpdate) ? '新增租户管理员' : '编辑租户管理员'));

      async function handleSubmit() {
        try {
          setDrawerProps({ confirmLoading: true });
          const values = await validate();
          const requestParams = {
            id: values.id,
            username: values.username,
            realName: values.realName,
            phoneNumber: values.phoneNumber,
            email: values.email,
            enabled: values.enabled,
            tenantExpireTime:
              typeof values.tenantExpireTime != 'undefined' && values.tenantExpireTime != null
                ? values.tenantExpireTime.format('YYYY-MM-DD HH:mm:ss')
                : null,
            tenantId: tenantId.value,
          };
          await saveTenantAdmin(requestParams as any as UserDTO);
          closeDrawer(); //关闭侧框
          emit('success');
        } finally {
          setDrawerProps({ confirmLoading: false });
        }
      }

      return {
        tenantAdminFormDrawer,
        handleSubmit,
        tenantAdminForm,
        getTitle,
      };
    },
  });
</script>
