<template>
  <Modal :maskClosable="false" :keyboard="false" v-model:open="data.isShowModal" :footer="null"
    :title="$t('robot.configRelation.editTitle')" width="60%" @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.configRelation.robotGroupUuid')" name="robotGroupUuid">
            <Select allow-clear showSearch :filterOption="selectFilterOption" v-model:value="form.robotGroupUuid"
              :loading="data.groupLoading" :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.configRelation.robotUuid')" name="robotUuid">
            <Select allow-clear showSearch :filterOption="selectFilterOption" v-model:value="form.robotUuid"
              :loading="data.robotLoading" :placeholder="$t('common.placeholderIn')" @change="handleRobotChange">
              <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.configRelation.configType')" name="configType">
            <Select allow-clear showSearch :filterOption="selectFilterOption" v-model:value="form.configType" allowClear
              :placeholder="$t('common.placeholderIn')" @change="handleConfigTypeChange">
              <SelectOption v-for="(item, index) in data.configTypeOptions" :key="index" :value="item.value"
                :label="item.label" :text="item.label">{{ item.label }}
              </SelectOption>
            </Select>
          </FormItem>
        </Col>
        <Col :span="12">
          <FormItem :label="$t('robot.configRelation.configUuid')" name="configUuid">
            <Select allow-clear showSearch :filterOption="selectFilterOption" v-model:value="form.configUuid"
              :loading="data.configLoading" :placeholder="$t('common.placeholderIn')" :disabled="form.configType !== 1">
              <SelectOption v-for="(item, index) in data.configOptions" :key="index" :value="item.uuid"
                :label="item.configName" :text="item.configName">{{ item.configName }}
              </SelectOption>
            </Select>
          </FormItem>
        </Col>
        <Col :span="12">
          <FormItem :label="$t('robot.configRelation.configPriority')" name="configPriority">
            <Select allow-clear showSearch :filterOption="selectFilterOption" v-model:value="form.configPriority"
              allowClear :placeholder="$t('common.placeholderIn')">
              <SelectOption v-for="(item, index) in data.configPriorityOptions" :key="index" :value="item.value"
                :label="item.label" :text="item.label">{{ item.label }}
              </SelectOption>
            </Select>
          </FormItem>
        </Col>
        <!-- 动态时间组 -->
        <Col :span="24">
          <FormItem :label-col="{ span: 3 }" :label="$t('robot.configRelation.timeGroups')">
            <div v-for="(timeGroup, index) in form.timeGroups" :key="index" class="time-group-item">
              <Row :gutter="12">
                <Col :span="9">
                  <FormItem :name="['timeGroups', index, 'startTime']"
                    :rules="[{ required: true, message: '请选择开始时间' }, { validator: validateStartTime }]">
                    <Select v-model:value="timeGroup.startTime" allowClear :placeholder="$t('common.placeholderIn')"
                      style="width: 100%" @change="handleTimeChange(index)">
                      <SelectOption v-for="hour in data.timeOptions" :key="hour" :value="hour">
                        {{ hour }}
                      </SelectOption>
                    </Select>
                  </FormItem>
                </Col>
                <Col :span="2">
                  <div style="text-align: center;">~</div>
                </Col>
                <Col :span="9">
                  <FormItem :name="['timeGroups', index, 'endTime']"
                    :rules="[{ required: true, message: '请选择结束时间' }, { validator: validateEndTime }]">
                    <Select v-model:value="timeGroup.endTime" allowClear :placeholder="$t('common.placeholderIn')"
                      style="width: 100%" @change="handleTimeChange(index)">
                      <SelectOption v-for="hour in data.timeOptions" :key="hour" :value="hour">
                        {{ hour }}
                      </SelectOption>
                    </Select>
                  </FormItem>
                </Col>
                <Col :span="4">
                  <div style="display: flex; align-items: right; height: 32px;justify-content: flex-end;">
                    <Button type="link" danger @click="removeTimeGroup(index)" :disabled="form.timeGroups.length <= 1">
                      {{ $t('common.delete') }}
                    </Button>
                    <Button type="link" @click="addTimeGroup"
                      v-if="form.timeGroups.length < 5 && index === form.timeGroups.length - 1">
                      {{ $t('common.add') }}
                    </Button>
                  </div>
                </Col>
              </Row>
            </div>
          </FormItem>
        </Col>
        <Col :span="24">
          <FormItem :label-col="{ span: 3 }" :label="$t('robot.configRelation.remark')" name="remark">
            <TextArea v-model:value="form.remark" 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>

<style scoped>
.time-group-item {
  margin-bottom: 16px;
}

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

<script setup lang="ts">
import { reactive, ref, onMounted } from "vue";
import { $t } from '@vben/locales';
import { Modal, Form, Input, Select, Row, Col, Button, DatePicker, message } from 'ant-design-vue';
import { configRelation, robotAccount, robotGroup, rRunningConfig } 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,
  groupLoading: false,
  robotLoading: false,
  configLoading: false,
  groupOptions: [],
  robotOptions: [],
  configOptions: [],
  configTypeOptions: [
    { label: $t('robot.configRelation.configTypeOptions.v1'), value: 1 },
    { label: $t('robot.configRelation.configTypeOptions.v3'), value: 3 }
  ],
  configPriorityOptions: [
    { label: $t('robot.configRelation.configPriorityOptions.v1'), value: 1 },
    { label: $t('robot.configRelation.configPriorityOptions.v2'), value: 2 },
    { label: $t('robot.configRelation.configPriorityOptions.v3'), value: 3 },
    { label: $t('robot.configRelation.configPriorityOptions.v4'), value: 4 }
  ],
  // 24小时制时间选项
  timeOptions: Array.from({ length: 25 }, (_, i) => i.toString().padStart(2, '0'))
})

const form = reactive({
  uuid: null,
  robotGroupUuid: '',
  robotUuid: '',
  configType: undefined,
  configName: '',
  configUuid: '',
  configPriority: undefined,
  remark: '',
  // 动态时间组数组，初始包含一个时间组
  timeGroups: [
    {
      startTime: null,
      endTime: null
    }
  ]
})

// 选择框过滤方法
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) {
      data.groupOptions = res.data || [];
    }
  } catch (error) {
    console.error('加载分组数据失败:', error);
  } finally {
    data.groupLoading = false;
  }
}

// 加载机器人选项
const loadRobotOptions = async (robotGroupUuid?: string) => {
  data.robotLoading = true;
  try {
    const params: any = {};
    if (robotGroupUuid) {
      params.groupId = robotGroupUuid;
    }
    const res = await robotAccount.queryList(params);
    if (!res.error) {
      data.robotOptions = res.data || [];
    }
  } catch (error) {
    console.error('加载机器人数据失败:', error);
  } finally {
    data.robotLoading = false;
  }
}

// 加载配置选项
const loadConfigOptions = async () => {
  if (form.configType !== 1) {
    data.configOptions = [];
    return;
  }

  data.configLoading = true;
  try {
    const res = await rRunningConfig.queryList({});
    if (!res.error) {
      data.configOptions = res.data || [];
    }
  } catch (error) {
    console.error('加载配置数据失败:', error);
  } finally {
    data.configLoading = false;
  }
}

// 分组选择变化处理
const handleGroupChange = (value: string) => {
  form.groupName = '';
  form.robotGroupUuid = value;

  if (value) {
    //查找机器人分组
    const group = data.groupOptions.find((item: any) => item.uuid === value);
    if (group) {
      form.groupName = group.name;
    }
  }

  form.robotUuid = ''; // 清空机器人选择
  form.robotAccount = ''; // 清空机器人账号
  loadRobotOptions(value); // 根据分组筛选机器人
}

// 机器人选择变化处理
const handleRobotChange = (value: string) => {
  form.robotUuid = value;
  //查找该值的机器人的账号
  const robot = data.robotOptions.find((item: any) => item.uuid === value);
  if (robot) {
    form.robotAccount = robot.email;
  }
}

// 配置类型变化处理
const handleConfigTypeChange = (value: number) => {
  form.configType = value;
  if (value === 1) {
    loadConfigOptions();
  } else {
    data.configOptions = [];
    form.configUuid = '';
  }
}

// 添加时间组
const addTimeGroup = () => {
  if (form.timeGroups.length < 5) {
    form.timeGroups.push({
      startTime: null,
      endTime: null
    });
  }
}

// 删除时间组
const removeTimeGroup = (index: number) => {
  if (form.timeGroups.length > 1) {
    form.timeGroups.splice(index, 1);
  }
}

// 时间变化处理
const handleTimeChange = (index: number) => {
  // 触发验证
  formRef.value?.validateFields([['timeGroups', index, 'startTime'], ['timeGroups', index, 'endTime']]);
}

// 开始时间验证
const validateStartTime = (_rule: any, value: string) => {
  if (!value) {
    return Promise.reject(new Error('请选择开始时间'));
  }

  const index = parseInt(_rule.field.split('.')[1]);
  const endTime = form.timeGroups[index]?.endTime;

  if (endTime && value >= endTime) {
    return Promise.reject(new Error('开始时间必须小于结束时间'));
  }

  return Promise.resolve();
}

// 结束时间验证
const validateEndTime = (_rule: any, value: string) => {
  if (!value) {
    return Promise.reject(new Error('请选择结束时间'));
  }

  const index = parseInt(_rule.field.split('.')[1]);
  const startTime = form.timeGroups[index]?.startTime;

  if (startTime && value <= startTime) {
    return Promise.reject(new Error('结束时间必须大于开始时间'));
  }

  return Promise.resolve();
}

// 表单规则
const rules = reactive({
  robotGroupUuid: [{
    validator: (rule: any, value: string) => {
      if (!value && !form.robotUuid) {
        return Promise.reject(new Error('请选择分组或机器人'));
      }
      return Promise.resolve();
    }
  }],
  robotUuid: [{
    validator: (rule: any, value: string) => {
      if (!value && !form.robotGroupUuid) {
        return Promise.reject(new Error('请选择分组或机器人'));
      }
      return Promise.resolve();
    }
  }]
})

const formRef = ref();

function handleSubmit() {
  data.loading = true;
  formRef.value.validate().then(() => {
    // 验证时间组
    const hasValidTimeGroup = form.timeGroups.some(group => group.startTime && group.endTime);
    if (!hasValidTimeGroup) {
      message?.error('请至少填写一个有效的时间组');
      data.loading = false;
      return;
    }

    // 将时间组数据按序号累计设置到form的字段上
    form.timeGroups.forEach((group, index) => {
      const groupIndex = index + 1;
      form[`startTime${groupIndex}`] = group.startTime;
      form[`endTime${groupIndex}`] = group.endTime;
    });

    // 准备提交数据
    const submitData = {
      ...form,
      // 将时间组转换为字符串格式，用于后端处理
      timeGroups: form.timeGroups.map((group, index) => ({
        ...group,
        groupIndex: index + 1
      }))
    };

    configRelation.updateByUid(submitData).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;

  // 处理时间组数据
  let timeGroups = [];
  if (item.startTime !== null && item.endTime !== null) {
    timeGroups.push({
      startTime: item.startTime.toString().padStart(2, '0'),
      endTime: item.endTime.toString().padStart(2, '0')
    })
  }
  if (item.startTime1 !== null && item.endTime1 !== null) {
    timeGroups.push({
      startTime: item.startTime1.toString().padStart(2, '0'),
      endTime: item.endTime1.toString().padStart(2, '0')
    })
  }
  if (item.startTime2 !== null && item.endTime2 !== null) {
    timeGroups.push({
      startTime: item.startTime2.toString().padStart(2, '0'),
      endTime: item.endTime2.toString().padStart(2, '0')
    })
  }
  if (item.startTime3 !== null && item.endTime3 !== null) {
    timeGroups.push({
      startTime: item.startTime3.toString().padStart(2, '0'),
      endTime: item.endTime3.toString().padStart(2, '0')
    })
  }
  if (item.startTime4 !== null && item.endTime4 !== null) {
    timeGroups.push({
      startTime: item.startTime4.toString().padStart(2, '0'),
      endTime: item.endTime4.toString().padStart(2, '0')
    })
  }
  if (item.startTime5 !== null && item.endTime5 !== null) {
    timeGroups.push({
      startTime: item.startTime5.toString().padStart(2, '0'),
      endTime: item.endTime5.toString().padStart(2, '0')
    })
  }
  form.timeGroups = timeGroups;

  Object.assign(form, {
    ...item,
    timeGroups: timeGroups
  });

  loadGroupOptions();
  loadRobotOptions();
  if (form.configType === 1) {
    loadConfigOptions();
  }
}

defineExpose({
  _open
})
</script>