<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" title="绑定Google Ads帐号" @ok="handleSubmit" width="850" showFooter>
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>

<script lang="ts" setup>
  import { nextTick, ref } from 'vue';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { getGoogleAdsAccount, bindGoogleAdsAccount } from '../AdwebSite.api';

  const emit = defineEmits(['success', 'register']);
  const { createMessage } = useMessage();

  const formSchema: FormSchema[] = [
    {
      field: 'googleAdsAccount',
      label: 'Google Ads帐号',
      component: 'Input',
      required: true,
    },
    {
      field: 'apiRefreshToken',
      label: 'API Refresh Token',
      component: 'Input',
    },
    {
      field: 'siteCode',
      label: '站点代码',
      component: 'Input',
      required: true,
      show: false,
    },
  ];

  const [registerForm, { resetFields, validate, setFieldsValue }] = useForm({
    labelWidth: 120,
    schemas: formSchema,
    showActionButtonGroup: false,
  });

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner();

  async function handleSubmit() {
    try {
      const values = await validate();
      const params: Record<string, any> = {
        customerId: values.googleAdsAccount,
        siteCode: values.siteCode,
      };
      if (values.apiRefreshToken) {
        params.refreshToken = values.apiRefreshToken;
      }
      await bindGoogleAdsAccount(params);
      createMessage.success('Google Ads账号绑定成功');
      emit('success');
      closeDrawer();
    } catch (error) {
      createMessage.error('绑定Google Ads账号失败');
      console.error(error);
    }
  }

  // Add this method to handle initialization
  const init = (data: { record: Recordable }) => {
    nextTick(() => {
      resetFields();
    });
    setDrawerProps({ visible: true, confirmLoading: true });

    try {
      // 将 siteCode 作为路径参数传递
      const params = {
        siteCode: data.record.code,
      };

      nextTick(() => {
        // 初始化默认写入siteCode
        setFieldsValue({
          siteCode: data.record.code,
        });
      });
      getGoogleAdsAccount(params).then((res) => {
        if (res) {
          setFieldsValue({
            googleAdsAccount: res.customerId,
            apiRefreshToken: res.refreshToken,
          });
        }
      });
    } catch (error) {
      createMessage.error('获取Google Ads账号信息失败');
      console.error(error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  };

  // Expose the init method
  defineExpose({
    init,
  });
</script>
