<!-- 配置下发弹窗 -->
<script lang="ts" setup name="PushConfig">
import axios from 'axios'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getConfig, pushConfig } from '@/api/page/control'
const dialogFormVisible = ref<boolean>(false) // 对话框是否显示
const dataFormRef = ref<FormInstance>()
// 表单对象
const dataForm = ref({
  push_url: '', // 地址
  push_interval: '', // 间隔
  push_type: '', // 类型
})
function validateURL(url: string) {
  try {
    new URL(url)
    return true
  } catch (error) {
    return false
  }
}
const validateIp = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('地址不能为空'))
  }
  else {
    if (validateURL(value)) {
      callback()
    }
    else {
      callback(new Error('地址不合法'))
    }
    callback()
  }
}
const validateNumber = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback()
  }
  else {
    if (Number(value) < 0) {
      callback(new Error('请输入大于等于0的数字'))
    }
    else {
      callback()
    }
    callback()
  }
}
// 校验规则
const rules: FormRules = reactive({
  push_type: [{ required: true, message: '推送类型必选', trigger: ['blur', 'change'] }],
  push_url: [{ required: true, validator: validateIp, trigger: ['blur', 'change'] }],
  push_interval: [{ validator: validateNumber, trigger: ['blur', 'change'] }],
})// 前端校验规则
// 弹窗初始化
const initDialog = () => {
  dialogFormVisible.value = true
  resetForm()
  nextTick(() => {
    dataFormRef.value?.resetFields()
  })
}

defineExpose({ initDialog })

// 重置表单
function resetForm() {
  // console.log(dataForm.value)
  dataForm.value.push_url = ''
  dataForm.value.push_interval = ''
  dataForm.value.push_type = ''
}
// 保存数据
function saveData() {
  dataFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      ElMessageBox.confirm(
        `确认推送配置吗？`,
        '提示',
        { confirmButtonText: '确认', cancelButtonText: '取消', type: 'warning' },
      ).then(() => {
        pushConfig(dataForm.value).then((res) => {
          ElMessage.success('操作成功')
          dialogFormVisible.value = false
        })
      })

    }
  })
}
const pushList = ref<any[]>([])
axios.get(`./config/config.json?ts=${new Date().getTime()}`).then((res) => {
  pushList.value = res.data.push_type
})
// 监听类型 获取之前的配置
watch(() => dataForm.value.push_type, (newVal) => {
  if (newVal) {
    getConfig().then(res => {
      const current = res.data.filter((item: any) => String(item.push_type) === newVal)
      if (current.length) {
        // ElMessageBox.confirm(
        //   `查询到上一次下发配置内容，是否填充到当前？`,
        //   '提示',
        //   { confirmButtonText: '确认', cancelButtonText: '取消', type: 'warning' },
        // ).then(() => {
        dataForm.value.push_url = current[0].push_url
        dataForm.value.push_interval = current[0].push_interval
        // })

      }
    })
  }
}, {
  deep: true,
  immediate: true
})
</script>

<template>
  <el-dialog v-model="dialogFormVisible" title="推送配置" append-to-body width="40%">
    <el-form ref="dataFormRef" :rules="rules" :model="dataForm" label-position="right" label-width="80px">
      <el-form-item label="推送类型" prop="push_type">
        <el-select v-model="dataForm.push_type" placeholder="推送类型" clearable class="select" style="width: 100%;">
          <el-option v-for="item in pushList" :key="item.value" :value="item.value" :label="item.name" />
        </el-select>
      </el-form-item>
      <el-form-item label="推送地址" prop="push_url">
        <el-input :disabled="!dataForm.push_type" v-model.trim="dataForm.push_url" type="text" placeholder="必填"
          style="width: 100%;" />
      </el-form-item>
      <el-form-item label="推送间隔" prop="push_interval">
        <el-input :disabled="!dataForm.push_type" v-model.trim="dataForm.push_interval" type="number" :step="10"
          controls-position="right" style="width: 100%;" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="saveData">
          保存
        </el-button>
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>
.footer {
  display: flex;
  justify-content: flex-end;
}
</style>
