<template>
  <Modal :maskClosable="false" :keyboard="false" v-model:open="data.isShowModal" :footer="null"
    :title="$t('robot.account.addTitle')" width="50%" @cancel="_close">
    <Form ref="formRef" :model="form" :rules="rules" :label-col="{ span: 6 }" labelAlign="left" :labelWrap="true">
      <Row :gutter="24">
        <!-- <Col :span="12">
          <FormItem :label="$t('robot.account.code')" name="code">
            <Input v-model:value="form.code" allowClear :placeholder="$t('common.placeholderIn')"/>
          </FormItem>
        </Col> -->
        <Col :span="12">
          <FormItem :label="$t('robot.account.email')" name="email">
            <Input v-model:value="form.email" allowClear :placeholder="$t('common.placeholderIn')" />
          </FormItem>
        </Col>
        <Col :span="12">
          <FormItem :label="$t('robot.account.password')" name="password">
            <Input v-model:value="form.password" allowClear :placeholder="$t('common.placeholderIn')" />
          </FormItem>
        </Col>
        <Col :span="12">
          <FormItem :label="$t('robot.account.status')" name="status">
            <Select allow-clear showSearch :filterOption="selectFilterOption" v-model:value="form.status" allowClear
              :placeholder="$t('common.placeholderIn')">
              <SelectOption v-for="(item, index) in data.statusOptions" :key="index" :value="item.value"
                :label="item.label" :text="item.label">{{ item.label }}
              </SelectOption>
            </Select>
          </FormItem>
        </Col>
        <Col :span="12">
          <FormItem :label="$t('robot.account.groupId')" name="groupId">
            <Select allow-clear showSearch :filterOption="selectFilterOption" v-model:value="form.groupId" allowClear
              :placeholder="$t('common.placeholderIn')" @change="handleGroupChange">
              <SelectOption v-for="(item, index) in data.groupOptions" :key="index" :value="item.uuid"
                :label="item.groupName" :text="item.groupName">{{ item.groupName }}
              </SelectOption>
            </Select>
          </FormItem>
        </Col>
        <!-- <Col :span="12">
          <FormItem :label="$t('robot.account.groupName')" name="groupName">
            <Input v-model:value="form.groupName" allowClear :placeholder="$t('common.placeholderIn')" disabled/>
          </FormItem>
        </Col> -->
        <!-- <Col :span="12">
          <FormItem :label="$t('robot.account.managerId')" name="managerId">
            <Input v-model:value="form.managerId" allowClear :placeholder="$t('common.placeholderIn')"/>
          </FormItem>
        </Col>
        <Col :span="12">
          <FormItem :label="$t('robot.account.managerName')" name="managerName">
            <Input v-model:value="form.managerName" allowClear :placeholder="$t('common.placeholderIn')"/>
          </FormItem>
        </Col> -->
        <Col :span="12">
          <FormItem :label="$t('robot.account.userNumber')" name="userNumber">
            <Input v-model:value="form.userNumber" allowClear :placeholder="$t('common.placeholderIn')" />
          </FormItem>
        </Col>
        <Col :span="12">
          <FormItem :label="$t('robot.account.countryMobileCode')" name="countryMobileCode">
            <Input v-model:value="form.countryMobileCode" allowClear :placeholder="$t('common.placeholderIn')" />
          </FormItem>
        </Col>
        <Col :span="12">
          <FormItem :label="$t('robot.account.mobile')" name="mobile">
            <Input v-model:value="form.mobile" allowClear :placeholder="$t('common.placeholderIn')" />
          </FormItem>
        </Col>
        <Col :span="12">
          <FormItem :label="$t('robot.account.nickname')" name="nickname">
            <Input v-model:value="form.nickname" allowClear :placeholder="$t('common.placeholderIn')" />
          </FormItem>
        </Col>
        <Col :span="12">
          <FormItem :label="$t('robot.account.headerIconUrl')" name="headerIconUrl">
            <Input v-model:value="form.headerIconUrl" allowClear :placeholder="$t('common.placeholderIn')" />
          </FormItem>
        </Col>
        <Col :span="12">
          <FormItem :label="$t('robot.account.userId')" name="userId">
            <Input v-model:value="form.userId" allowClear :placeholder="$t('common.placeholderIn')" />
          </FormItem>
        </Col>
        <Col :span="24">
          <FormItem :label-col="{ span: 3 }" :label="$t('robot.account.notes')" name="notes">
            <TextArea v-model:value="form.notes" allowClear :placeholder="$t('common.placeholderIn')" :rows="3" />
          </FormItem>
        </Col>
      </Row>
      <FormItem style="text-align: right">
        <Button @click="_close" :disabled="data.loading">{{ $t('common.cancel') }}</Button>
        <Button danger style="margin-left: 10px" @click="handleResetForm" :disabled="data.loading">
          {{ $t('common.reset') }}
        </Button>
        <Button type="primary" style="margin-left: 10px" @click="handleSubmit" :loading="data.loading"
          :disabled="data.loading">{{ $t('common.confirm') }}
        </Button>
      </FormItem>
    </Form>
  </Modal>
</template>

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

const FormItem = Form.Item;
const SelectOption = Select.Option;
const TextArea = Input.TextArea;

interface Emits {
  (e: 'close', submit: Boolean): void
}

const emits = defineEmits<Emits>()

const data = reactive({
  isShowModal: false,
  loading: false,
  statusOptions: [
    { label: $t('robot.account.statusOptions.v0'), value: 0 },
    { label: $t('robot.account.statusOptions.v1'), value: 1 }
  ],
  groupOptions: [],
  groupLoading: false
})

const form = reactive({
  code: '',
  email: '',
  password: '',
  notes: '',
  status: undefined,
  groupId: undefined,
  groupName: '',
  managerId: undefined,
  managerName: '',
  userNumber: '',
  countryMobileCode: '',
  mobile: '',
  nickname: '',
  headerIconUrl: '',
  userId: undefined
})

// 选择框过滤方法
const selectFilterOption = (input: string, option: any) => {
  return option.text.toLowerCase().indexOf(input.toLowerCase()) >= 0;
}

// 加载分组数据
const loadGroupOptions = async () => {
  data.groupLoading = true;
  try {
    const res = await robotGroup.queryList({});
    if (!res.error && res.data) {
      data.groupOptions = res.data;
    }
  } catch (error) {
    console.error('加载分组数据失败:', error);
  } finally {
    data.groupLoading = false;
  }
}

// 分组选择变化处理
const handleGroupChange = (value: string) => {
  if (value) {
    const selectedGroup = data.groupOptions.find(group => group.uuid === value);
    if (selectedGroup) {
      form.groupName = selectedGroup.groupName;
    }
  } else {
    form.groupName = '';
  }
}

// 表单规则
const rules = reactive({
  code: [{ required: true, message: $t('form.required') }],
  account: [{ required: true, message: $t('form.required') }],
  password: [{ required: true, message: $t('form.required') }],
  status: [{ required: true, message: $t('form.required') }]
})

const formRef = ref();

function handleSubmit() {
  data.loading = true;
  formRef.value.validate().then(() => {
    robotAccount.create(form).then((res) => {
      if (res.error) {
        return;
      }
      message?.success($t('common.addSuccess'));
      _close(true);
    })
  }).catch(() => {
    // 验证失败
  }).finally(() => {
    data.loading = false;
  })
}

function handleResetForm() {
  formRef.value.resetFields();
}

function _close(submit = false) {
  data.isShowModal = false;
  formRef.value.resetFields();
  emits('close', submit);
}

defineExpose({
  _open() {
    data.isShowModal = true;
    loadGroupOptions();
  }
})
</script>