<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :showCancelBtn="false"
    :showOkBtn="false"
    :title="getTitle"
    width="500px"
  >
    <BasicForm @register="registerForm" />
    <template #appendFooter>
      <a-button @click="showQRCode">获取登陆二维码</a-button>
    </template>
  </BasicDrawer>
  <BasicModal
    @register="registerModal"
    v-bind="$attrs"
    :visible="true"
    title="扫码登陆"
    :helpMessage="['扫码完成后请等待页面刷新']"
    :destroyOnClose="true"
    :maskClosable="false"
    @ok="handleSubmit"
  >
    <div style="text-align: center">
      <div v-html="modalContent"></div>
    </div>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '@/components/Form/index';
  import { formSchema } from './wx.data';
  import { BasicDrawer, useDrawerInner } from '@/components/Drawer';
  import { BasicModal, useModal } from '/@/components/Modal';
  import { useI18n } from 'vue-i18n';

  import { createWx, updateWx } from '@/api/wechat/wx';
  import { refreshLoginQRApi } from '@/api/wechat/wxhook';

  export default defineComponent({
    name: 'WxDrawer',
    components: { BasicDrawer, BasicForm, BasicModal },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);
      const { t } = useI18n();
      let modalContent = ref('');

      const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
        labelWidth: 160,
        baseColProps: { span: 24 },
        layout: 'vertical',
        schemas: formSchema,
        showActionButtonGroup: false,
      });

      const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
        resetFields();
        setDrawerProps({ confirmLoading: false });

        isUpdate.value = !!data?.isUpdate;

        if (unref(isUpdate)) {
          setFieldsValue({
            ...data.record,
          });
        }
      });

      const getTitle = computed(() =>
        !unref(isUpdate) ? t('wechat.wx.addWx') : t('wechat.wx.editWx'),
      );

      const [registerModal, { openModal, setModalProps, closeModal }] = useModal();
      async function handleSubmit() {
        const values = await validate();
        setModalProps({ confirmLoading: true });
        setDrawerProps({ confirmLoading: true });
        let result = await createWx(values);
        if (result.code === 0) {
          closeDrawer();
          closeModal();
          emit('success');
        }
        setModalProps({ confirmLoading: false });
        setDrawerProps({ confirmLoading: false });
      }

      async function showQRCode() {
        const values = await validate();
        let result = await refreshLoginQRApi(values);
        if (result.code === 0) {
          if (result.data.status === '0' || result.data.status === '5') {
            modalContent.value = `<img src="${result.data.qRCode}" />`;
          } else if (result.data.status === '3' && unref(isUpdate)) {
            modalContent.value = `<p><b>${result.data.statusDesc}</b></p><p>如果需要更换账号，您需要先退出登陆~</p>`;
          } else {
            modalContent.value = `<p><b>${result.data.statusDesc}</b></p>`;
          }
          openModal(true);
        }
      }

      return {
        registerDrawer,
        registerForm,
        getTitle,
        handleSubmit,
        registerModal,
        showQRCode,
        modalContent,
      };
    },
  });
</script>
