<template>
    <div class="cron-simplified">
        <!-- 周期选择 -->
        <div class="period-section">
            <div class="period-title">周期</div>
            <div class="period-buttons">
                <el-button
                    v-for="period in periodOptions"
                    :key="period.value"
                    :type="selectedPeriod === period.value ? 'primary' : ''"
                    @click="handlePeriodChange(period.value)"
                    class="period-btn"
                >
                    {{ period.label }}
                    <span v-if="period.value === 'hour'"> 0-23 </span>
                </el-button>
            </div>
        </div>

        <!-- 时间输入区域 -->
        <div class="time-input-section" v-if="showTimeInputs">
            <div class="time-inputs">
                <div class="time-input-item" v-if="showMonth">
                    <label>月份</label>
                    <el-input-number
                        v-model="timeValues.month"
                        :min="1"
                        :max="12"
                        :controls="false"
                        size="default"
                        class="time-input"
                    />
                </div>
                <div class="time-input-item" v-if="showDay">
                    <label>日期</label>
                    <el-input-number
                        v-model="timeValues.day"
                        :min="1"
                        :max="31"
                        :controls="false"
                        size="default"
                        class="time-input"
                    />
                </div>
                <div class="time-input-item" v-if="showHour">
                    <label>小时(0-23)</label>
                    <el-input-number
                        v-model="timeValues.hour"
                        :min="0"
                        :max="23"
                        :controls="false"
                        size="default"
                        class="time-input"
                    />
                </div>
                <div class="time-input-item" v-if="showMinute">
                    <label>分钟</label>
                    <el-input-number
                        v-model="timeValues.minute"
                        :min="0"
                        :max="59"
                        :controls="false"
                        size="default"
                        class="time-input"
                    />
                </div>
            </div>
        </div>

        <!-- 星期选择 -->
        <div class="week-section" v-if="showWeek">
            <div class="week-title">星期</div>
            <div class="week-buttons">
                <el-button
                    v-for="week in weekOptions"
                    :key="week.value"
                    :type="selectedWeek === week.value ? 'primary' : ''"
                    @click="handleWeekChange(week.value)"
                    class="week-btn"
                >
                    {{ week.label }}
                </el-button>
            </div>
        </div>

        <!-- Cron表达式显示 -->
        <!-- <div class="cron-result-section">
            <div class="result-title">时间表达式</div>
            <div class="cron-expression">{{ crontabValueString }}</div>
        </div> -->

        <!-- 最近5次运行时间 -->
        <CrontabResult :ex="crontabValueString"></CrontabResult>

        <!-- 操作按钮 -->
        <div class="pop_btn">
            <el-button type="primary" @click="submitFill">确定</el-button>
            <el-button type="warning" @click="clearCron">重置</el-button>
            <el-button @click="hidePopup">取消</el-button>
        </div>
    </div>
</template>

<script setup>
import { ref, computed, watch, getCurrentInstance, onMounted } from 'vue'
import CrontabResult from './result.vue'

const { proxy } = getCurrentInstance()
const emit = defineEmits(['hide', 'fill'])
const props = defineProps({
    hideComponent: {
        type: Array,
        default: () => [],
    },
    expression: {
        type: String,
        default: '',
    },
})

// 周期选项
const periodOptions = [
    { label: '每年', value: 'year' },
    { label: '每月', value: 'month' },
    { label: '每周', value: 'week' },
    { label: '每天', value: 'day' },
    { label: '每小时', value: 'hour' },
    { label: '每分钟', value: 'minute' },
]

// 星期选项
const weekOptions = [
    { label: '日', value: 1 },
    { label: '一', value: 2 },
    { label: '二', value: 3 },
    { label: '三', value: 4 },
    { label: '四', value: 5 },
    { label: '五', value: 6 },
    { label: '六', value: 7 },
]

// 选中的周期
const selectedPeriod = ref('minute')
// 选中的星期（用于每周）
const selectedWeek = ref(1)

// 时间值
const timeValues = ref({
    minute: 0,
    hour: 0,
    day: 1,
    month: 1,
})

// Cron表达式对象（5位标准格式：分钟 小时 日 月 星期）
const crontabValueObj = ref({
    min: '*',
    hour: '*',
    day: '*',
    month: '*',
    week: '?',
})

// 执行描述
const executionDesc = computed(() => {
    const periodMap = {
        minute: '每分钟执行',
        hour: '每小时执行',
        day: '每天执行',
        week: '每周执行',
        month: '每月执行',
        year: '每年执行',
    }
    return periodMap[selectedPeriod.value] || '每分钟执行'
})

// 显示控制
const showTimeInputs = computed(() => {
    return selectedPeriod.value !== 'minute'
})

const showMinute = computed(() => {
    return ['hour', 'day', 'week', 'month', 'year'].includes(selectedPeriod.value)
})

const showHour = computed(() => {
    return ['day', 'week', 'month', 'year'].includes(selectedPeriod.value)
})

const showDay = computed(() => {
    return ['month', 'year'].includes(selectedPeriod.value)
})

const showMonth = computed(() => {
    return selectedPeriod.value === 'year'
})

const showWeek = computed(() => {
    return selectedPeriod.value === 'week'
})

// Cron表达式字符串（6位格式：秒 分钟 小时 日 月 星期，秒固定为0）
const crontabValueString = computed(() => {
    const obj = crontabValueObj.value
    return '0 ' + obj.min + ' ' + obj.hour + ' ' + obj.day + ' ' + obj.month + ' ' + obj.week
})

// 监听时间值变化，更新Cron表达式
watch(
    [selectedPeriod, selectedWeek, timeValues],
    () => {
        updateCronExpression()
    },
    { deep: true },
)

// 更新Cron表达式（生成6位格式：秒固定为0，分钟 小时 日 月 星期）
function updateCronExpression() {
    switch (selectedPeriod.value) {
        case 'minute':
            // 每分钟：* * * * ?
            crontabValueObj.value = {
                min: '*',
                hour: '*',
                day: '*',
                month: '*',
                week: '?',
            }
            break
        case 'hour':
            // 每小时：指定分钟 * * * ?
            crontabValueObj.value = {
                min: String(timeValues.value.minute),
                hour: '*',
                day: '*',
                month: '*',
                week: '?',
            }
            break
        case 'day':
            // 每天：指定分钟 指定小时 * * ?
            crontabValueObj.value = {
                min: String(timeValues.value.minute),
                hour: String(timeValues.value.hour),
                day: '*',
                month: '*',
                week: '?',
            }
            break
        case 'week':
            // 每周：指定分钟 指定小时 ? * 指定星期
            crontabValueObj.value = {
                min: String(timeValues.value.minute),
                hour: String(timeValues.value.hour),
                day: '?',
                month: '*',
                week: String(selectedWeek.value),
            }
            break
        case 'month':
            // 每月：指定分钟 指定小时 指定日期 * ?
            crontabValueObj.value = {
                min: String(timeValues.value.minute),
                hour: String(timeValues.value.hour),
                day: String(timeValues.value.day),
                month: '*',
                week: '?',
            }
            break
        case 'year':
            // 每年：指定分钟 指定小时 指定日期 指定月份 ?
            crontabValueObj.value = {
                min: String(timeValues.value.minute),
                hour: String(timeValues.value.hour),
                day: String(timeValues.value.day),
                month: String(timeValues.value.month),
                week: '?',
            }
            break
    }
}

// 周期改变
function handlePeriodChange(period) {
    selectedPeriod.value = period
    updateCronExpression()
}

// 星期改变
function handleWeekChange(week) {
    selectedWeek.value = week
    updateCronExpression()
}

// 解析表达式（支持5位和6位格式，生成时统一为6位格式：0 分钟 小时 日 月 星期）
function resolveExp() {
    if (props.expression) {
        const arr = props.expression.split(/\s+/)
        let obj = {}

        // 判断是5位还是6位表达式
        if (arr.length === 5) {
            // 5位格式：分钟 小时 日 月 星期（兼容旧数据）
            obj = {
                min: arr[0],
                hour: arr[1],
                day: arr[2],
                month: arr[3],
                week: arr[4],
            }
        } else if (arr.length >= 6) {
            // 6位或7位格式：秒 分钟 小时 日 月 星期 [年]
            // 秒字段（arr[0]）固定为0，忽略它，使用分钟作为第一位
            obj = {
                min: arr[1],
                hour: arr[2],
                day: arr[3],
                month: arr[4],
                week: arr[5],
            }
        } else {
            clearCron()
            return
        }

        crontabValueObj.value = { ...obj }

        // 根据表达式反推周期选择
        // 判断是否为数字（简单判断）
        const isNumber = (str) => {
            return /^\d+$/.test(str)
        }

        if (
            obj.min === '*' &&
            obj.hour === '*' &&
            obj.day === '*' &&
            obj.month === '*' &&
            obj.week === '?'
        ) {
            selectedPeriod.value = 'minute'
        } else if (
            isNumber(obj.min) &&
            obj.hour === '*' &&
            obj.day === '*' &&
            obj.month === '*' &&
            obj.week === '?'
        ) {
            selectedPeriod.value = 'hour'
            timeValues.value.minute = parseInt(obj.min) || 0
        } else if (
            isNumber(obj.min) &&
            isNumber(obj.hour) &&
            obj.day === '*' &&
            obj.month === '*' &&
            obj.week === '?'
        ) {
            selectedPeriod.value = 'day'
            timeValues.value.minute = parseInt(obj.min) || 0
            timeValues.value.hour = parseInt(obj.hour) || 0
        } else if (
            isNumber(obj.min) &&
            isNumber(obj.hour) &&
            obj.day === '?' &&
            obj.month === '*' &&
            isNumber(obj.week)
        ) {
            selectedPeriod.value = 'week'
            timeValues.value.minute = parseInt(obj.min) || 0
            timeValues.value.hour = parseInt(obj.hour) || 0
            selectedWeek.value = parseInt(obj.week) || 1
        } else if (
            isNumber(obj.min) &&
            isNumber(obj.hour) &&
            isNumber(obj.day) &&
            obj.month === '*' &&
            obj.week === '?'
        ) {
            selectedPeriod.value = 'month'
            timeValues.value.minute = parseInt(obj.min) || 0
            timeValues.value.hour = parseInt(obj.hour) || 0
            timeValues.value.day = parseInt(obj.day) || 1
        } else if (
            isNumber(obj.min) &&
            isNumber(obj.hour) &&
            isNumber(obj.day) &&
            isNumber(obj.month) &&
            obj.week === '?'
        ) {
            selectedPeriod.value = 'year'
            timeValues.value.minute = parseInt(obj.min) || 0
            timeValues.value.hour = parseInt(obj.hour) || 0
            timeValues.value.day = parseInt(obj.day) || 1
            timeValues.value.month = parseInt(obj.month) || 1
        } else {
            // 如果无法匹配，默认使用每分钟
            selectedPeriod.value = 'minute'
        }
    } else {
        clearCron()
    }
}

// 隐藏弹窗
function hidePopup() {
    emit('hide')
}

// 填充表达式
function submitFill() {
    emit('fill', crontabValueString.value)
    hidePopup()
}

// 重置
function clearCron() {
    selectedPeriod.value = 'minute'
    selectedWeek.value = 1
    timeValues.value = {
        minute: 0,
        hour: 0,
        day: 1,
        month: 1,
    }
    updateCronExpression()
}

// 监听表达式变化
watch(
    () => props.expression,
    () => {
        resolveExp()
    },
    { immediate: true },
)

onMounted(() => {
    if (props.expression) {
        resolveExp()
    } else {
        updateCronExpression()
    }
})
</script>

<style lang="scss" scoped>
.cron-simplified {
    padding: 20px;
    background: #f5f5f5;
    min-height: 400px;
}

.period-section {
    background: #fff;
    padding: 20px;
    border-radius: 4px;
    margin-bottom: 20px;

    .period-title {
        font-size: 14px;
        font-weight: 500;
        color: #333;
        margin-bottom: 15px;
    }

    .period-buttons {
        display: flex;
        gap: 10px;
        flex-wrap: wrap;

        .period-btn {
            min-width: 80px;
            border-radius: 4px;
        }
    }
}

.execution-section {
    background: #fff;
    padding: 20px;
    border-radius: 4px;
    margin-bottom: 20px;
    min-height: 60px;

    .execution-desc {
        font-size: 14px;
        color: #666;
    }
}

.time-input-section {
    background: #fff;
    padding: 20px;
    border-radius: 4px;
    margin-bottom: 20px;

    .time-inputs {
        display: flex;
        gap: 20px;
        flex-wrap: wrap;
        align-items: flex-end;

        .time-input-item {
            display: flex;
            flex-direction: column;
            gap: 8px;

            label {
                font-size: 14px;
                color: #333;
                font-weight: 500;
            }

            .time-input {
                width: 120px;

                :deep(.el-input__inner) {
                    text-align: center;
                }
            }
        }
    }
}

.week-section {
    background: #fff;
    padding: 20px;
    border-radius: 4px;
    margin-bottom: 20px;

    .week-title {
        font-size: 14px;
        font-weight: 500;
        color: #333;
        margin-bottom: 15px;
    }

    .week-buttons {
        display: flex;
        gap: 10px;
        flex-wrap: wrap;

        .week-btn {
            min-width: 50px;
            border-radius: 4px;
        }
    }
}

.cron-result-section {
    background: #fff;
    padding: 20px;
    border-radius: 4px;
    margin-bottom: 20px;

    .result-title {
        font-size: 14px;
        font-weight: 500;
        color: #333;
        margin-bottom: 15px;
    }

    .cron-expression {
        font-size: 14px;
        color: #1677ff;
        font-family: monospace;
        padding: 10px;
        background: #f0f9ff;
        border-radius: 4px;
        word-break: break-all;
        border: 1px solid #d4e8ff;
    }
}

.pop_btn {
    text-align: center;
    margin-top: 20px;
    padding-top: 20px;
    border-top: 1px solid #e8e8e8;
    display: flex;
    justify-content: center;
    gap: 10px;
}
</style>
