<template>
  <div class="sysnotion-config">
    <div class="tophead">
      <div @click="rollback()"
        ><img src="@/views/message/reportmessage/img/rollback.png" />返回</div
      >
      <span v-if="!isDisabled">新建系统通知</span>
      <span v-else>查看系统通知</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" />
        <!-- 按钮区域 -->
        <div class="btns" v-if="!isDisabled">
          <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 } from 'element-plus';
  import { useUserStore } from '@/store/modules/user';
  import {
    addSystemMessage,
    confirmReportConfig,
    updateSystemMessage,
    viewSystemMessage,
  } from '@/api/message/sysnotion-config';
  import { RuleFormView, MessageTypeEnum, ContentTypeEnum, RuleFormAdd } from './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.BANNER,
    title: '',
    bannerUrl: '',
    pushChannel: [],
    expirationTime: '',
    recipientType: 1, // 全员
    userGroupList: [],
    customUserList: [],
    introduction: '',
    contentType: ContentTypeEnum.RICHTEXT,
    content: '',
    contentUrl: '',
    operator: info.value.nickname,
  });

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

  const router = useRouter();
  const rollback = () => {
    router.back();
  };
  const route = useRoute();
  const sysId = route.query.id;
  onMounted(() => {
    if (sysId) {
      isDisabled.value = true;
      viewSystemMessage(Number(sysId)).then((res) => {
        if (!res?.status) {
          isDisabled.value = false;
        }
        ruleForm.id = Number(sysId);
        ruleForm.title = res.title;
        ruleForm.introduction = res.introduction ? res.introduction : '';
        ruleForm.messageType = res.messageType;
        ruleForm.content = res.content ? res.content : ' ';
        ruleForm.pushChannel = res.pushChannel;
        ruleForm.recipientType = res.recipientType;

        if (res.recipientType === 2) {
          // 若选择分组
          ruleForm.userGroupList = res.userGroupList;
        } else if (res.recipientType === 3) {
          // 若选择自定义
          ruleForm.customUserList = res.customUserList;
        }
      });
    }
  });

  // 取消
  const onCancel = () => {
    // 比对数据
    const changes = compareData(ruleForm, originalData);
    console.log('Object.keys(changes): ', Object.keys(changes));

    // ElMessageBox.confirm(
    //   '您对系统通知的额操作尚未保存，请问是否暂存?',
    //   '提示',
    //   {
    //     confirmButtonText: '暂存',
    //     cancelButtonText: '取消',
    //     type: 'warning',
    //   }
    // )
    //   .then(() => {
    //     ElMessage({
    //       type: 'success',
    //       message: '暂存成功',
    //     })
    //   })
    //   .catch(() => {
    //     ElMessage({
    //       type: 'info',
    //       message: '取消暂存',
    //     })
    //   })
  };

  // 暂存
  const onSave = async () => {
    // to save dada
    const baseInfoData = await basicInfoRef.value?.validate();
    const contentConfigData = contentConfigRef.value?.buildFormdata();
    console.log('baseInfoData', baseInfoData);
    console.log('contentConfigData', contentConfigData);

    const params: RuleFormAdd = {
      ...baseInfoData!,
      ...contentConfigData,
    };
    delete params.operator;


    if (!sysId) {
      addSystemMessage(params).then((res) => {
        if (res) {
          ruleForm.id = res;
          ElMessage({
            message: '暂存成功!',
            type: 'success',
          });
        }
      });
    } else {
      updateSystemMessage(params).then(() => {
        ElMessage({
            message: '编辑成功!',
            type: 'success',
        });
      });
    }
  };

  const submitForm = () => {
    if (!ruleForm.id) {
      ElMessage({
        message: '暂存后才能下发!',
        type: 'warning',
      });
      return;
    }
    confirmReportConfig(ruleForm.id).then(() => {
      ElMessage({
        message: '下发成功!',
        type: 'success',
      });
      router.back();
    });
  };

  // 比对方法
  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;
  };
</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>
