<template>
  <el-dialog 
    :title="form.id ? '编辑' : '新增'" 
    v-model="visible"
    :close-on-click-modal="false" 
    draggable
    width="90%"
    top="5vh"
    class="entrance-rule-dialog">
    <el-form 
      ref="dataFormRef" 
      :model="form" 
      :rules="dataRules" 
      label-width="100px" 
      :validate-on-rule-change="false"
      v-loading="loading">
      
      <!-- 基本信息 -->
      <el-card shadow="never" class="mb20">
        <template #header>
          <span style="font-weight: bold;">基本信息</span>
        </template>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="规则名称" prop="ruleName">
              <el-input 
                v-model="form.ruleName" 
                placeholder="请输入规则名称" 
                clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="假期模式" prop="isHoliday">
              <el-radio-group v-model="form.isHoliday">
                <el-radio label="0">关闭</el-radio>
                <el-radio label="1">开启</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <!-- 规则配置 -->
      <el-card shadow="never">
        <template #header>
          <span style="font-weight: bold;">规则配置</span>
        </template>
        <el-tabs v-model="activeTab" type="border-card">
          <!-- 大门特殊规则 -->
          <el-tab-pane label="大门特殊规则" name="position">
            <div class="rule-config-section">
              <el-form-item label="禁用星期">
                <el-checkbox-group v-model="form.positionDisableRule.weekList">
                  <el-checkbox label="1">周日</el-checkbox>
                  <el-checkbox label="2">周一</el-checkbox>
                  <el-checkbox label="3">周二</el-checkbox>
                  <el-checkbox label="4">周三</el-checkbox>
                  <el-checkbox label="5">周四</el-checkbox>
                  <el-checkbox label="6">周五</el-checkbox>
                  <el-checkbox label="7">周六</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
              <el-form-item label="禁用位置ID">
                <el-input 
                  v-model="positionListInput" 
                  placeholder="请输入位置ID，多个用逗号分隔（如：8,29）"
                  @blur="handlePositionListBlur" />
                <div class="form-tip">当前配置：{{ form.positionDisableRule.positionList.join(', ') || '无' }}</div>
              </el-form-item>
            </div>
          </el-tab-pane>

          <!-- 走读生大门时段(进) -->
          <el-tab-pane label="走读生大门(进)" name="dayIn">
            <TimeRuleTableComponent 
              :rule-list="form.dayRuleList" 
              rule-type="dayRuleList" />
          </el-tab-pane>

          <!-- 走读生大门时段(出) -->
          <el-tab-pane label="走读生大门(出)" name="dayOut">
            <TimeRuleTableComponent 
              :rule-list="form.outDayRuleList" 
              rule-type="dayRuleList" />
          </el-tab-pane>

          <!-- 住宿生大门时段(进) -->
          <el-tab-pane label="住宿生大门(进)" name="dormIn">
            <TimeRuleTableComponent 
              :rule-list="form.dormRuleList" 
              rule-type="dormRuleList" />
          </el-tab-pane>

          <!-- 住宿生大门时段(出) -->
          <el-tab-pane label="住宿生大门(出)" name="dormOut">
            <TimeRuleTableComponent 
              :rule-list="form.outDormRuleList" 
              rule-type="dormRuleList" />
          </el-tab-pane>

          <!-- 住宿生宿舍时段(进) -->
          <el-tab-pane label="住宿生宿舍(进)" name="roomIn">
            <TimeRuleTableComponent 
              :rule-list="form.roomInRuleList" 
              rule-type="dormRuleList" />
          </el-tab-pane>

          <!-- 住宿生宿舍时段(出) -->
          <el-tab-pane label="住宿生宿舍(出)" name="roomOut">
            <TimeRuleTableComponent 
              :rule-list="form.roomOutRuleList" 
              rule-type="dormRuleList" />
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button type="primary" @click="onSubmit" :disabled="loading">确 认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="EntranceRuleDialog">
import { ref, reactive, nextTick, onMounted, defineComponent, h } from 'vue'
import { useMessage } from "/@/hooks/message";
import { getObj, addObj, putObj } from '/@/api/stuwork/entrancerule'
import { ElTable, ElTableColumn, ElTimePicker, ElButton } from 'element-plus'
import { Plus, Delete } from '@element-plus/icons-vue'

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

// 时间段规则表格组件
const TimeRuleTableComponent = defineComponent({
  name: 'TimeRuleTableComponent',
  props: {
    ruleList: {
      type: Array,
      required: true
    },
    ruleType: {
      type: String,
      required: true
    }
  },
  setup(props: any) {
    const getTimeList = (dayRule: any) => {
      return props.ruleType === 'dayRuleList' ? dayRule.dayRuleList : dayRule.dormRuleList
    }

    const addTimeSlot = (dayRule: any) => {
      const timeList = getTimeList(dayRule)
      timeList.push({ startTime: '', endTime: '' })
    }

    const removeTimeSlot = (dayRule: any, index: number) => {
      const timeList = getTimeList(dayRule)
      if (timeList.length > 1) {
        timeList.splice(index, 1)
      }
    }

    return () => {
      return h('div', { class: 'time-rule-table' }, [
        h(ElTable, {
          data: props.ruleList,
          border: true,
          style: { width: '100%' }
        }, {
          default: () => [
            h(ElTableColumn, {
              prop: 'week',
              label: '星期',
              width: '100',
              align: 'center'
            }),
            h(ElTableColumn, {
              label: '时间段配置',
              align: 'center',
              minWidth: '600'
            }, {
              default: ({ row }: any) => {
                const timeList = getTimeList(row)
                return h('div', { class: 'time-slots-container' }, 
                  timeList.map((timeSlot: any, index: number) => {
                    // 通过数组索引更新，确保响应式
                    const updateStartTime = (val: string) => {
                      const list = getTimeList(row)
                      if (list[index]) {
                        list[index].startTime = val || ''
                      }
                    }
                    const updateEndTime = (val: string) => {
                      const list = getTimeList(row)
                      if (list[index]) {
                        list[index].endTime = val || ''
                      }
                    }
                    return h('div', { key: index, class: 'time-slot-item' }, [
                      h(ElTimePicker, {
                        modelValue: timeSlot.startTime || '',
                        'onUpdate:modelValue': updateStartTime,
                        format: 'HH:mm',
                        valueFormat: 'HH:mm',
                        placeholder: '开始时间',
                        style: { width: '120px', marginRight: '10px' }
                      }),
                      h('span', { style: { margin: '0 10px' } }, '至'),
                      h(ElTimePicker, {
                        modelValue: timeSlot.endTime || '',
                        'onUpdate:modelValue': updateEndTime,
                        format: 'HH:mm',
                        valueFormat: 'HH:mm',
                        placeholder: '结束时间',
                        style: { width: '120px', marginRight: '10px' }
                      }),
                      h(ElButton, {
                        type: 'danger',
                        size: 'small',
                        icon: Delete,
                        circle: true,
                        onClick: () => removeTimeSlot(row, index),
                        disabled: timeList.length <= 1,
                        style: { marginLeft: '10px' }
                      })
                    ])
                  })
                )
              }
            }),
            h(ElTableColumn, {
              label: '操作',
              width: '120',
              align: 'center'
            }, {
              default: ({ row }: any) => 
                h(ElButton, {
                  type: 'primary',
                  size: 'small',
                  icon: Plus,
                  onClick: () => addTimeSlot(row)
                }, { default: () => '添加时段' })
            })
          ]
        })
      ])
    }
  }
})

// 定义变量内容
const dataFormRef = ref();
const visible = ref(false)
const loading = ref(false)
const activeTab = ref('position')
const positionListInput = ref('')

// 提交表单数据
const form = reactive({
  id: '',
  ruleName: '',
  isHoliday: '0',
  // 规则配置数据结构
  positionDisableRule: {
    weekList: [] as string[],
    positionList: [] as string[]
  },
  dayRuleList: [] as any[],
  outDayRuleList: [] as any[],
  dormRuleList: [] as any[],
  outDormRuleList: [] as any[],
  roomInRuleList: [] as any[],
  roomOutRuleList: [] as any[]
});

// 定义校验规则
const dataRules = ref({
  ruleName: [
    { required: true, message: '请输入规则名称', trigger: 'blur' }
  ]
});

// 时间段规则表格组件
const TimeRuleTable = defineComponent({
  name: 'TimeRuleTable',
  props: {
    ruleList: {
      type: Array,
      required: true
    },
    ruleType: {
      type: String,
      required: true
    }
  },
  setup(props: any) {
    const getTimeList = (dayRule: any) => {
      return props.ruleType === 'dayRuleList' ? dayRule.dayRuleList : dayRule.dormRuleList
    }

    const addTimeSlot = (dayRule: any) => {
      const timeList = getTimeList(dayRule)
      timeList.push({ startTime: '', endTime: '' })
    }

    const removeTimeSlot = (dayRule: any, index: number) => {
      const timeList = getTimeList(dayRule)
      if (timeList.length > 1) {
        timeList.splice(index, 1)
      }
    }

    return () => {
      return h('div', { class: 'time-rule-table' }, [
        h(ElTable, {
          data: props.ruleList,
          border: true,
          style: { width: '100%' }
        }, {
          default: () => [
            h(ElTableColumn, {
              prop: 'week',
              label: '星期',
              width: '100',
              align: 'center'
            }),
            h(ElTableColumn, {
              label: '时间段配置',
              align: 'center',
              minWidth: '600'
            }, {
              default: ({ row }: any) => {
                const timeList = getTimeList(row)
                return h('div', { class: 'time-slots-container' }, 
                  timeList.map((timeSlot: any, index: number) => 
                    h('div', { key: index, class: 'time-slot-item' }, [
                      h(ElTimePicker, {
                        modelValue: timeSlot.startTime,
                        'onUpdate:modelValue': (val: string) => { timeSlot.startTime = val },
                        format: 'HH:mm',
                        valueFormat: 'HH:mm',
                        placeholder: '开始时间',
                        style: { width: '120px', marginRight: '10px' }
                      }),
                      h('span', { style: { margin: '0 10px' } }, '至'),
                      h(ElTimePicker, {
                        modelValue: timeSlot.endTime,
                        'onUpdate:modelValue': (val: string) => { timeSlot.endTime = val },
                        format: 'HH:mm',
                        valueFormat: 'HH:mm',
                        placeholder: '结束时间',
                        style: { width: '120px', marginRight: '10px' }
                      }),
                      h(ElButton, {
                        type: 'danger',
                        size: 'small',
                        icon: Delete,
                        circle: true,
                        onClick: () => removeTimeSlot(row, index),
                        disabled: timeList.length <= 1,
                        style: { marginLeft: '10px' }
                      })
                    ])
                  )
                )
              }
            }),
            h(ElTableColumn, {
              label: '操作',
              width: '120',
              align: 'center'
            }, {
              default: ({ row }: any) => 
                h(ElButton, {
                  type: 'primary',
                  size: 'small',
                  icon: Plus,
                  onClick: () => addTimeSlot(row)
                }, { default: () => '添加时段' })
            })
          ]
        })
      ])
    }
  }
})

// 处理位置列表输入
const handlePositionListBlur = () => {
  if (positionListInput.value) {
    form.positionDisableRule.positionList = positionListInput.value
      .split(',')
      .map(item => item.trim())
      .filter(item => item)
  } else {
    form.positionDisableRule.positionList = []
  }
}

// 打开弹窗
const openDialog = (id?: string) => {
  visible.value = true
  form.id = ''
  positionListInput.value = ''
  
  // 重置表单数据
  nextTick(() => {
    dataFormRef.value?.resetFields()
    form.id = ''
    form.ruleName = ''
    form.isHoliday = '0'
    // 初始化规则配置数据结构
    initRuleData()
    
    // 如果是编辑，获取详情
    if (id) {
      getEntranceRuleData(id)
    }
  })
}

// 初始化规则数据结构
const initRuleData = () => {
  // 大门特殊规则
  form.positionDisableRule = {
    weekList: [],
    positionList: []
  }
  
  // 初始化7天的规则数组
  const weekDays = [
    { week: '周一', weekNo: '2' },
    { week: '周二', weekNo: '3' },
    { week: '周三', weekNo: '4' },
    { week: '周四', weekNo: '5' },
    { week: '周五', weekNo: '6' },
    { week: '周六', weekNo: '7' },
    { week: '周日', weekNo: '1' }
  ]
  
  // 走读生大门时段(进) - 每天至少1个时间段
  form.dayRuleList = weekDays.map(day => ({
    week: day.week,
    weekNo: day.weekNo,
    dayRuleList: [{ startTime: '', endTime: '' }]
  }))
  
  // 走读生大门时段(出)
  form.outDayRuleList = weekDays.map(day => ({
    week: day.week,
    weekNo: day.weekNo,
    dayRuleList: [{ startTime: '', endTime: '' }]
  }))
  
  // 住宿生大门时段(进)
  form.dormRuleList = weekDays.map(day => ({
    week: day.week,
    weekNo: day.weekNo,
    dormRuleList: [{ startTime: '', endTime: '' }]
  }))
  
  // 住宿生大门时段(出)
  form.outDormRuleList = weekDays.map(day => ({
    week: day.week,
    weekNo: day.weekNo,
    dormRuleList: [{ startTime: '', endTime: '' }]
  }))
  
  // 住宿生宿舍时段(进)
  form.roomInRuleList = weekDays.map(day => ({
    week: day.week,
    weekNo: day.weekNo,
    dormRuleList: [{ startTime: '', endTime: '' }]
  }))
  
  // 住宿生宿舍时段(出)
  form.roomOutRuleList = weekDays.map(day => ({
    week: day.week,
    weekNo: day.weekNo,
    dormRuleList: [{ startTime: '', endTime: '' }]
  }))
}

// 获取详情
const getEntranceRuleData = async (id: string) => {
  loading.value = true
  try {
    const res = await getObj({ id })
    if (res.data) {
      Object.assign(form, {
        id: res.data.id || '',
        ruleName: res.data.ruleName || '',
        isHoliday: res.data.isHoliday || '0',
        positionDisableRule: res.data.positionDisableRule || { weekList: [], positionList: [] },
        dayRuleList: res.data.dayRuleList || [],
        outDayRuleList: res.data.outDayRuleList || [],
        dormRuleList: res.data.dormRuleList || [],
        outDormRuleList: res.data.outDormRuleList || [],
        roomInRuleList: res.data.roomInRuleList || [],
        roomOutRuleList: res.data.roomOutRuleList || []
      })
      
      // 设置位置列表输入框
      if (form.positionDisableRule.positionList.length > 0) {
        positionListInput.value = form.positionDisableRule.positionList.join(', ')
      }
      
      // 确保每个规则列表都有数据
      const weekDays = [
        { week: '周一', weekNo: '2' },
        { week: '周二', weekNo: '3' },
        { week: '周三', weekNo: '4' },
        { week: '周四', weekNo: '5' },
        { week: '周五', weekNo: '6' },
        { week: '周六', weekNo: '7' },
        { week: '周日', weekNo: '1' }
      ]
      
      // 如果某个规则列表为空，初始化它
      if (form.dayRuleList.length === 0) {
        form.dayRuleList = weekDays.map(day => ({
          week: day.week,
          weekNo: day.weekNo,
          dayRuleList: [{ startTime: '', endTime: '' }]
        }))
      }
      if (form.outDayRuleList.length === 0) {
        form.outDayRuleList = weekDays.map(day => ({
          week: day.week,
          weekNo: day.weekNo,
          dayRuleList: [{ startTime: '', endTime: '' }]
        }))
      }
      if (form.dormRuleList.length === 0) {
        form.dormRuleList = weekDays.map(day => ({
          week: day.week,
          weekNo: day.weekNo,
          dormRuleList: [{ startTime: '', endTime: '' }]
        }))
      }
      if (form.outDormRuleList.length === 0) {
        form.outDormRuleList = weekDays.map(day => ({
          week: day.week,
          weekNo: day.weekNo,
          dormRuleList: [{ startTime: '', endTime: '' }]
        }))
      }
      if (form.roomInRuleList.length === 0) {
        form.roomInRuleList = weekDays.map(day => ({
          week: day.week,
          weekNo: day.weekNo,
          dormRuleList: [{ startTime: '', endTime: '' }]
        }))
      }
      if (form.roomOutRuleList.length === 0) {
        form.roomOutRuleList = weekDays.map(day => ({
          week: day.week,
          weekNo: day.weekNo,
          dormRuleList: [{ startTime: '', endTime: '' }]
        }))
      }
    }
  } catch (err: any) {
    useMessage().error(err.msg || '获取详情失败')
  } finally {
    loading.value = false
    nextTick(() => {
      dataFormRef.value?.clearValidate()
    })
  }
}

// 提交
const onSubmit = async () => {
  const valid = await dataFormRef.value?.validate().catch(() => {})
  if (!valid) return false

  loading.value = true
  try {
    // 直接使用form中的数据，确保用户输入的数据能够提交
    const params: any = {
      ruleName: form.ruleName,
      isHoliday: form.isHoliday,
      positionDisableRule: form.positionDisableRule,
      dayRuleList: form.dayRuleList,
      outDayRuleList: form.outDayRuleList,
      dormRuleList: form.dormRuleList,
      outDormRuleList: form.outDormRuleList,
      roomInRuleList: form.roomInRuleList,
      roomOutRuleList: form.roomOutRuleList
    }
    
    if (form.id) {
      params.id = form.id
      await putObj(params)
      useMessage().success('编辑成功')
    } else {
      await addObj(params)
      useMessage().success('新增成功')
    }
    
    visible.value = false
    emit('refresh')
  } catch (err: any) {
    useMessage().error(err.msg || (form.id ? '编辑失败' : '新增失败'))
  } finally {
    loading.value = false
  }
}

// 初始化
onMounted(() => {
  // 初始化规则数据结构
  initRuleData()
})

// 暴露方法给父组件
defineExpose({
  openDialog
})
</script>


<style scoped lang="scss">
.mb20 {
  margin-bottom: 20px;
}

.rule-config-section {
  padding: 20px;
  
  .form-tip {
    font-size: 12px;
    color: #909399;
    margin-top: 5px;
  }
}

.time-rule-table {
  padding: 20px;
  
  .time-slots-container {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    align-items: center;
  }
  
  .time-slot-item {
    display: flex;
    align-items: center;
    padding: 5px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    background-color: #f5f7fa;
  }
}

:deep(.el-card__header) {
  background-color: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-tabs--border-card) {
  border: 1px solid #dcdfe6;
  box-shadow: none;
}

:deep(.el-table) {
  .el-table__cell {
    padding: 10px 0;
  }
}
</style>
