<template>
  <div class="sysnotion-config">
    <div class="tophead">
      <div @click="rollback()"
        ><img src="@/views/message/reportmessage/img/rollback.png" />返回</div
      >
      <span >{{ disabled ? '新建' : '查看'}}系统通知</span>
    </div>
    <div class="content">
      <div class="left">
        <!-- 基本配置 -->
        <BasicInfo ref="basicInfoRef" :data-soure="ruleForm" :is-disabled="isDisabled" />
        <!-- 内容配置区域 -->
        <ContentConfig ref="contentConfigRef" :data-soure="ruleForm" :is-disabled="isDisabled" :key="initKey"/>
        <!-- 按钮区域 -->
        <div class="btns" v-if="disabled">
          <div style="position: absolute; right: 0; bottom: 0">
            <el-button @click="onCancel">取消</el-button>
            <el-button @click="onSave">暂存</el-button>
            <el-button type="primary" @click="submitForm">确定发布</el-button>
          </div>
        </div>
      </div>
      <!-- 实时预览 -->
      <RightCard :rule-form="ruleForm" />
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { useRoute, useRouter } from 'vue-router';
  import { ref, reactive, onMounted, computed } from 'vue';
  import { storeToRefs } from 'pinia';
  import { ElMessage, ElMessageBox } from 'element-plus';
  import { useUserStore } from '@/store/modules/user';
  import {
    addSystemMessage,
    confirmReportConfig,
    updateSystemMessage,
    viewSystemMessage,
  } from '@/api/message/sysnotion-config';
  import {
    RuleFormView,
    MessageTypeEnum,
    ContentTypeEnum,
    RuleFormAdd,
    SysMessageStatus,
} from './type';
  import { recipientTypeEnum } from '../systemNotifications/type';
  import BasicInfo from './compontents/BasicInfo.vue';
  import ContentConfig from './compontents/ContentConfig.vue';
  import RightCard from './compontents/RightCard.vue';

  const isDisabled = ref<boolean>(false); // 是可编辑还是只查看状态
  
  const useUser = useUserStore();
  const { info } = storeToRefs(useUser);
  const basicInfoRef = ref<InstanceType<typeof BasicInfo>>();
  const contentConfigRef = ref<InstanceType<typeof ContentConfig>>();
  const ruleForm = reactive<RuleFormView>({
    messageType: MessageTypeEnum.TEXT,
    title: '',
    bannerUrl: '',
    pushChannel: [],
    expirationTime: '',
    recipientType: recipientTypeEnum.all, // 默认全员
    userGroupList: [],
    customUserList: [],
    introduction: '',
    contentType: ContentTypeEnum.RICHTEXT,
    content: '',
    contentUrl: '',
    operator: info.value.nickname,
    status: SysMessageStatus.DRAFT,
  });

  // 原始数据副本
  // let originalData: RuleFormView = {
  //   ...ruleForm,
  // };

  const router = useRouter();
  const rollback = () => {
    router.back();
  };
  const route = useRoute();
  const sysId = Number(route.query.id as string);
  const viewModel = route.query.viewModel as string;
  const initKey = ref(0)
  const disabled = computed(() => !isDisabled.value || viewModel === 'edit');
  
  /**
   * 获取当前系统配置信息
   */
  const fetchSystemMessage = async () => {
    // 首次暂存后切换到编辑模式，因为路由没有发生变化，组件也不会发生变化，
    // sysId会一直为undefined，但此时 ruleForm.id 是存在的
    const messageId = sysId || ruleForm.id;

    // 查看 或 编辑状态
    if (messageId) {
      isDisabled.value = true;
      const res = await viewSystemMessage(messageId);
      if (res.status === SysMessageStatus.DRAFT && viewModel === 'edit') {
        // 如果未发布，还是可以编辑的
        isDisabled.value = false;
      } else {
        isDisabled.value = true;
      }
      ruleForm.id = messageId;
      initKey.value += 1;
      Object.entries(res).forEach(([key, value]) => {
        ruleForm[key] = value;
      });
    }
  };

  /**
   * 取消按钮
   */
  const onCancel = () => {
    // TODO：比对数据。 暂时不上
    // const changes = compareData(ruleForm, originalData);

    ElMessageBox.confirm('你填写的数据若未及时保存，离开页面后将会丢失', '提示', {
      confirmButtonText: '确认取消',
      cancelButtonText: '继续留在页面',
      type: 'warning',
    })
      .then(() => {
        router.push('/message/systemNotifications');
      })
      .catch(() => {});
  };

  /**
   * 暂存功能。 未正式发布之前，可继续编辑
   */
  const onSave = async () => {
    try {
      await saveSysData();
    } catch (error) {
      ElMessage.error(error as string);
    }
  };
  const saveSysData = async() => {
    // 基础配置信息。
    const isValidSuccess = await basicInfoRef.value?.validate();
    const baseInfoData = await basicInfoRef.value?.buildFromData();
    if (!isValidSuccess) return;

    // 内容配置信息。
    const contentConfigData = contentConfigRef.value?.buildFormdata();

    const params: RuleFormAdd = {
      ...baseInfoData!,
      ...contentConfigData,
    };
    // 请求体，不需要 operator 和 status
    delete params.operator;
    delete params.status;

    const messageId = sysId || ruleForm.id;

    if (!messageId) {
      // 首次保存
      ruleForm.id = await addSystemMessage(params);
      ElMessage.success('暂存成功!');
      await router.replace(`/message/sys-notification?id=${ruleForm.id}`);
      fetchSystemMessage();
    } else {
      // 继续编辑
      await updateSystemMessage(params);
      ElMessage.success('编辑成功!');
    }
  }

  const submitForm = async() => {
    try {
      await saveSysData();
      if (!ruleForm.id) return;
      confirmReportConfig(ruleForm.id).then(() => {
        ElMessage({
          message: '下发成功!',
          type: 'success',
        });
        router.push('/message/systemNotifications');
      });
    } catch (error) {
      ElMessage.error(error as string);
    }
  };

  // 比对方法
  const compareData = (newData: RuleFormView, oldData: RuleFormView) => {
    const diff: Partial<Omit<RuleFormView, 'content'>> = {};
    for (const key in newData) {
      if (newData[key as keyof RuleFormView] !== oldData[key as keyof RuleFormView]) {
        diff[key as keyof RuleFormView] = newData[key as keyof RuleFormView];
      }
    }
    return diff;
  };

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

<style lang="scss" scoped>
  .sysnotion-config {
    position: relative;
    height: calc(100vh - 64px - 18px);
    background-color: rgba(255, 255, 255, 1);
    box-sizing: border-box !important;
    .tophead {
      display: flex;
      gap: 20px;
      width: 100%;
      height: 50px;
      padding: 16px 0 14px 21px;
      border-bottom: 1px solid rgba(0, 0, 0, 0.06);
      div {
        display: flex;
        align-items: center;
        font-weight: 400;
        font-size: 14px;
        color: #303133;
        line-height: 22px;
        cursor: pointer;
        img {
          margin-right: 4px;
        }
      }
    }
    .content {
      display: flex;
      width: 100%;
      height: calc(100vh - 64px - 18px - 50px);
      padding: 0 30px 0 0;
      .left {
        display: flex;
        flex-direction: column;
        flex: 1;
        position: relative;
        padding: 21px;
        border-right: 1px solid rgba(0, 0, 0, 0.06);
        overflow-y: auto;
        .el-form-outer {
          display: flex;
          flex-direction: column;
          gap: 32px;
        }
        .transprant {
          :deep(.el-form-item__label::before) {
            content: '**';
            opacity: 0;
          }
        }
        .btns {
          margin-top: 35px;
          flex: 1;
          width: 100%;
          position: relative;
        }
      }
    }
  }
</style>
