<template>
  <Modal v-model:visible="visible" title="全局配置" width="50%" :footer="null"
    :maskClosable="false" :keyboard="false" :destroyOnClose="true">
    <Form ref="formRef" :model="formState" :rules="rules" :label-col="{ span: 8 }" labelAlign="left" :labelWrap="true">
      <Row :gutter="24">
        <Col :span="24">
          <FormItem label="直播间最大机器人数" name="roomRobotMax">
            <InputNumber v-model:value="formState.roomRobotMax" :min="0" placeholder="直播间最大机器人数" style="width: 100%" />
          </FormItem>
        </Col>
      </Row>
      <FormItem style="text-align: right">
        <Button @click="handleCancel" :disabled="loading">{{ $t('common.cancel') }}</Button>
        <Button type="primary" style="margin-left: 10px" @click="handleSubmit" :loading="loading"
                :disabled="loading">{{ $t('common.submit') }}
        </Button>
      </FormItem>
    </Form>
  </Modal>
</template>

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

const FormItem = Form.Item;

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

const formState = reactive({
  roomRobotMax: undefined
});

const rules = {
  roomRobotMax: [
    { required: true, message: '请输入直播间最大机器人数', trigger: 'blur' }
  ]
};

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

async function fetchGlobalConfig() {
  loading.value = true;
  try {
    const res = await rRunningConfigGlobal.getOneBy({});
    if (!res.error && res.data) {
      // 填充表单数据
      Object.keys(formState).forEach(key => {
        if (res.data[key] !== undefined) {
          formState[key] = res.data[key];
        }
      });
    }
  } catch (error) {
    console.error('获取全局配置失败:', error);
    message.error('获取全局配置失败');
  } finally {
    loading.value = false;
  }
}

function _open() {
  visible.value = true;
  // 打开时自动获取数据
  fetchGlobalConfig();
}

function handleSubmit() {
  formRef.value.validate().then(() => {
    loading.value = true;
    rRunningConfigGlobal.updateBy(formState).then((res) => {
      if (res.error) {
        message.error('保存失败');
        return;
      }
      message.success($t('common.editSuccess'));
      handleCancel();
      emit('close');
    }).finally(() => {
      loading.value = false;
    })
  }).catch(() => {
    message.error($t('common.validateError'));
  })
}

function handleCancel() {
  visible.value = false;
  formRef.value.resetFields();
}

defineExpose({
  _open
});
</script>