<template>
  <el-dialog
    v-model="visible"
    :title="dialogType === 'add' ? $t('page.form.titleAdd') : $t('page.form.titleEdit')"
    width="800px"
    align-center
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="120px">
      <el-form-item :label="$t('page.form.labelName')" prop="name">
        <el-input v-model="formData.name" :placeholder="$t('page.form.placeholderName')" />
      </el-form-item>
      <el-form-item :label="$t('page.form.labelType')" prop="type">
        <sa-select v-model="formData.type" dict="crontab_task_type" />
      </el-form-item>
      <el-form-item :label="$t('page.form.labelTaskStyle')" prop="task_style">
        <el-space>
          <el-select v-model="formData.task_style" :style="{ width: '100px' }">
            <el-option :value="1" :label="$t('page.form.taskStyleEveryDay')" />
            <el-option :value="2" :label="$t('page.form.taskStyleEveryHour')" />
            <el-option :value="3" :label="$t('page.form.taskStyleNHours')" />
            <el-option :value="4" :label="$t('page.form.taskStyleNMinutes')" />
            <el-option :value="5" :label="$t('page.form.taskStyleNSeconds')" />
            <el-option :value="6" :label="$t('page.form.taskStyleEveryWeek')" />
            <el-option :value="7" :label="$t('page.form.taskStyleEveryMonth')" />
            <el-option :value="8" :label="$t('page.form.taskStyleEveryYear')" />
          </el-select>
          <template v-if="formData.task_style == 8">
            <el-input-number
              v-model="formData.month"
              :precision="0"
              :min="1"
              :max="12"
              controls-position="right"
              :style="{ width: '100px' }"
            />
            <span>{{ $t('page.form.unitMonth') }}</span>
          </template>
          <template v-if="formData.task_style > 6">
            <el-input-number
              v-model="formData.day"
              :precision="0"
              :min="1"
              :max="31"
              controls-position="right"
              :style="{ width: '100px' }"
            />
            <span>{{ $t('page.form.unitDay') }}</span>
          </template>
          <el-select
            v-if="formData.task_style == 6"
            v-model="formData.week"
            :style="{ width: '100px' }"
          >
            <el-option :value="1" :label="$t('page.form.weekMon')" />
            <el-option :value="2" :label="$t('page.form.weekTue')" />
            <el-option :value="3" :label="$t('page.form.weekWed')" />
            <el-option :value="4" :label="$t('page.form.weekThu')" />
            <el-option :value="5" :label="$t('page.form.weekFri')" />
            <el-option :value="6" :label="$t('page.form.weekSat')" />
            <el-option :value="0" :label="$t('page.form.weekSun')" />
          </el-select>
          <template v-if="[1, 3, 6, 7, 8].includes(formData.task_style)">
            <el-input-number
              v-model="formData.hour"
              :precision="0"
              :min="0"
              :max="23"
              controls-position="right"
              :style="{ width: '100px' }"
            />
            <span>{{ $t('page.form.unitHour') }}</span>
          </template>
          <template v-if="formData.task_style != 5">
            <el-input-number
              v-model="formData.minute"
              :precision="0"
              :min="0"
              :max="59"
              controls-position="right"
              :style="{ width: '100px' }"
            />
            <span>{{ $t('page.form.unitMinute') }}</span>
          </template>
          <template v-if="formData.task_style == 5">
            <el-input-number
              v-model="formData.second"
              :precision="0"
              :min="0"
              :max="59"
              controls-position="right"
              :style="{ width: '100px' }"
            />
            <span>{{ $t('page.form.unitSecond') }}</span>
          </template>
        </el-space>
      </el-form-item>
      <el-form-item :label="$t('page.form.labelTarget')" prop="target">
        <el-input
          v-model="formData.target"
          type="textarea"
          :rows="3"
          :placeholder="$t('page.form.placeholderTarget')"
        />
      </el-form-item>
      <el-form-item :label="$t('page.form.labelParams')" prop="params">
        <el-input
          v-model="formData.parameter"
          type="textarea"
          :rows="3"
          :placeholder="$t('page.form.placeholderParams')"
        />
      </el-form-item>
      <el-form-item :label="$t('page.form.labelStatus')" prop="status">
        <sa-radio v-model="formData.status" dict="data_status" />
      </el-form-item>
      <el-form-item :label="$t('page.form.labelRemark')" prop="remark">
        <el-input
          v-model="formData.remark"
          type="textarea"
          :rows="2"
          :placeholder="$t('page.form.placeholderRemark')"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">{{ $t('common.cancel') }}</el-button>
      <el-button type="primary" @click="handleSubmit">{{ $t('table.form.submit') }}</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
  import api from '@/api/tool/crontab'
  import { ElMessage } from 'element-plus'
  import type { FormInstance, FormRules } from 'element-plus'
  import { useI18n } from 'vue-i18n'

  interface Props {
    modelValue: boolean
    dialogType: string
    data?: Record<string, any>
  }

  interface Emits {
    (e: 'update:modelValue', value: boolean): void
    (e: 'success'): void
  }

  const props = withDefaults(defineProps<Props>(), {
    modelValue: false,
    dialogType: 'add',
    data: undefined
  })

  const emit = defineEmits<Emits>()
  const { t } = useI18n()

  const formRef = ref<FormInstance>()

  /**
   * 弹窗显示状态双向绑定
   */
  const visible = computed({
    get: () => props.modelValue,
    set: (value) => emit('update:modelValue', value)
  })

  /**
   * 表单验证规则
   */
  const rules = computed<FormRules>(() => ({
    name: [{ required: true, message: t('page.form.ruleNameRequired'), trigger: 'blur' }],
    type: [{ required: true, message: t('page.form.ruleTypeRequired'), trigger: 'blur' }],
    task_style: [{ required: true, message: t('page.form.ruleTaskStyleRequired'), trigger: 'blur' }],
    target: [{ required: true, message: t('page.form.ruleTargetRequired'), trigger: 'blur' }]
  }))

  /**
   * 初始数据
   */
  const initialFormData = {
    id: null,
    name: '',
    type: '',
    rule: '',
    task_style: 1,
    month: 1,
    day: 1,
    week: 1,
    hour: 1,
    minute: 1,
    second: 1,
    target: '',
    parameter: '',
    status: 1,
    remark: ''
  }

  /**
   * 表单数据
   */
  const formData = reactive({ ...initialFormData })

  /**
   * 监听弹窗打开，初始化表单数据
   */
  watch(
    () => props.modelValue,
    (newVal) => {
      if (newVal) {
        initPage()
      }
    }
  )

  /**
   * 初始化页面数据
   */
  const initPage = async () => {
    // 先重置为初始值
    Object.assign(formData, initialFormData)
    // 如果有数据，则填充数据
    if (props.data) {
      await nextTick()
      initForm()
    }
  }

  // 提取数字
  const extractNumber = (str: string) => {
    const match = str.match(/\d+/)
    return match ? Number.parseInt(match[0]) : 0
  }

  /**
   * 初始化表单数据
   */
  const initForm = () => {
    if (props.data) {
      for (const key in formData) {
        if (props.data[key] != null && props.data[key] != undefined) {
          ;(formData as any)[key] = props.data[key]
        }
      }
      const words = formData['rule'].split(' ')
      formData['second'] = extractNumber(words[0])
      formData['minute'] = extractNumber(words[1])
      formData['hour'] = extractNumber(words[2])
      formData['day'] = extractNumber(words[3])
      formData['month'] = extractNumber(words[4])
      formData['week'] = extractNumber(words[5])
    }
  }

  /**
   * 关闭弹窗并重置表单
   */
  const handleClose = () => {
    visible.value = false
    formRef.value?.resetFields()
  }

  /**
   * 提交表单
   */
  const handleSubmit = async () => {
    if (!formRef.value) return
    try {
      await formRef.value.validate()
      if (props.dialogType === 'add') {
        await api.save(formData)
        ElMessage.success(t('page.form.addSuccess'))
      } else {
        await api.update(formData)
        ElMessage.success(t('page.form.editSuccess'))
      }
      emit('success')
      handleClose()
    } catch (error) {
      console.log('表单验证失败:', error)
    }
  }
</script>
