<template>
  <div class="realtime-push">
    <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" :before-change="debouncedhandleSwitchChange" />
    <span class="info-text">推送对象{{ objectNum }}人</span>
    <el-popover :visible="formVisible" width="300" placement="bottom-end" title="推送设置">
      <template #reference>
        <img
          style="margin: 0 10px; cursor: pointer"
          @click="formVisible = !formVisible"
          src="@/assets/icons/edit_2.png"
          alt=""
        />
      </template>
      <template #default>
        <div class="config-form-container">
          <el-form ref="ruleFormRef" :model="ruleFormData" label-width="82px">
            <el-form-item
              prop="userGroupList"
              label="推送对象："
              :rules="[{ validator: formValidator, trigger: 'change' }]"
            >
              <GroupSelect
                v-model="ruleFormData.userGroupList"
                :groupOptions="groupOptions"
                @change="handleUserGroupListChange"
              />
            </el-form-item>
          </el-form>
        </div>
        <div class="config-form-btn">
          <el-button @click="formVisible = false">取消</el-button>
          <el-button type="primary" @click="updateConfig(switchVal)">确定</el-button>
        </div>
      </template>
    </el-popover>
  </div>
</template>

<script setup lang="ts">
  import { onMounted, ref, reactive } from 'vue';
  import { ElMessage } from 'element-plus';
  import { updateBreakPushConfig, queryBreakPushConfig } from '@/api/security-confidentiality-person/outer-person';
  import GroupSelect from '@/components/PersonGroup/components/GroupSelect.vue';
  import { useGroupInfoHook } from '@/components/PersonGroup/hook/groupInfo';
  import { debounce } from 'lodash-es';

  const switchVal = ref(false);
  const objectNum = ref(0);

  const formVisible = ref(false);
  const ruleFormRef = ref();
  const ruleFormData = reactive<{
    userGroupList: number[];
  }>({
    userGroupList: [],
  });

  const { getUserGroupList, groupOptions } = useGroupInfoHook();

  async function getNoticeConfig() {
    try {
      const res = await queryBreakPushConfig();
      switchVal.value = res.alertPush;
      ruleFormData.userGroupList = res.pushGroupIdList!;
      objectNum.value = res.pushObjectCount!;
    } catch (error) {
      ElMessage.error('获取闯入告警推送配置失败');
    }
  }

  async function updateConfig(val: boolean) {
    if (formVisible.value) {
      const res = await ruleFormRef.value.validate();
      if (!res) return false;
    }
    try {
      await updateBreakPushConfig({ alertPush: val, pushGroupIdList: ruleFormData.userGroupList! });
    } catch (error) {
      ElMessage.error('更新闯入告警推送配置失败');
    }
    if (formVisible.value) formVisible.value = false;
    getNoticeConfig();
  }

  function handleSwitchChange() {
    // no async
    if (!switchVal.value) {
      if (objectNum.value > 0) {
        updateConfig(!switchVal.value);
      } else {
        ElMessage.error('请先完成推送对象设置');
      }
    } else {
      updateConfig(!switchVal.value);
    }
    return false;
  }
  const debouncedhandleSwitchChange = debounce(handleSwitchChange, 1000);

  const formValidator = (_rule, value, callback) => {
    if (value == null || !value.length) {
      return callback(new Error('请选择用户组'));
    } else {
      callback();
    }
  };

  const handleUserGroupListChange = (userGroupList: number[]) => {
    ruleFormData.userGroupList = userGroupList;
  };

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

<style scoped>
  .realtime-push {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
  }
  .label {
    padding: 0 10px;
    color: rgba(0, 0, 0, 0.85);
    font-size: 14px;
  }
  .info-text {
    width: 120px;
    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 {
    padding-top: 20px;
    text-align: end;
  }

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