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

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

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

  const formSchema = [
    {
      field: 'FaceBookAccount',
      label: 'FaceBook帐号',
      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.FaceBookAccount,
        siteCode: values.siteCode,
      };
      if (values.apiRefreshToken) {
        params.refreshToken = values.apiRefreshToken;
      }
      await bindFaceBookAccount(params);
      createMessage.success('FaceBook账号绑定成功');
      emit('success');
      closeDrawer();
    } catch (error) {
      createMessage.error('绑定FaceBook账号失败');
      console.error(error);
    }
  }

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

    try {
      // 将 siteCode 作为路径参数传递
      const params = {
        siteCode: data.record.code,
      };
      const res = await getFaceBookAccount(params);
      if (res) {
        console.log(data.record.code)
        setFieldsValue({
          FaceBookAccount: res.customerId,
          apiRefreshToken: res.refreshToken,
          siteCode: data.record.code,
        });
      }else {
        setFieldsValue({
          siteCode: data.record.code
        });
      }
    } catch (error) {
      createMessage.error('获取FaceBook账号信息失败');
      console.error(error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  };

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