<template>
  <Modal v-model:visible="visible" :title="$t('robot.chatConfig.addTitle')" width="50%" :footer="null" @cancel="handleCancel">
    <Form :model="formState" :rules="rules" ref="formRef" :label-col="{ span: 6 }"  labelAlign="left" :wrapper-col="{ span: 16 }">
      <!-- 配置名称 -->
      <FormItem :label="$t('robot.chatConfig.configName')" name="name">
        <Input v-model:value="formState.name" :placeholder="$t('robot.chatConfig.configName')" />
      </FormItem>

      <!-- 机器人分组 -->
      <FormItem :label="$t('robot.chatConfig.robotGroupUuid')" name="robotGroupUuid">
        <Select 
        allow-clear
          v-model:value="formState.robotGroupUuid" 
          :placeholder="$t('robot.chatConfig.robotGroupUuidRequired')"
          :options="robotGroupOptions"
          show-search
          :filter-option="filterOption"
          @change="handleRobotGroupChange"
        />
      </FormItem>

      <!-- 机器人 -->
      <FormItem :label="$t('robot.chatConfig.robotUuid')" name="robotUuid">
        <Select 
        allow-clear
          v-model:value="formState.robotUuid" 
          :placeholder="$t('robot.chatConfig.robotUuid')"
          :options="robotOptions"
          show-search
          :filter-option="filterOption"
        />
      </FormItem>

      <!-- 最小间隔时间 -->
      <FormItem :label="$t('robot.chatConfig.minIntervalTime')" name="minIntervalTime">
        <InputNumber v-model:value="formState.minIntervalTime" :placeholder="$t('robot.chatConfig.minIntervalTime')" style="width: 100%" :min="0" />
      </FormItem>

      <!-- 最大间隔时间 -->
      <FormItem :label="$t('robot.chatConfig.maxIntervalTime')" name="maxIntervalTime">
        <InputNumber v-model:value="formState.maxIntervalTime" :placeholder="$t('robot.chatConfig.maxIntervalTime')" style="width: 100%" :min="0" />
      </FormItem>

      <!-- 聊天次数 -->
      <FormItem :label="$t('robot.chatConfig.count')" name="count">
        <InputNumber v-model:value="formState.count" :placeholder="$t('robot.chatConfig.count')" style="width: 100%" :min="0" />
      </FormItem>

      <!-- 状态 -->
      <FormItem :label="$t('robot.chatConfig.status')" name="status">
        <Select v-model:value="formState.status" :placeholder="$t('robot.chatConfig.status')" style="width: 100%">
          <SelectOption :value="0">{{ $t('robot.chatConfig.statusOptions.v0') }}</SelectOption>
          <SelectOption :value="1">{{ $t('robot.chatConfig.statusOptions.v1') }}</SelectOption>
        </Select>
      </FormItem>

      <!-- AI开关 -->
      <FormItem :label="$t('robot.chatConfig.aiSwitch')" name="aiSwitch">
        <Select v-model:value="formState.aiSwitch" :placeholder="$t('robot.chatConfig.aiSwitch')" style="width: 100%">
          <SelectOption :value="0">{{ $t('robot.chatConfig.aiSwitchOptions.v0') }}</SelectOption>
          <SelectOption :value="1">{{ $t('robot.chatConfig.aiSwitchOptions.v1') }}</SelectOption>
        </Select>
      </FormItem>

      <!-- 开场白 -->
      <!-- <FormItem :label="$t('robot.chatConfig.openingRemarks')" name="openingRemarks">
        <TextArea v-model:value="formState.openingRemarks" :placeholder="$t('robot.chatConfig.openingRemarks')" :rows="4" />
      </FormItem> -->

      <!-- 备注 -->
      <FormItem :label="$t('robot.chatConfig.notes')" name="notes">
        <TextArea v-model:value="formState.notes" :placeholder="$t('robot.chatConfig.notes')" :rows="4" />
      </FormItem>

      <!-- 按钮 -->
      <FormItem :wrapper-col="{ offset: 6, span: 16 }">
        <Button type="primary" @click="handleSubmit" :loading="loading">{{ $t('common.submit') }}</Button>
        <Button @click="handleCancel" style="margin-left: 10px">{{ $t('common.cancel') }}</Button>
      </FormItem>
    </Form>
  </Modal>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from "vue";
import { $t } from '@vben/locales';
import { Modal, Form, FormItem, Input, InputNumber, Button, Select, message } from 'ant-design-vue';
import { chatConfig, robotGroup, robotAccount } from '#/api';

const TextArea = Input.TextArea;
const SelectOption = Select.Option;

const visible = ref(false);
const loading = ref(false);
const formRef = ref();

const formState = reactive({
  name: null,
  robotGroupUuid: null,
  robotUuid: null,
  minIntervalTime: null,
  maxIntervalTime: null,
  count: null,
  status: 1,
  aiSwitch: 0,
  openingRemarks: null,
  notes: null,
  creator: null,
});

const robotGroupOptions = ref([]);
const robotOptions = ref([]);

const rules = {
  name: [
    { required: true, message: $t('robot.chatConfig.configNameRequired'), trigger: 'blur' },
  ],
};

// 加载机器人分组列表
const loadRobotGroups = async () => {
  try {
    const res = await robotGroup.queryList({});
    if (res.data && Array.isArray(res.data)) {
      robotGroupOptions.value = res.data.map(item => ({
        label: item.groupName || item.uuid,
        value: item.uuid,
      }));
    }
  } catch (error) {
    console.error('加载机器人分组列表失败:', error);
  }
};

// 加载机器人列表
const loadRobots = async (robotGroupUuid = null) => {
  try {
    const params = robotGroupUuid ? { robotGroupUuid } : {};
    const res = await robotAccount.queryList(params);
    if (res.data && Array.isArray(res.data)) {
      robotOptions.value = res.data.map(item => ({
        label: item.email || item.uuid,
        value: item.uuid,
      }));
    } else {
      robotOptions.value = [];
    }
  } catch (error) {
    console.error('加载机器人列表失败:', error);
    robotOptions.value = [];
  }
};

// 机器人分组变化处理
const handleRobotGroupChange = (value) => {
  formState.robotUuid = null;
  loadRobots(value);
};

// 下拉框搜索过滤
const filterOption = (input, option) => {
  return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
};

function handleSubmit() {
  formRef.value.validate().then(() => {
    loading.value = true;
    chatConfig.create(formState).then((res) => {
      if (res.error) {
        return;
      }
      message.success($t('common.addSuccess'));
      handleCancel();
      emit('close');
    }).finally(() => {
      loading.value = false;
    })
  }).catch(() => {
    message.error($t('common.validateError'));
  })
}

function handleCancel() {
  visible.value = false;
  formRef.value.resetFields();
  formState.robotGroupUuid = null;
  formState.robotUuid = null;
  robotOptions.value = [];
}

const emit = defineEmits(['close']);

function _open() {
  visible.value = true;
  loadRobotGroups();
  loadRobots(); // 加载所有机器人列表
}

function reset() {
  formRef.value.resetFields();
  formState.robotGroupUuid = null;
  formState.robotUuid = null;
  robotOptions.value = [];
}

defineExpose({
  _open,
  reset,
});
</script>