<script setup lang="ts">
import { ref } from 'vue';

import { useVbenDrawer, useVbenForm } from '@vben/common-ui';

import { initiateFormSchema } from './connectInfo-data';

import { initiateConnectInfo } from '#/api/system/infoEntry/connectInfo/connectInfo';
import { requestClient } from '#/api/request';

const emit = defineEmits<{
  reload: [];
}>();

// 获取人员列表的方法
const getPersonOptions = async (stationId: number) => {
  try {
    const res = await requestClient.get('/system/user/stationList', {
      params: { stationId },
    });
    return Array.isArray(res)
      ? res.map((item: any) => ({
          label: item.userName,
          value: item.userId,
        }))
      : [];
  } catch (error) {
    console.error('获取人员列表失败:', error);
    return [];
  }
};

// 创建一个包装函数来处理联动逻辑
const handleStationChange = async (selectedId: number) => {
  console.log('selectedId', selectedId);
  
  // 清空已选监交人
  await formApi.setValues({ handoverPersonId: undefined });
  
  if (selectedId) {
    // 获取新的监交人选项
    const newOptions = await getPersonOptions(selectedId);
    
    // 动态更新监交人下拉框的配置
    formApi.setState({
      schema: initiateFormSchema({ 
        handleStationChange,
        handoverPersonOptions: newOptions 
      })
    });
  } else {
    // 如果清空了油站选择，清空监交人选项
    formApi.setState({
      schema: initiateFormSchema({ 
        handleStationChange,
        handoverPersonOptions: [] 
      })
    });
  }
};

const [Form, formApi] = useVbenForm({
  showDefaultActions: false,
  schema: initiateFormSchema({ 
    handleStationChange,
    handoverPersonOptions: [] 
  }),
});

const [Drawer, drawerApi] = useVbenDrawer({
  async onConfirm() {
    try {
      this.confirmLoading = true;
      const { valid } = await formApi.validate();
      if (!valid) {
        return;
      }
      const data = await formApi.getValues();
      // 提交发起交接数据
      await initiateConnectInfo(data);
      emit('reload');
      drawerApi.close();
    } catch (error) {
      console.error('发起交接失败:', error);
    } finally {
      this.confirmLoading = false;
    }
  },

  onClosed() {
    formApi.resetForm();
  },
});
</script>

<template>
  <Drawer title="发起交接">
    <Form />
  </Drawer>
</template>
