<template>
  <Modal v-model:visible="visible" :title="$t('robot.runningConfig.addTitle')" 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="12">
          <FormItem :label="$t('robot.runningConfig.configName')" name="configName">
            <Input v-model:value="formState.configName" :placeholder="$t('robot.runningConfig.configNameRequired')" />
            <p class="text-sm text-gray-500">{{ $t('robot.runningConfig.configNameDesc') }}</p>
          </FormItem>
        </Col>
        <Col :span="12">
          <FormItem :label="$t('robot.runningConfig.minOnlineUsers')" name="minOnlineUsers">
            <InputNumber v-model:value="formState.minOnlineUsers" :min="0" :placeholder="$t('robot.runningConfig.minOnlineUsersRequired')" style="width: 100%" />
            <p class="text-sm text-gray-500">{{ $t('robot.runningConfig.minOnlineUsersDesc') }}</p>
          </FormItem>
        </Col>
        <Col :span="12">
          <FormItem :label="$t('robot.runningConfig.maxOnlineUsers')" name="maxOnlineUsers">
            <InputNumber v-model:value="formState.maxOnlineUsers" :min="0" :placeholder="$t('robot.runningConfig.maxOnlineUsersRequired')" style="width: 100%" />
            <p class="text-sm text-gray-500">{{ $t('robot.runningConfig.maxOnlineUsersDesc') }}</p>
          </FormItem>
        </Col>
        <Col :span="12">
          <FormItem :label="$t('robot.runningConfig.minPopularityRank')" name="minPopularityRank">
            <InputNumber v-model:value="formState.minPopularityRank" :min="0" :placeholder="$t('robot.runningConfig.minPopularityRankRequired')" style="width: 100%" />
            <p class="text-sm text-gray-500">{{ $t('robot.runningConfig.minPopularityRankDesc') }}</p>
          </FormItem>
        </Col>
        <Col :span="12">
          <FormItem :label="$t('robot.runningConfig.maxPopularityRank')" name="maxPopularityRank">
            <InputNumber v-model:value="formState.maxPopularityRank" :min="0" :placeholder="$t('robot.runningConfig.maxPopularityRankRequired')" style="width: 100%" />
            <p class="text-sm text-gray-500">{{ $t('robot.runningConfig.maxPopularityRankDesc') }}</p>
          </FormItem>
        </Col>
        <Col :span="12">
          <FormItem :label="$t('robot.runningConfig.repeatEntetimes')" name="repeatEntetimes">
            <InputNumber v-model:value="formState.repeatEntetimes" :min="0" :placeholder="$t('robot.runningConfig.repeatEntetimesRequired')" style="width: 100%" />
            <p class="text-sm text-gray-500">{{ $t('robot.runningConfig.repeatEntetimesDesc') }}</p>
          </FormItem>
        </Col>
        <Col :span="12">
          <FormItem :label="$t('robot.runningConfig.durationUnit')" name="durationUnit">
            <Select v-model:value="formState.durationUnit" :placeholder="$t('robot.runningConfig.durationUnitRequired')">
              <SelectOption v-for="(item, index) in durationUnitOptions" :key="index" :value="item.value">
                {{ item.label }}
              </SelectOption>
            </Select>
            <p class="text-sm text-gray-500">{{ $t('robot.runningConfig.durationUnitDesc') }}</p>
          </FormItem>
        </Col>
        <Col :span="12">
          <FormItem :label="$t('robot.runningConfig.repeatEnteinterval')" name="repeatEnteinterval">
            <InputNumber v-model:value="formState.repeatEnteinterval" :min="0" :placeholder="$t('robot.runningConfig.repeatEnteintervalRequired')" style="width: 100%" />
            <p class="text-sm text-gray-500">{{ $t('robot.runningConfig.repeatEnteintervalDesc') }}</p>
          </FormItem>
        </Col>
        <Col :span="12">
          <FormItem :label="$t('robot.runningConfig.minLiveDuration')" name="minLiveDuration">
            <InputNumber v-model:value="formState.minLiveDuration" :min="0" :placeholder="$t('robot.runningConfig.minLiveDurationRequired')" style="width: 100%" />
            <p class="text-sm text-gray-500">{{ $t('robot.runningConfig.minLiveDurationDesc') }}</p>
          </FormItem>
        </Col>
        <Col :span="12">
          <FormItem :label="$t('robot.runningConfig.maxLiveDuration')" name="maxLiveDuration">
            <InputNumber v-model:value="formState.maxLiveDuration" :min="0" :placeholder="$t('robot.runningConfig.maxLiveDurationRequired')" style="width: 100%" />
            <p class="text-sm text-gray-500">{{ $t('robot.runningConfig.maxLiveDurationDesc') }}</p>
          </FormItem>
        </Col>
        <Col :span="12">
          <FormItem :label="$t('robot.runningConfig.minStayDuration')" name="minStayDuration">
            <InputNumber v-model:value="formState.minStayDuration" :min="0" :placeholder="$t('robot.runningConfig.minStayDurationRequired')" style="width: 100%" />
            <p class="text-sm text-gray-500">{{ $t('robot.runningConfig.minStayDurationDesc') }}</p>
          </FormItem>
        </Col>
        <Col :span="12">
          <FormItem :label="$t('robot.runningConfig.maxStayDuration')" name="maxStayDuration">
            <InputNumber v-model:value="formState.maxStayDuration" :min="0" :placeholder="$t('robot.runningConfig.maxStayDurationRequired')" style="width: 100%" />
            <p class="text-sm text-gray-500">{{ $t('robot.runningConfig.maxStayDurationDesc') }}</p>
          </FormItem>
        </Col>
        <Col :span="12">
          <FormItem :label="$t('robot.runningConfig.switchLiveInterval')" name="switchLiveInterval">
            <InputNumber v-model:value="formState.switchLiveInterval" :min="0" :placeholder="$t('robot.runningConfig.switchLiveIntervalRequired')" style="width: 100%" />
            <p class="text-sm text-gray-500">{{ $t('robot.runningConfig.switchLiveIntervalDesc') }}</p>
          </FormItem>
        </Col>
        <Col :span="12">
          <FormItem :label="$t('robot.runningConfig.likeProbability')" name="likeProbability">
            <InputNumber v-model:value="formState.likeProbability" :min="0" :max="100" :placeholder="$t('robot.runningConfig.likeProbabilityRequired')" style="width: 100%" />
            <p class="text-sm text-gray-500">{{ $t('robot.runningConfig.likeProbabilityDesc') }}</p>
          </FormItem>
        </Col>
        <Col :span="12">
          <FormItem :label="$t('robot.runningConfig.minFreeHeatTimes')" name="minFreeHeatTimes">
            <InputNumber v-model:value="formState.minFreeHeatTimes" :min="0" :placeholder="$t('robot.runningConfig.minFreeHeatTimesRequired')" style="width: 100%" />
            <p class="text-sm text-gray-500">{{ $t('robot.runningConfig.minFreeHeatTimesDesc') }}</p>
          </FormItem>
        </Col>
        <Col :span="12">
          <FormItem :label="$t('robot.runningConfig.maxFreeHeatTimes')" name="maxFreeHeatTimes">
            <InputNumber v-model:value="formState.maxFreeHeatTimes" :min="0" :placeholder="$t('robot.runningConfig.maxFreeHeatTimesRequired')" style="width: 100%" />
            <p class="text-sm text-gray-500">{{ $t('robot.runningConfig.maxFreeHeatTimesDesc') }}</p>
          </FormItem>
        </Col>
        <Col :span="12">
          <FormItem :label="$t('robot.runningConfig.shareProbability')" name="shareProbability">
            <InputNumber v-model:value="formState.shareProbability" :min="0" :max="100" :placeholder="$t('robot.runningConfig.shareProbabilityRequired')" style="width: 100%" />
            <p class="text-sm text-gray-500">{{ $t('robot.runningConfig.shareProbabilityDesc') }}</p>
          </FormItem>
        </Col>
        <Col :span="12">
          <FormItem :label="$t('robot.runningConfig.followProbability')" name="followProbability">
            <InputNumber v-model:value="formState.followProbability" :min="0" :max="100" :placeholder="$t('robot.runningConfig.followProbabilityRequired')" style="width: 100%" />
            <p class="text-sm text-gray-500">{{ $t('robot.runningConfig.followProbabilityDesc') }}</p>
          </FormItem>
        </Col>
        <Col :span="12">
          <FormItem :label="$t('robot.runningConfig.chatSwitch')" name="chatSwitch">
            <Select v-model:value="formState.chatSwitch" :placeholder="$t('robot.runningConfig.chatSwitchRequired')">
              <SelectOption v-for="(item, index) in switchOptions" :key="index" :value="item.value">
                {{ item.label }}
              </SelectOption>
            </Select>
            <p class="text-sm text-gray-500">{{ $t('robot.runningConfig.chatSwitchDesc') }}</p>
          </FormItem>
        </Col>
        <Col :span="12">
          <FormItem :label="$t('robot.runningConfig.giftSwitch')" name="giftSwitch">
            <Select v-model:value="formState.giftSwitch" :placeholder="$t('robot.runningConfig.giftSwitchRequired')">
              <SelectOption v-for="(item, index) in switchOptions" :key="index" :value="item.value">
                {{ item.label }}
              </SelectOption>
            </Select>
            <p class="text-sm text-gray-500">{{ $t('robot.runningConfig.giftSwitchDesc') }}</p>
          </FormItem>
        </Col>
        <Col :span="12">
          <FormItem :label="$t('robot.runningConfig.activitySwitch')" name="activitySwitch">
            <Select v-model:value="formState.activitySwitch" :placeholder="$t('robot.runningConfig.activitySwitchRequired')">
              <SelectOption v-for="(item, index) in switchOptions" :key="index" :value="item.value">
                {{ item.label }}
              </SelectOption>
            </Select>
            <p class="text-sm text-gray-500">{{ $t('robot.runningConfig.activitySwitchDesc') }}</p>
          </FormItem>
        </Col>
        <Col :span="12">
          <FormItem :label="$t('robot.runningConfig.status')" name="status">
            <Select v-model:value="formState.status" :placeholder="$t('robot.runningConfig.statusRequired')">
              <SelectOption v-for="(item, index) in statusOptions" :key="index" :value="item.value">
                {{ item.label }}
              </SelectOption>
            </Select>
            <p class="text-sm text-gray-500">{{ $t('robot.runningConfig.statusDesc') }}</p>
          </FormItem>
        </Col>
        <Col :span="12">
          <FormItem :label="$t('robot.runningConfig.exclusive')" name="exclusive">
            <Select v-model:value="formState.exclusive" :placeholder="$t('robot.runningConfig.exclusive')">
              <SelectOption v-for="(item, index) in exclusiveOptions" :key="index" :value="item.value">
                {{ item.label }}
              </SelectOption>
            </Select>
            <p class="text-sm text-gray-500">{{ $t('robot.runningConfig.exclusiveDesc') }}</p>
          </FormItem>
        </Col>
        <Col :span="12">
          <FormItem :label="$t('robot.runningConfig.giftConfigUuid')" name="giftConfigUuid">
            <Select v-model:value="formState.giftConfigUuid" :placeholder="$t('robot.runningConfig.giftConfigUuidRequired')" :loading="giftConfigLoading">
              <SelectOption v-for="(item, index) in giftConfigOptions" :key="index" :value="item.uuid">
                {{ item.configName }}
              </SelectOption>
            </Select>
            <p class="text-sm text-gray-500">{{ $t('robot.runningConfig.giftConfigUuidDesc') }}</p>
          </FormItem>
        </Col>
        <!-- 流量爬坡规则 -->
        <Col :span="24">
          <FormItem :label-col="{ span: 3 }" :label="$t('robot.runningConfig.rampUpRules')">
            <div class="ramp-up-rules-container">
              <div v-for="(rule, index) in formState.rampUpRules" :key="index" class="rule-item">
                <Row :gutter="8">
                  <Col :span="10">
                    <InputNumber 
                      v-model:value="rule.minute" 
                      :min="0" 
                      :placeholder="$t('robot.runningConfig.minute')" 
                      style="width: 100%" 
                    />
                  </Col>
                  <Col :span="10">
                    <InputNumber 
                      v-model:value="rule.count" 
                      :min="0" 
                      :placeholder="$t('robot.runningConfig.count')" 
                      style="width: 100%" 
                    />
                  </Col>
                  <Col :span="4">
                    <Button 
                      type="danger" 
                      @click="removeRule(index)" 
                      :disabled="formState.rampUpRules.length <= 1"
                    >
                      {{ $t('common.delete') }}
                    </Button>
                  </Col>
                </Row>
              </div>
              <Button type="dashed" @click="addRule" style="width: 100%; margin-top: 8px;">
                + {{ $t('common.add') }}
              </Button>
            </div>
          </FormItem>
        </Col>
        <Col :span="24">
          <FormItem :label-col="{ span: 3 }" :label="$t('robot.runningConfig.notes')" name="notes">
            <TextArea v-model:value="formState.notes" :placeholder="$t('robot.runningConfig.notes')" />
          </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, Select, Button, message } from 'ant-design-vue';
import { rRunningConfig, giftConfig } from '#/api';

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

const visible = ref(false);
const loading = ref(false);
const giftConfigLoading = ref(false);
const formRef = ref();
const TextArea = Input.TextArea;
const giftConfigOptions = ref([]);

const formState = reactive({
  configName: '',
  notes: '',
  minOnlineUsers: undefined,
  maxOnlineUsers: undefined,
  minLiveDuration: undefined,
  maxLiveDuration: undefined,
  minPopularityRank: undefined,
  maxPopularityRank: undefined,
  minStayDuration: undefined,
  maxStayDuration: undefined,
  repeatEntetimes: undefined,
  repeatEntecycle: undefined,
  repeatEnteinterval: undefined,
  switchLiveInterval: undefined,
  durationUnit: undefined,
  likeProbability: undefined,
  minFreeHeatTimes: undefined,
  maxFreeHeatTimes: undefined,
  shareProbability: undefined,
  followProbability: undefined,
  chatSwitch: undefined,
  giftSwitch: undefined,
  activitySwitch: undefined,
  status: undefined,
  exclusive: undefined,
  giftConfigUuid: '',
  giftConfigName: '',
  rampUpRules: [{ minute: undefined, count: undefined }]
});

const rules = {
  configName: [
    { required: true, message: $t('robot.runningConfig.configNameRequired'), trigger: 'blur' }
  ],
  // minOnlineUsers: [
  //   { required: true, message: $t('robot.runningConfig.minOnlineUsersRequired'), trigger: 'blur' }
  // ],
  // maxOnlineUsers: [
  //   { required: true, message: $t('robot.runningConfig.maxOnlineUsersRequired'), trigger: 'blur' }
  // ],
  // minLiveDuration: [
  //   { required: true, message: $t('robot.runningConfig.minLiveDurationRequired'), trigger: 'blur' }
  // ],
  // maxLiveDuration: [
  //   { required: true, message: $t('robot.runningConfig.maxLiveDurationRequired'), trigger: 'blur' }
  // ],
  // minPopularityRank: [
  //   { required: true, message: $t('robot.runningConfig.minPopularityRankRequired'), trigger: 'blur' }
  // ],
  // maxPopularityRank: [
  //   { required: true, message: $t('robot.runningConfig.maxPopularityRankRequired'), trigger: 'blur' }
  // ],
  // minStayDuration: [
  //   { required: true, message: $t('robot.runningConfig.minStayDurationRequired'), trigger: 'blur' }
  // ],
  // maxStayDuration: [
  //   { required: true, message: $t('robot.runningConfig.maxStayDurationRequired'), trigger: 'blur' }
  // ],
  // repeatEntetimes: [
  //   { required: true, message: $t('robot.runningConfig.repeatEntetimesRequired'), trigger: 'blur' }
  // ],
  // repeatEntecycle: [
  //   { required: true, message: $t('robot.runningConfig.repeatEntecycleRequired'), trigger: 'change' }
  // ],
  // repeatEnteinterval: [
  //   { required: true, message: $t('robot.runningConfig.repeatEnteintervalRequired'), trigger: 'blur' }
  // ],
  // switchLiveInterval: [
  //   { required: true, message: $t('robot.runningConfig.switchLiveIntervalRequired'), trigger: 'blur' }
  // ],
  // likeProbability: [
  //   { required: true, message: $t('robot.runningConfig.likeProbabilityRequired'), trigger: 'blur' }
  // ],
  // minFreeHeatTimes: [
  //   { required: true, message: $t('robot.runningConfig.minFreeHeatTimesRequired'), trigger: 'blur' }
  // ],
  // maxFreeHeatTimes: [
  //   { required: true, message: $t('robot.runningConfig.maxFreeHeatTimesRequired'), trigger: 'blur' }
  // ],
  // shareProbability: [
  //   { required: true, message: $t('robot.runningConfig.shareProbabilityRequired'), trigger: 'blur' }
  // ],
  // followProbability: [
  //   { required: true, message: $t('robot.runningConfig.followProbabilityRequired'), trigger: 'blur' }
  // ],
  // chatSwitch: [
  //   { required: true, message: $t('robot.runningConfig.chatSwitchRequired'), trigger: 'change' }
  // ],
  // giftSwitch: [
  //   { required: true, message: $t('robot.runningConfig.giftSwitchRequired'), trigger: 'change' }
  // ],
  // activitySwitch: [
  //   { required: true, message: $t('robot.runningConfig.activitySwitchRequired'), trigger: 'change' }
  // ],
  // status: [
  //   { required: true, message: $t('robot.runningConfig.statusRequired'), trigger: 'change' }
  // ],
  // giftConfigUuid: [
  //   { required: true, message: $t('robot.runningConfig.giftConfigUuidRequired'), trigger: 'change' }
  // ]
};

const statusOptions = [
  { label: $t('robot.runningConfig.statusOptions.v0'), value: 0 },
  { label: $t('robot.runningConfig.statusOptions.v1'), value: 1 }
];

const switchOptions = [
  { label: $t('robot.runningConfig.switchOptions.0'), value: 0 },
  { label: $t('robot.runningConfig.switchOptions.1'), value: 1 }
];

const repeatEntecycleOptions = [
  { label: $t('robot.runningConfig.repeatEntecycleOptions.1'), value: 1 },
  { label: $t('robot.runningConfig.repeatEntecycleOptions.2'), value: 2 },
  { label: $t('robot.runningConfig.repeatEntecycleOptions.3'), value: 3 },
  { label: $t('robot.runningConfig.repeatEntecycleOptions.4'), value: 4 }
];

const exclusiveOptions = [
  { label: $t('robot.runningConfig.exclusiveOptions.v0'), value: 0 },
  { label: $t('robot.runningConfig.exclusiveOptions.v1'), value: 1 }
];

const durationUnitOptions = [
  { label: $t('robot.runningConfig.durationUnitOptions.1'), value: 1 },
  { label: $t('robot.runningConfig.durationUnitOptions.2'), value: 2 },
  { label: $t('robot.runningConfig.durationUnitOptions.3'), value: 3 },
  { label: $t('robot.runningConfig.durationUnitOptions.4'), value: 4 },
  { label: $t('robot.runningConfig.durationUnitOptions.5'), value: 5 },
  { label: $t('robot.runningConfig.durationUnitOptions.6'), value: 6 },
  { label: $t('robot.runningConfig.durationUnitOptions.7'), value: 7 }
];

// 添加规则
function addRule() {
  formState.rampUpRules.push({ minute: undefined, count: undefined });
}

// 删除规则
function removeRule(index) {
  if (formState.rampUpRules.length > 1) {
    formState.rampUpRules.splice(index, 1);
  }
}

// 获取送礼配置列表
async function fetchGiftConfigList() {
  giftConfigLoading.value = true;
  try {
    const res = await giftConfig.queryList({});
    if (!res.error && res.data) {
      giftConfigOptions.value = res.data.list || [];
    }
  } catch (error) {
    console.error('获取送礼配置列表失败:', error);
  } finally {
    giftConfigLoading.value = false;
  }
}

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

function _open() {
  visible.value = true;
  fetchGiftConfigList();
}

function handleSubmit() {
  formRef.value.validate().then(() => {
    loading.value = true;

    // 组装数据，将rampUpRules转换为JSON字符串
    const submitData = {
      ...formState,
      rampUpRules: JSON.stringify(formState.rampUpRules.filter(rule => rule.minute !== undefined && rule.count !== undefined))
    };

    rRunningConfig.create(submitData).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();
  // 重置rampUpRules
  formState.rampUpRules = [{ minute: undefined, count: undefined }];
}

defineExpose({
  _open
});
</script>

<style scoped>
.ramp-up-rules-container {
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  padding: 12px;
}

.rule-item {
  margin-bottom: 8px;
}

.rule-item:last-child {
  margin-bottom: 0;
}
</style>