<template>
    <div id="changeContab">
        <el-tabs type="border-card">
            <!--      分-->
            <el-tab-pane>
                <template #label>
                    <!-- <span><i icon="el-icon-date" />分</span> -->
                    <div>
                        {{ $t('minute') }}
                    </div>
                </template>
                <div class="tabBody">
                    <el-row>
                        <el-radio
                            v-model="minute.cronEvery"
                            label="1"
                        >
                            {{ $t('everyMinute') }}
                        </el-radio>
                    </el-row>
                    <el-row>
                        <el-radio
                            v-model="minute.cronEvery"
                            label="2"
                        >{{ $t('every') }}
                            <el-input-number
                                v-model="minute.incrementIncrement"
                                :precision="0"
                                :min="1"
                                :max="59"
                            />
                            {{ $t('minuteExecuteFrom') }}
                            <el-input-number
                                v-model="minute.incrementStart"
                                :precision="0"
                                :min="0"
                                :max="59"
                            />
                            {{ $t('minuteStart') }}
                        </el-radio>
                    </el-row>
                    <el-row>
                        <el-radio
                            v-model="minute.cronEvery"
                            class="long"
                            label="3"
                        >{{ $t('specificMinutes') }}
                        </el-radio>
                        <el-select
                            v-model="minute.specificSpecific"
                            :teleported="false"
                            multiple
                        >
                            <el-option
                                v-for="(val, index) in 60"
                                :key="index"
                                :value="val-1"
                            >
                                {{ val - 1 }} <!-- 0-59 -->
                            </el-option>
                        </el-select>
                    </el-row>
                    <el-row>
                        <el-radio
                            v-model="minute.cronEvery"
                            label="4"
                        >{{ $t('periodFrom') }}
                            <el-input-number
                                v-model="minute.rangeStart"
                                :precision="0"
                                :min="1"
                                :max="59"
                            />
                            {{ $t('to') }}
                            <el-input-number
                                v-model="minute.rangeEnd"
                                :precision="0"
                                :min="0"
                                :max="59"
                            />
                            {{ $t('minute') }}
                        </el-radio>
                    </el-row>
                </div>
            </el-tab-pane>
            <!--      时-->
            <el-tab-pane>
                <template #label>
                    <!-- <span><i icon="el-icon-date" />分</span> -->
                    <div>
                        {{ $t('hour') }}
                    </div>
                </template>
                <div class="tabBody">
                    <el-row>
                        <el-radio
                            v-model="hour.cronEvery"
                            label="1"
                        >
                            {{ $t('everyHour') }}
                        </el-radio>
                    </el-row>
                    <el-row>
                        <el-radio
                            v-model="hour.cronEvery"
                            label="2"
                        >{{ $t('every') }}
                            <el-input-number
                                v-model="hour.incrementIncrement"
                                :precision="0"
                                :min="0"
                                :max="23"
                            />
                            {{ $t('hourExecuteFrom') }}
                            <el-input-number
                                v-model="hour.incrementStart"
                                :precision="0"
                                :min="0"
                                :max="23"
                            />
                            {{ $t('hourStart') }}
                        </el-radio>
                    </el-row>
                    <el-row>
                        <el-radio
                            v-model="hour.cronEvery"
                            class="long"
                            label="3"
                        >{{ $t('specificHours') }}
                        </el-radio>
                        <el-select
                            v-model="hour.specificSpecific"
                            :teleported="false"
                            multiple
                        >
                            <el-option
                                v-for="(val, index) in 24"
                                :key="index"
                                :value="val-1"
                            >
                                {{ val - 1 }}
                            </el-option>
                        </el-select>
                    </el-row>
                    <el-row>
                        <el-radio
                            v-model="hour.cronEvery"
                            label="4"
                        >{{ $t('periodFrom') }}
                            <el-input-number
                                v-model="hour.rangeStart"
                                :precision="0"
                                :min="0"
                                :max="23"
                            />
                            {{ $t('to') }}
                            <el-input-number
                                v-model="hour.rangeEnd"
                                :precision="0"
                                :min="0"
                                :max="23"
                            />
                            {{ $t('hour') }}
                        </el-radio>
                    </el-row>
                </div>
            </el-tab-pane>
            <!--      天 周-->
            <el-tab-pane>
                <template #label>
                    <!-- <span><i icon="el-icon-date" />分</span> -->
                    <div>
                        {{ $t('day') }}
                    </div>
                </template>
                <div class="tabBody">
                    <el-row>
                        <el-radio
                            v-model="day.cronEvery"
                            label="1"
                        >
                            {{ $t('everyDay') }}
                        </el-radio>
                    </el-row>
                    <!-- <el-row>
                        <el-radio
                            v-model="day.cronEvery"
                            label="2"
                        >每隔
                            <el-input-number
                                v-model="week.incrementIncrement"
                                :precision="0"
                                :min="1"
                                :max="7"
                            />
                            周执行 从
                            <el-select
                                v-model="week.incrementStart"
                                :teleported="false"
                            >
                                <el-option
                                    v-for="(val, index) in 7"
                                    :key="index"
                                    :label="weekList[val-1]"
                                    :value="val"
                                />
                            </el-select>
                            开始
                        </el-radio>
                    </el-row> -->
                    <el-row>
                        <el-radio
                            v-model="day.cronEvery"
                            label="3"
                        >{{ $t('every') }}
                            <el-input-number
                                v-model="day.incrementIncrement"
                                :precision="0"
                                :min="1"
                                :max="31"
                            />
                            {{ $t('dayExecuteFrom') }}
                            <el-input-number
                                v-model="day.incrementStart"
                                :precision="0"
                                :min="1"
                                :max="31"
                            />
                            {{ $t('dayStart') }}
                        </el-radio>
                    </el-row>
                    <el-row>
                        <el-radio
                            v-model="day.cronEvery"
                            class="long"
                            label="4"
                        >{{ $t('specificWeekdays') }}
                        </el-radio>
                        <el-select
                            v-model="week.specificSpecific"
                            :teleported="false"
                            multiple
                        >
                            <el-option
                                v-for="(val, index) in 7"
                                :key="index"
                                :label="weekList[val-1]"
                                :value="val"
                            />
                        </el-select>
                    </el-row>
                    <el-row>
                        <el-radio
                            v-model="day.cronEvery"
                            class="long"
                            label="5"
                        >{{ $t('specificDays') }}
                        </el-radio>
                        <el-select
                            v-model="day.specificSpecific"
                            :teleported="false"
                            multiple
                        >
                            <el-option
                                v-for="(val, index) in 31"
                                :key="index"
                                :value="val"
                            >
                                {{ val }}
                            </el-option>
                        </el-select>
                    </el-row>
                    <el-row>
                        <el-radio
                            v-model="day.cronEvery"
                            label="6"
                        >
                            {{ $t('lastDayOfMonth') }}
                        </el-radio>
                    </el-row>
                    <el-row>
                        <el-radio
                            v-model="day.cronEvery"
                            label="7"
                        >
                            {{ $t('lastWorkdayOfMonth') }}
                        </el-radio>
                    </el-row>
                    <el-row>
                        <el-radio
                            v-model="day.cronEvery"
                            label="8"
                        >{{ $t('lastWeekdayOfMonth') }}
                            <el-select
                                v-model="week.cronLastSpecificDomDay"
                                :teleported="false"
                            >
                                <el-option
                                    v-for="(val, index) in 7"
                                    :key="index"
                                    :label="weekList[val-1]"
                                    :value="val"
                                />
                            </el-select>
                            <!-- {{ $t('Day.lastWeek')[1] || '' }} -->
                        </el-radio>
                    </el-row>
                    <el-row>
                        <el-radio
                            v-model="day.cronEvery"
                            label="9"
                        >
                            <el-input-number
                                v-model="day.cronDaysBeforeEomMinus"
                                :precision="0"
                                :min="1"
                                :max="31"
                            />
                            {{ $t('daysBeforeMonthEnd') }}
                        </el-radio>
                    </el-row>
                    <el-row>
                        <el-radio
                            v-model="day.cronEvery"
                            label="10"
                        >{{ $t('nearestWorkdayToDay') }}
                            <el-input-number
                                v-model="day.cronDaysNearestWeekday"
                                :precision="0"
                                :min="1"
                                :max="31"
                            />
                            {{ $t('day') }}
                        </el-radio>
                    </el-row>
                    <el-row>
                        <el-radio
                            v-model="day.cronEvery"
                            label="11"
                        >{{ $t('nthWeekdayOfMonth') }}
                            <el-input-number
                                v-model="week.cronNthDayNth"
                                :precision="0"
                                :min="1"
                                :max="5"
                            />
                            {{ $t('th') }}
                            <el-select
                                v-model="week.cronNthDayDay"
                                :teleported="false"
                            >
                                <el-option
                                    v-for="(val, index) in 7"
                                    :key="index"
                                    :label="weekList[val-1]"
                                    :value="val"
                                />
                            </el-select>
                        </el-radio>
                    </el-row>
                </div>
            </el-tab-pane>
            <!--      月-->
            <el-tab-pane>
                <template #label>
                    <!-- <span><i icon="el-icon-date" />分</span> -->
                    <div>
                        {{ $t('month') }}
                    </div>
                </template>
                <div class="tabBody">
                    <el-row>
                        <el-radio
                            v-model="month.cronEvery"
                            label="1"
                        >
                            {{ $t('everyMonth') }}
                        </el-radio>
                    </el-row>
                    <el-row>
                        <el-radio
                            v-model="month.cronEvery"
                            label="2"
                        >{{ $t('every') }}
                            <el-input-number
                                v-model="month.incrementIncrement"
                                :precision="0"
                                :min="1"
                                :max="12"
                            />
                            {{ $t('monthExecuteFrom') }}
                            <el-input-number
                                v-model="month.incrementStart"
                                :precision="0"
                                :min="1"
                                :max="12"
                            />
                        </el-radio>
                    </el-row>
                    <el-row>
                        <el-radio
                            v-model="month.cronEvery"
                            class="long"
                            label="3"
                        >{{ $t('specificMonths') }}
                        </el-radio>
                        <el-select
                            v-model="month.specificSpecific"
                            :teleported="false"
                            multiple
                        >
                            <el-option
                                v-for="(val, index) in 12"
                                :key="index"
                                :label="val"
                                :value="index"
                            />
                        </el-select>
                    </el-row>
                    <el-row>
                        <el-radio
                            v-model="month.cronEvery"
                            label="4"
                        >{{ $t('from') }}
                            <el-input-number
                                v-model="month.rangeStart"
                                :precision="0"
                                :min="1"
                                :max="12"
                            />
                            {{ $t('to') }}
                            <el-input-number
                                v-model="month.rangeEnd"
                                :precision="0"
                                :min="1"
                                :max="12"
                            />
                        </el-radio>
                    </el-row>
                </div>
            </el-tab-pane>
        </el-tabs>
        <div class="bottom">
            <div class="value">
                {{ cron }}
            </div>
            <el-button
                type="primary"
                @click="change"
            >
                {{ $t('save') }}
            </el-button>
            <el-button
                type="primary"
                @click="close"
            >
                {{ $t('close') }}
            </el-button>
            <!--      <el-button type="primary" @click="rest($data)">{{$t('Reset')}}</el-button>-->
        </div>
    </div>
</template>
<script lang="ts">
import { defineComponent, reactive, computed, watch, getCurrentInstance } from 'vue'
import { ObjectInterface } from '../../script/util'
import cronstrue from 'cronstrue/i18n'
/**
 * 后台使用quarz解析cron表达式
 * 0-11代表1-12月 JAN，FEB，MAR，APR，MAY，JUN，JUL，AUG，SEP，OCT，NOV，DEC
 * 1-7代表从周日到周六 SUN，MON，TUE，WED，THU，FRI，SAT
 */

export default defineComponent({
    name: 'InfoCron',
    /* eslint-disable */
    props: {
        data: {
            type: Object,
            default: () => {}
        },
        modelData: {
            type: Object,
            default: () => {}
        }
    },
    emits: ['change', 'close'],
    setup (props, ctx) {
        const { ctx: that } = getCurrentInstance() as any
        let { data, modelData } = props
        const weekList = reactive(['日', '一', '二', '三', '四', '五', '六'].map(function (e) {
            const weekdayMap: { [key: string]: string } = {
                '日': 'weekdaySunday',
                '一': 'weekdayMonday',
                '二': 'weekdayTuesday',
                '三': 'weekdayWednesday',
                '四': 'weekdayThursday',
                '五': 'weekdayFriday',
                '六': 'weekdaySaturday'
            }
            return (window as any).$t(weekdayMap[e])
        }))
        const second = reactive({
            cronEvery: '',
            incrementStart: 3,
            incrementIncrement: 5,
            rangeStart: 0,
            rangeEnd: 0,
            specificSpecific: [0]
        })
        const minute = reactive({
            cronEvery: '2', // 默认选中第几个单选按钮
            incrementStart: 1, // 第二个选项的第二个值
            incrementIncrement: 5, // 第二个选项的第一个值
            rangeStart: 1, // 第四个选项的第一个值
            rangeEnd: 59, // 第四个选项的第二个值
            specificSpecific: [0]// 第三个选项具体时间点的默认值
        })
        const hour = reactive({
            cronEvery: '1',
            incrementStart: 1,
            incrementIncrement: 5,
            rangeStart: 0,
            rangeEnd: 23,
            specificSpecific: [1]
        })
        const day = reactive({
            cronEvery: '1',
            incrementStart: 1,
            incrementIncrement: 1,
            rangeStart: 0,
            rangeEnd: 0,
            specificSpecific: [1],
            // cronLastSpecificDomDay: 1,
            cronDaysBeforeEomMinus: 1,
            cronDaysNearestWeekday: 1
        })
        const week = reactive({
            cronEvery: '',
            incrementStart: 1,
            incrementIncrement: 1,
            specificSpecific: [],
            cronLastSpecificDomDay: 1,
            cronNthDayDay: 1,
            cronNthDayNth: 1
        })
        const month = reactive({
            cronEvery: '1',
            incrementStart: 1,
            incrementIncrement: 5,
            rangeStart: 1,
            rangeEnd: 12,
            specificSpecific: []
        })
        const year = reactive({
            cronEvery: '',
            incrementStart: 2020,
            incrementIncrement: 1,
            rangeStart: 0,
            rangeEnd: 0,
            specificSpecific: [] 
        })
        const output = reactive({
            second: '',
            minute: '',
            hour: '',
            day: '',
            month: '',
            Week: '',
            year: '' 
        })
        const minutesText = computed(() => {
            let minutes = ''
            let cronEvery = minute.cronEvery
            switch (cronEvery.toString()) {
                case '1':
                    minutes = '*'
                    break
                case '2':
                    minutes = `${minute.incrementStart}/${minute.incrementIncrement}`
                    break
                case '3':
                    minute.specificSpecific.map(val => {
                        minutes += val + ','
                    })
                    minutes = minutes.slice(0, -1)
                    break
                case '4':
                    minutes = `${minute.rangeStart}-${minute.rangeEnd}`
                    break
            }
            return minutes
        })
        const hoursText = computed(() => {
            let hours = ''
            let cronEvery = hour.cronEvery
            switch (cronEvery.toString()) {
                case '1':
                    hours = '*'
                    break
                case '2':
                    hours = `${hour.incrementStart}/${hour.incrementIncrement}`
                    break
                case '3':
                    hour.specificSpecific.map(val => {
                        hours += val + ','
                    })
                    hours = hours.slice(0, -1)
                    break
                case '4':
                    hours = `${hour.rangeStart}-${hour.rangeEnd}`
                    break
            }
            return hours
        })
        const daysText = computed(() => {
            let days = ''
            let cronEvery = day.cronEvery
            switch (cronEvery.toString()) {
                case '1':
                    break
                case '2':
                case '4':
                case '8':
                case '11':
                    days = '?'
                    break
                case '3':
                    days = `${day.incrementStart}/${day.incrementIncrement}`
                    break
                case '5':
                    day.specificSpecific.map(val => {
                        days += val + ','
                    })
                    days = days.slice(0, -1)
                    break
                case '6':
                    days = 'L'
                    break
                case '7':
                    days = 'LW'
                    break
                // case '8':
                //     days = `${day.cronLastSpecificDomDay}L`
                //     break
                case '9':
                    days = `L-${day.cronDaysBeforeEomMinus}`
                    break
                case '10':
                    days = `${day.cronDaysNearestWeekday}W`
                    break
            }
            return days 
        })
        const weeksText = computed(() => {
            let weeks = ''
            let cronEvery = day.cronEvery
            switch (cronEvery.toString()) {
                case '1':
                case '3':
                case '5':
                    weeks = '?'
                    break
                case '2':
                    weeks = `${week.incrementStart}/${week.incrementIncrement}`
                    break
                case '4':
                    week.specificSpecific.map(val => {
                        weeks += val + ','
                    })
                    weeks = weeks.slice(0, -1)
                    break
                case '6':
                case '7':
                // case '8':
                case '9':
                case '10':
                    weeks = '?'
                    break
                case '8':
                    weeks = `${week.cronLastSpecificDomDay}L`
                    break
                case '11':
                    weeks = `${week.cronNthDayDay}#${week.cronNthDayNth}`
                    break
            }
            return weeks
        })
        const monthsText = computed(() => {
            let months = ''
            let cronEvery = month.cronEvery
            switch (cronEvery.toString()) {
                case '1':
                    months = '*'
                    break
                case '2':
                    months = `${month.incrementStart - 1}/${month.incrementIncrement}` // incrementStart 0到11
                    break
                case '3':
                    month.specificSpecific.map(val => {
                        months += val + ','
                    })
                    months = months.slice(0, -1)
                    break
                case '4':
                    months = `${month.rangeStart - 1}-${month.rangeEnd - 1}`
                    break
            }
            return months
        })
        const cron = computed(() => {
            return  `0 ${minutesText.value || '*'} ${hoursText.value || '*'} ${daysText.value || '*'} ${monthsText.value || '*'} ${weeksText.value || '?'} *`
        })
        const cronString = computed(() => {
            // return cronstrue.toString(cron.value as unknown as string, { locale: 'zh_CN' })
        })
        // 解析 cron 表达式的函数
        const parseCron = (cron: string) => {
            const parts = cron.split(' ')
            const minutePart = parts[1]
            const hourPart = parts[2]
            const dayPart = parts[3]
            const monthPart = parts[4]
            const weekPart = parts[5]
            // 解析分钟部分
            if (minutePart === '*') {
                minute.cronEvery = '1'
            } else if (minutePart.includes('/')) {
                const [start, increment] = minutePart.split('/')
                minute.cronEvery = '2'
                minute.incrementStart = parseInt(start)
                minute.incrementIncrement = parseInt(increment)
            } else if (minutePart.includes(',')) {
                minute.cronEvery = '3'
                minute.specificSpecific = minutePart.split(',').map(Number)
            } else if (minutePart.includes('-')) {
                const [start, end] = minutePart.split('-')
                minute.cronEvery = '4'
                minute.rangeStart = parseInt(start)
                minute.rangeEnd = parseInt(end)
            }

            // 解析小时部分
            if (hourPart === '*') {
                hour.cronEvery = '1'
            } else if (hourPart.includes('/')) {
                const [start, increment] = hourPart.split('/')
                hour.cronEvery = '2'
                hour.incrementStart = parseInt(start)
                hour.incrementIncrement = parseInt(increment)
            } else if (hourPart.includes(',')) {
                hour.cronEvery = '3'
                hour.specificSpecific = hourPart.split(',').map(Number)
            } else if (hourPart.includes('-')) {
                const [start, end] = hourPart.split('-')
                hour.cronEvery = '4'
                hour.rangeStart = parseInt(start)
                hour.rangeEnd = parseInt(end)
            }

            // 解析天部分
            if (dayPart === '?') {
                // 处理周相关情况
            } else if (dayPart === 'L') {
                day.cronEvery = '6'
            } else if (dayPart === 'LW') {
                day.cronEvery = '7'
            // } else if (dayPart.includes('L')) {
            //     day.cronEvery = '8'
            //     day.cronLastSpecificDomDay = Number(dayPart.replace('L', ''))
            } else if (dayPart.includes('W')) {
                day.cronEvery = '10'
                day.cronDaysNearestWeekday = Number(dayPart.replace('W', ''))
            } else if (dayPart.includes('/')) {
                const [start, increment] = dayPart.split('/').map(Number)
                day.cronEvery = '3'
                day.incrementStart = start
                day.incrementIncrement = increment
            } else if (dayPart.includes(',')) {
                day.cronEvery = '5'
                day.specificSpecific = dayPart.split(',').map(Number)
            } else if (dayPart.includes('-')) {
                const num = Number(dayPart.replace('L-', ''));
                if (!isNaN(num)) {
                    day.cronEvery = '9';
                    day.cronDaysBeforeEomMinus = num;
                }
            }

            // 解析月部分
            if (monthPart === '*') {
                month.cronEvery = '1'
            } else if (monthPart.includes('/')) {
                const [start, increment] = monthPart.split('/')
                month.cronEvery = '2'
                month.incrementStart = parseInt(start) + 1 // 回显1到12
                month.incrementIncrement = parseInt(increment)
            } else if (monthPart.includes(',')) {
                month.cronEvery = '3'
                // @ts-ignore
                month.specificSpecific = monthPart.split(',').map(Number)
            } else if (monthPart.includes('-')) {
                const [start, end] = monthPart.split('-')
                month.cronEvery = '4'
                month.rangeStart = parseInt(start) + 1
                month.rangeEnd = parseInt(end) + 1
            }

            // 解析周部分
            if (weekPart === '?') {
                // 处理天相关情况
            } else if (weekPart.includes('#')) {
                const [day0, nth] = weekPart.split('#').map(Number)
                day.cronEvery = '11'
                week.cronNthDayDay = day0
                week.cronNthDayNth = nth
            } else if (weekPart.includes('/')) {
                const [start, increment] = weekPart.split('/').map(Number)
                day.cronEvery = '2'
                week.incrementStart = start
                week.incrementIncrement = increment
            } else if (weekPart.includes(',')) {
                day.cronEvery = '4'
                // @ts-ignore
                week.specificSpecific = weekPart.split(',').map(Number)
            } else if (weekPart.includes('L')) {
                day.cronEvery = '8'
                week.cronLastSpecificDomDay = Number(weekPart.replace('L', ''))
            }
        }
        const change = () => {
            ctx.emit('change', cron, cronString)
        }
        const close = () => {
            ctx.emit('close')
        }
        const rest = (data: ObjectInterface) => {
            for (let i in data) {
                if (data[i] instanceof Object) {
                    rest(data[i] as ObjectInterface)
                } else {
                    switch (typeof data[i]) {
                        case 'object':
                            data[i] = []
                            break
                        case 'string':
                            data[i] = ''
                            break
                    }
                }
            }
        }
        watch(() => that, () => {
            rest(that)
        })
        return {
            second,
            minute,
            hour,
            day,
            week,
            month,
            year,
            output,
            cron,
            cronString,
            weekList,
            close,
            change,
            parseCron
        }
    }
})
</script>
<style lang="scss" scoped>
#changeContab {
    :deep(.el-tabs__content) {
        overflow: inherit;
    }
    .el-radio--small {
        height: auto;
    }
    .language {
        position: absolute;
        right: 25px;
        z-index: 1;
    }

    .el-tabs {
        box-shadow: none;
    }

    .tabBody {
        .el-row {
            margin: 10px 0;
            .long {
                margin-right: 10px;
            }
        }
    }

    .bottom {
        width: 100%;
        text-align: center;
        margin-top: 5px;
        position: relative;

        .value {
            margin-bottom: 10px;
            padding: 5px;
            border: 1px solid #DCDFE6;
            font-size: 18px;
            vertical-align: middle;
        }
    }
}
</style>
