<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="550">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="100px"
    >
      <el-form-item label="提醒事项" prop="name">
        <el-input v-model="formData.name" placeholder="请输入提醒事项" />
      </el-form-item>
      <el-form-item label="邮件模板" prop="templateCode">
        <el-select v-model="formData.templateCode">
          <el-option
            v-for="item in templatesList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="提醒时长" prop="reminderTime">
        <div class="time-picker">
          <div
            class="time-unit"
            v-for="(unit, index) in timeUnits"
            :key="index"
          >
            <select
              v-model="timeValues.reminderTime[unit.name]"
              :id="unit.name"
            >
              <option
                v-for="option in unit.options"
                :key="option"
                :value="option"
              >
                {{ option }}
              </option>
            </select>
            <label :for="unit.name">{{ unit.label }}</label>
          </div>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script lang="ts" setup>
import { CommonStatusEnum } from '@/utils/constants'
import * as EmailNotifyApi from '@/api/email/notify/index'
import * as MailTemplateApi from "@/api/system/mail/template";

defineOptions({ name: 'EmailNotifyForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  configId: undefined,
  name: '',
  templateCode: undefined,
  reminderTime: 0,
  status: CommonStatusEnum.ENABLE
})

const formRules = reactive({
  name: [{ required: true, message: '提醒事项不能为空', trigger: 'blur' }],
  templateCode: [{ required: true, message: '邮件模板不能为空', trigger: 'change' }]
})

const formRef = ref() // 表单 Ref

// 时间单位配置
const timeUnits = [
  {
    name: 'days',
    label: '天',
    options: Array.from({ length: 31 }, (_, i) => i)
  },
  {
    name: 'hours',
    label: '小时',
    options: Array.from({ length: 24 }, (_, i) => i)
  },
  {
    name: 'minutes',
    label: '分钟',
    options: Array.from({ length: 60 }, (_, i) => i)
  },
  {
    name: 'seconds',
    label: '秒',
    options: Array.from({ length: 60 }, (_, i) => i)
  }
]

// 时间值
const timeValues = reactive({
  reminderTime: {
    days: 0,
    hours: 0,
    minutes: 0,
    seconds: 0
  }
})

// 邮件模板列表
const templatesList = ref([])

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 获取邮件模板列表
  const data = {
    pageNo: 1,
    pageSize: -1
  }
  const res = await MailTemplateApi.getMailTemplatePage(data)
  templatesList.value = res.list.map((item) => {
    return {
      label: item.name,
      value: item.code,
    }
  })
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const data = await EmailNotifyApi.getIsMailNotifyConfigById(id)
      formData.value = data
      // 转换时间
      const convertTime = (time: number) => ({
        days: Math.floor(time / (24 * 60 * 60)),
        hours: Math.floor((time % (24 * 60 * 60)) / (60 * 60)),
        minutes: Math.floor((time % (60 * 60)) / 60),
        seconds: time % 60
      })
      timeValues.reminderTime = convertTime(data.reminderTime)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = { ...formData.value }
    // 计算总秒数
    const calculateTotalSeconds = ({ days, hours, minutes, seconds }) =>
      ((days * 24 + hours) * 60 + minutes) * 60 + seconds
    data.reminderTime = calculateTotalSeconds(timeValues.reminderTime)

    if (formType.value === 'create') {
      await EmailNotifyApi.addIsMailNotifyConfig(data)
      message.success(t('common.createSuccess'))
    } else {
      await EmailNotifyApi.updateIsMailNotifyConfig(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    configId: undefined,
    name: '',
    templateCode: undefined,
    reminderTime: 0,
    status: CommonStatusEnum.ENABLE
  }
  // 重置时间值
  timeValues.reminderTime = {
    days: 0,
    hours: 0,
    minutes: 0,
    seconds: 0
  }
  formRef.value?.resetFields()
}
</script>

<style lang="scss" scoped>
.time-picker {
  display: flex;
  gap: 15px;
  align-items: center;
  padding: 0 10px;
  border-radius: 8px;
}

.time-unit {
  display: flex;
}

label {
  font-size: 14px;
  color: #333;
  margin-left: 10px;
}

select {
  padding: 8px;
  margin-left: -10px;
  font-size: 14px;
  border: 1px solid #ddd;
  border-radius: 4px;
  transition: border-color 0.3s ease;
}

select:focus {
  border-color: #007bff;
  outline: none;
}
</style>
