<template>
  <div class="realtime-notice">
    <el-tooltip effect="light" content="开启后，将推送符合通知条件的违规行为至车主" placement="top">
      <img src="@/assets/icons/help.png" alt="" />
    </el-tooltip>
    <span class="label">实时通知</span>
    <el-switch v-model="switchVal" class="switch" @change="handleRealtimeNoticeChange" />
    <span class="condition" v-if="switchVal">条件：车速≥{{ showSpeed }}km/h</span>
    <el-popover
      v-if="switchVal"
      v-model:visible="formVisible"
      trigger="click"
      width="300"
      placement="bottom-end"
      title="设置通知条件"
      append-to=".realtime-notice"
    >
      <template #reference>
        <img style="margin: 0 10px; cursor: pointer" src="@/assets/icons/edit_2.png" alt="" />
      </template>
      <template #default>
        <div class="config-form-container">
          <el-form ref="ruleFormRef" :model="ruleFormData" label-width="60px">
            <el-form-item
              prop="speedLimit"
              label="车速："
              :rules="[
                {
                  validator: (_rule, value, callback) => {
                    console.log(typeof value);
                    if (value == null) return callback(new Error('请输入车速'));
                    if (!(Number.isInteger(value) && value > 0)) return callback(new Error('车速格式错误'));
                    if (value > 999) {
                      callback(new Error('超过车速时速上限'));
                    } else {
                      callback();
                    }
                  },
                  trigger: 'blur',
                },
              ]"
            >
              <el-input
                v-model.number="ruleFormData.speedLimit"
                placeholder="请输入车速"
                type="number"
                min="0"
                max="999"
                step="1"
              >
                <template #suffix>km/h</template>
              </el-input>
            </el-form-item>
          </el-form>
        </div>
        <div class="config-form-btn">
          <el-button @click="formVisible = false">取消</el-button>
          <el-button type="primary" @click="handleRealtimeNoticeChange(true)">确定</el-button>
        </div>
      </template>
    </el-popover>
  </div>
</template>

<script setup lang="ts">
  import { onMounted, ref, reactive } from 'vue';
  import { updateRealtimeNotice, getRealtimeNoticeConfig } from '@/api/traffic-violation/traffic-act';
  import { ElMessage } from 'element-plus';

  const switchVal = ref(false);
  const showSpeed = ref(45);

  const formVisible = ref(false);
  const ruleFormRef = ref();
  const ruleFormData = reactive<{
    speedLimit: number | null;
  }>({
    speedLimit: null,
  });

  async function getNoticeConfig() {
    try {
      const res = await getRealtimeNoticeConfig();
      switchVal.value = res.realtimeNotice;
      showSpeed.value = res.speedLimit || 45;
      ruleFormData.speedLimit = res.speedLimit || 45;
    } catch (error) {
      ElMessage.error('获取实时通知配置失败');
    }
  }

  async function handleRealtimeNoticeChange(val: boolean) {
    if (formVisible.value) {
      const res = await ruleFormRef.value.validate();
      if (!res) return false;
    }
    try {
      await updateRealtimeNotice({ realtimeNotice: val, speedLimit: val ? ruleFormData.speedLimit! : 45 });
    } catch (error) {
      ElMessage.error('更新实时通知配置失败');
    }
    if (formVisible.value) formVisible.value = false;
    getNoticeConfig();
  }

  onMounted(() => {
    getNoticeConfig();
  });
</script>

<style scoped>
  .realtime-notice {
    position: absolute;
    right: 0px;
    top: 0px;
    display: flex;
    align-items: center;
  }
  .label {
    padding: 0 10px;
    color: rgba(0, 0, 0, 0.85);
    font-size: 14px;
  }
  .condition {
    width: 180px;
    padding-right: 10px;
    text-align: end;
    color: rgba(0, 0, 0, 0.7);
    font-size: 14px;
  }
  .config-form-container {
    margin: 5px 0;
  }
  .config-form-btn {
    text-align: end;
  }

  :deep(.el-popover__title) {
    color: rgba(0, 0, 0, 0.85);
    font-size: 14px;
  }
</style>
