<template>
  <Modal :maskClosable="false" :keyboard="false" v-model:open="data.isShowModal" :footer="null"
    :title="$t('robot.account.batchEditTitle')" width="50%" @cancel="_close">
    <Form ref="formRef" :model="form" :rules="rules" :label-col="{ span: 6 }" labelAlign="left" :labelWrap="true" style="margin-top: 16px">
      <Row :gutter="24">
        <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.password')" name="password">
            <Input v-model:value="form.password" 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 } from "vue";
import { $t } from '@vben/locales';
import { Modal, Form, Input, Select, Row, Col, Button, message, Alert } 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,
  selectedCount: 0,
  selectedUids: [],
  statusOptions: [
    { label: $t('robot.account.statusOptions.v0'), value: 0 },
    { label: $t('robot.account.statusOptions.v1'), value: 1 }
  ],
  groupOptions: [],
  groupLoading: false
})

const form = reactive({
  status: undefined,
  groupId: undefined,
  password: '',
  notes: ''
})

// 选择框过滤方法
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) => {
  // 批量修改不需要处理groupName
}

// 表单规则
const rules = reactive({
  // 批量修改字段都是可选的，不需要强制验证
})

const formRef = ref();

function handleSubmit() {
  data.loading = true;
  formRef.value.validate().then(() => {
    // 获取选中的账号UUID列表
    const selectedUids = data.selectedCount > 0 ? data.selectedUids : [];
    
    if (selectedUids.length === 0) {
      message.error('请先选择要修改的账号');
      data.loading = false;
      return;
    }
    
    // 构建批量更新参数
    const updateData = {
      uids: selectedUids,
      ...form
    };
    
    // 过滤掉未修改的字段
    Object.keys(updateData).forEach(key => {
      if (updateData[key] === undefined || updateData[key] === '') {
        delete updateData[key];
      }
    });
    
    robotAccount.updateByUids(updateData).then((res) => {
      if (res.error) {
        message.error(res.msg || '批量修改失败');
        return;
      }
      message?.success($t('common.batchEditSuccess'));
      _close(true);
    }).catch((error) => {
      message.error('批量修改失败：' + error.message);
    }).finally(() => {
      data.loading = false;
    });
  }).catch((error) => {
    console.error('表单验证失败:', error);
    data.loading = false;
  });
}

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

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

function _open(selectedRows: any[]) {
  data.selectedCount = selectedRows.length;
  data.selectedUids = selectedRows.map(row => row.uuid);
  data.isShowModal = true;
  loadGroupOptions();
}

defineExpose({
  _open,
  _close
})
</script>