<template>
  <Modal :maskClosable="false" :keyboard="false" v-model:open="data.isShowModal" :footer="null" 
         :title="$t('robot.fee.editTitle')" 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.fee.groupName')" name="groupUuid">
            <Select allow-clear showSearch :filterOption="selectFilterOption" v-model:value="form.groupUuid"
              :placeholder="$t('robot.fee.groupName')" :loading="data.groupLoading">
              <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.fee.robotUuid')" name="robotUuid">
            <Select allow-clear showSearch :filterOption="selectFilterOption" v-model:value="form.robotUuid"
              :loading="data.robotLoading" @change="handleRobotChange" allowClear
              :placeholder="$t('common.placeholderIn')">
              <SelectOption v-for="(item, index) in data.robotOptions" :key="index" :value="item.uuid"
                :label="item.email" :text="item.email">{{ item.email }}</SelectOption>
            </Select>
          </FormItem>
        </Col>
        <!-- <Col :span="12">
          <FormItem :label="$t('robot.fee.robotAccount')" name="robotAccount">
            <Input v-model:value="form.robotAccount" allowClear disabled :placeholder="$t('common.placeholderIn')"/>
          </FormItem>
        </Col> -->
        <Col :span="12">
          <FormItem :label="$t('robot.fee.totalAmount')" name="totalAmount">
            <InputNumber v-model:value="form.totalAmount" :precision="2" :min="0" style="width: 100%" 
                         allowClear :placeholder="$t('common.placeholderIn')"/>
          </FormItem>
        </Col>
        <Col :span="12">
          <FormItem :label="$t('robot.fee.usedAmount')" name="usedAmount">
            <InputNumber v-model:value="form.usedAmount" :precision="2" :min="0" style="width: 100%" 
                         allowClear :placeholder="$t('common.placeholderIn')" disabled/>
          </FormItem>
        </Col>
        <Col :span="12">
          <FormItem :label="$t('robot.fee.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.fee.validStartTime')" name="validStartTime">
            <DatePicker v-model:value="form.validStartTime" style="width: 100%" showTime
                        :placeholder="$t('common.placeholderIn')" format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss"/>
          </FormItem>
        </Col>
        <Col :span="12">
          <FormItem :label="$t('robot.fee.validEndTime')" name="validEndTime">
            <DatePicker v-model:value="form.validEndTime" style="width: 100%" showTime
                        :placeholder="$t('common.placeholderIn')" format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss"/>
          </FormItem>
        </Col>
        <Col :span="24">
          <FormItem :label-col="{ span: 3 }" :label="$t('robot.fee.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, InputNumber, Select, Row, Col, Button, message, DatePicker } from 'ant-design-vue';
import { robotFee, 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,
  robotLoading: false,
  groupLoading: false,
  robotOptions: [],
  groupOptions: [],
  statusOptions: [
    { label: $t('robot.fee.statusOptions.v0'), value: 0 },
    { label: $t('robot.fee.statusOptions.v1'), value: 1 }
  ]
})

const form = reactive({
  uuid: '',
  robotUuid: '',
  groupUuid: undefined,
  robotAccount: '',
  totalAmount: undefined,
  usedAmount: undefined,
  notes: '',
  status: undefined,
  validStartTime: undefined,
  validEndTime: undefined
})

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

// 加载机器人列表
const loadRobotOptions = async () => {
  data.robotLoading = true;
  try {
    const res = await robotAccount.queryList({});
    if (res.error) {
      return;
    }
    data.robotOptions = res.data || [];
  } catch (error) {
    console.error('加载机器人列表失败:', error);
  } finally {
    data.robotLoading = false;
  }
}

// 加载分组列表
const loadGroupOptions = async () => {
  data.groupLoading = true;
  try {
    const res = await robotGroup.queryList({});
    if (res.error) {
      return;
    }
    data.groupOptions = res.data || [];
  } catch (error) {
    console.error('加载分组列表失败:', error);
  } finally {
    data.groupLoading = false;
  }
}

// 处理机器人选择变化
const handleRobotChange = (value: string) => {
  if (value) {
    const selectedRobot = data.robotOptions.find((robot: any) => robot.uuid === value);
    if (selectedRobot) {
      form.robotAccount = selectedRobot.email;
    }
  } else {
    form.robotAccount = '';
  }
}

// 表单规则
const rules = reactive({
  robotUuid: [{
    validator: (rule: any, value: string) => {
      if (!value && !form.groupUuid) {
        return Promise.reject($t('robot.fee.robotOrGroupRequired'));
      }
      return Promise.resolve();
    }
  }],
  groupUuid: [{
    validator: (rule: any, value: string) => {
      if (!value && !form.robotUuid) {
        return Promise.reject($t('robot.fee.robotOrGroupRequired'));
      }
      return Promise.resolve();
    }
  }],
  totalAmount: [{ required: true, message: $t('form.required') }],
  status: [{ required: true, message: $t('form.required') }],
  validStartTime: [{ required: true, message: $t('form.required') }],
  validEndTime: [{ required: true, message: $t('form.required') }]
})

const formRef = ref();

function handleSubmit() {
  data.loading = true;
  formRef.value.validate().then(() => {
    robotFee.updateByUid(form).then((res) => {
      if (res.error) {
        return;
      }
      message?.success($t('common.editSuccess'));
      _close(true);
    })
  }).finally(() => {
    data.loading = false;
  })
}

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

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

function _open(item) {
  data.isShowModal = true;
  Object.assign(form, item);
  loadRobotOptions();
  loadGroupOptions();
}

defineExpose({
  _open
})
</script>