<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="500px"
    @ok="handleSubmit"
  >
    <BasicForm @register="tenantForm">
      <template #iconSelect>
        <Upload
          name="avatar"
          list-type="picture-card"
          class="avatar-uploader"
          :show-upload-list="false"
          :customRequest="customUpload"
          :before-upload="beforeUpload"
        >
          <img v-if="tenantLogo" :src="tenantLogo" alt="avatar" />
          <div v-else>
            <LoadingOutlined v-if="loading" />
            <plus-outlined v-else />
            <div class="ant-upload-text">上传</div>
          </div>
        </Upload>
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { PlusOutlined, LoadingOutlined } from '@ant-design/icons-vue';
  import { message, Upload } from 'ant-design-vue';

  import { useI18n } from '/@/hooks/web/useI18n';
  import { tenantFormSchema } from '/@/views/tenant/list/tenantBaseColumns';
  import { FileItem } from '/@/components/Upload/src/typing';
  import { upload } from '/@/api/oss/ossFileUploader';
  import { getTenantRoles, updateOrCreateTenant } from '/@/api/tenant/tenantApi';
  import { useMessage } from '/@/hooks/web/useMessage';

  export default defineComponent({
    name: 'TenantDrawer',
    components: {
      BasicDrawer,
      BasicForm,
      Upload,
      PlusOutlined,
      LoadingOutlined,
    },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const loading = ref(false);
      const { createMessage } = useMessage();

      const isUpdate = ref(true);
      const tenantLogo = ref('');

      async function customUpload({ file }) {
        if (beforeUpload(file)) {
          tenantLogo.value = '';
          loading.value = true;
          const formData = new FormData();
          formData.append('file', file);
          const response = await upload(formData);
          if (response.fileStaticUri) {
            tenantLogo.value = response.fileStaticUri;
            loading.value = false;
          }
        }
      }

      const beforeUpload = (file: FileItem) => {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
        if (!isJpgOrPng) {
          message.error('只能上传图片文件!');
        }
        const isLt2M = (file.size as number) / 1024 / 1024 < 5;
        if (!isLt2M) {
          message.error('图片大小不能超过5MB!');
        }
        return isJpgOrPng && isLt2M;
      };
      const [tenantForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
        labelWidth: 100,
        schemas: tenantFormSchema,
        showActionButtonGroup: false,
        baseColProps: { lg: 24, md: 24 },
      });
      const { t } = useI18n(); //加载国际化

      //默认传递页面数据
      const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
        await resetFields();
        tenantLogo.value = '';
        setDrawerProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;

        //初始化，菜单名称为可用
        await updateSchema({ field: 'title', componentProps: { disabled: false } });
        //如果是编辑操作，设置页面数据
        if (unref(isUpdate)) {
          getTenantRoles(data.record.tenantId).then((result) => {
            Reflect.set(data.record, 'roleIds', result);
            //为表单赋值
            setFieldsValue(data.record);
            tenantLogo.value = data.record.icon;
            //编辑模式，菜单名称为不可用
            updateSchema({ field: 'title', componentProps: { disabled: true } });
          });
        }
      });
      //得到页面标题
      const getTitle = computed(() =>
        !unref(isUpdate)
          ? t('routes.common.system.pageSystemTitleCreateTenant')
          : t('routes.common.system.pageSystemTitleEditTenant')
      );

      //提交按钮
      async function handleSubmit() {
        setDrawerProps({ confirmLoading: true });
        try {
          const values = await validate();
          const req = {
            id: values.id,
            icon: tenantLogo.value,
            name: values.name,
            enabled: values.enabled,
            description: values.description,
            roleIds: values.roleIds,
            tenantId: values.tenantId,
            tenantExpireTime:
              typeof values.tenantExpireTime != 'undefined' && values.tenantExpireTime != null
                ? values.tenantExpireTime.format('YYYY-MM-DD HH:mm:ss')
                : null,
            tenantProfileId: {
              id: values.tenantProfileId,
              entityType: 'TENANT_PROFILE',
            },
          };
          await updateOrCreateTenant(req);
          emit('success');
          createMessage.success(`${unref(isUpdate) ? '编辑' : '新增'}成功`);
          closeDrawer(); //关闭侧框
        } catch (e) {
          if ((e as { code: string }).code === 'ECONNABORTED') {
            emit('success');
            closeDrawer(); //关闭侧框
          }
        } finally {
          setDrawerProps({ confirmLoading: false });
        }
      }
      return {
        registerDrawer,
        tenantForm,
        getTitle,
        handleSubmit,
        tenantLogo,
        beforeUpload,
        customUpload,
        loading,
      };
    },
  });
</script>
<style>
  .ant-upload-select-picture-card i {
    font-size: 32px;
    color: #999;
  }
</style>
