<!--
 * @Descripttion: 跳转到页面展示页面
 * @Version: 1.0
 * @Author: cby
 * @Date: 2025-09-15 19:43:00
 * @LastEditors: cby
 * @LastEditTime: 2025-09-15 19:43:00
-->
<template>
  <div class="cxssb-content">
    <!-- 头部导航栏 - 固定导航 -->
    <Nav style="position: fixed;z-index: 100;width: 100%;" />

    <!-- 主体内容区 -->
    <div class="main-page-content" :style="containerStyle">
      <iframe
        ref="myIframe"
        v-if="!iskxt"
        :src="iFrameSrc"
        :style="{  height: iframeHeight + 'px', }"
        class="iframe-container"
        @lxchange="lxchange"
         @load="initHeightObserver"
      >
      </iframe>
      <iframe ref="myIframe" v-if="iskxt" :src="iFrameSrc" style="height: calc(100vh - 76px)" class="iframe-container">
      </iframe>
      <Footer />
    </div>
    <t-dialog
      :closeOnOverlayClick="false"
      header="联系服务"
      :visible.sync="delVisible"
      @confirm="onDelConfirm"
      @cancel="oncancel"
      :onClose="onDelClose"
      class="global-dialog"
      attach="body"
    >
      <div class="dialog-line">
        <div class="dialog-line-title">联系人：</div>
        <div class="dialog-line-text">{{ lxrow.lxr }}</div>
      </div>
      <div class="dialog-line">
        <div class="dialog-line-title">联系电话：</div>
        <div class="dialog-line-text">{{ lxrow.lxdh }}</div>
      </div>
      <div class="dialog-line">
        <div class="dialog-line-title">电子邮箱：</div>
        <div class="dialog-line-text">{{ lxrow.email }}</div>
      </div>
      <div class="dialog-line">
        <div class="dialog-line-title" style="width:95px">留言内容：</div>
        <t-textarea v-model="xxnr" :autosize="{ minRows: 3 }"></t-textarea>
      </div>
    </t-dialog>
    <!-- 底部信息区 -->
  </div>
</template>

<script>
import Nav from '@/pages/index/components/nav/index.vue';
import Footer from '@/pages/index/components/footer/index.vue';
import api from '@/pages/index/api/gxzx/index.js';
export default {
  components: {
    Nav,
    Footer,
  },
  props: {},
  data() {
    return {
      delVisible: false,
      sfjzIframe: false,
      iFrameSrc: '',
      myFrameHeight: '300',
      mybreadList: ['首页', '111', '222'],
      kxttg: '',
      containerStyle: {
        width: '100%',
        // height: '958px',
        transform: 'scale(1)',
        transformOrigin: '0 0',
      },
      khfwStyle: {},
      iframeHeight: 300,
      resizeObserver: null,
      iskxt: false,
      lxrow: {},
      xxnr:'',
    };
  },
  created() {
    // 通常方式获取iframe的跳转地址
    const menuParams = this.$route.params;
    // open window方式获得ifram跳转地址
    if (this.$route.query.newUrl) {
      // alert(this.$route.query.newUrl);
      menuParams.menuPath = this.$route.query.newUrl;
    }
    if (this.$route.query.parmasStr) {
      // alert(this.$route.query.parmasStr);
      menuParams.parmasStr = this.$route.query.parmasStr;
    }

    this.pageGotoChange(menuParams);
  },
  mounted() {
    // this.onIframeLoad();
    this.gettfwzxurl();
    this.initIframeListener();
    this.updateScreenCompatibility();
    window.addEventListener('resize', () => {
      this.updateScreenCompatibility();
    });
    window.openNewWin = this.openNewWin;
    window.goSelfChange = this.goSelfChange;
    window.addEventListener('message', this.handleIframeMessage);
  },
   beforeDestroy() {
    if (this.resizeObserver) {
      this.resizeObserver.disconnect();
    }
    window.removeEventListener('message', this.handlePostMessage);
  },
  methods: {
    initHeightObserver() {
      const iframe = this.$refs.myIframe;
      
      try {
        const iframeWindow = iframe.contentWindow;
        const iframeDocument = iframe.contentDocument;
        
        // 使用MutationObserver监听DOM变化
        this.resizeObserver = new MutationObserver(() => {
          this.updateIframeHeight();
        });
        
        this.resizeObserver.observe(iframeDocument.body, {
          childList: true,
          subtree: true,
          attributes: true,
          characterData: true
        });
        
        // 监听iframe内部图片加载
        const images = iframeDocument.getElementsByTagName('img');
        Array.from(images).forEach(img => {
          img.addEventListener('load', this.updateIframeHeight);
          img.addEventListener('error', this.updateIframeHeight);
        });
        
        // 初始更新高度
        this.updateIframeHeight();
        
      } catch (error) {
        console.error('无法访问iframe内容:', error);
        // 降级方案：使用postMessage
        this.setupPostMessageFallback();
      }
    },
    
    updateIframeHeight() {
      const iframe = this.$refs.myIframe;
      if (!iframe) return;
      
      try {
        const iframeDocument = iframe.contentDocument;
        const height = Math.max(
          iframeDocument.body.scrollHeight,
          iframeDocument.body.offsetHeight,
          iframeDocument.documentElement.scrollHeight,
          iframeDocument.documentElement.offsetHeight
        );
        
        // 添加缓冲，防止内容被裁剪
        this.iframeHeight = height + 10;
        
      } catch (error) {
        console.warn('更新高度失败:', error);
      }
    },
    
    setupPostMessageFallback() {
      // 如果无法直接访问iframe DOM，使用postMessage方案
      window.addEventListener('message', this.handlePostMessage);
      this.$refs.myIframe.contentWindow.postMessage(
        { type: 'REQUEST_HEIGHT' }, 
        '*'
      );
    },
    handleIframeMessage(event) {
      console.log('event', event);
      this.xxnr = '';
      this.delVisible = true;
      this.lxrow = event.data.row;
    },
    lxchange(row) {
      console.log('lxchange', row);

      this.lxrow = row;
      this.delVisible = true;
    },
    oncancel(){
     this.delVisible = false;
    },
    onDelConfirm() {
      this.onSubmit();
    },
    async onSubmit() {
      try {
        let params = {
          yhuuid: this.lxrow.lrruuid,
          xxnr: this.xxnr,
          xxflDm: 1,
        };
        const { data } = await api.saveGgxx(params);
        // await this.saveGgxx({
        //   params: {
        //     yhuuid:this.lxrow.lrruuid,
        //     xxnr: this.ggFormData.xxnr,
        //     xxflDm: 1,
        //   },
        //   successCb: () => {
        this.$message.success('留言发布成功！');
      } catch (err) {
      } finally {
        this.xxnr = '';
        this.delVisible = false;
      }
      // });
    },
    onDelClose() {
      this.delVisible = false;
    },
    async gettfwzxurl() {
      try {
        // const res = await getMxjbxx(prame);
        const { data } = await api.tfwzxurl();
        let kxtcx = data.kxtcx;
        let kxtcz = data.kxtcz;
        let kxtfwzx = data.kxtfwzx;
        let kxttg = data.kxttg;
        let newUrl = this.$route.query.newUrl;
        if (newUrl == kxtcx || newUrl == kxtcz || newUrl == kxtfwzx || newUrl == kxttg) {
          this.iskxt = true;
        } else {
          this.iskxt = false;
        }
        console.log('res', data);
      } catch (error) {
        console.error('数据加载失败', error);
      }
    },
    initIframeListener() {
      console.log('mounted里调用initIframeListener');
      const iframe = this.$refs.myIframe;

      // 初始获取高度
      this.updateIframeHeight();

      // 监听iframe高度变化
      this.$watch('iframeHeight', (newHeight, oldHeight) => {
        if (newHeight !== oldHeight) {
          this.handleHeightChange(newHeight);
        }
      });

      // 定期检查高度变化
      this.heightCheckInterval = setInterval(() => {
        this.updateIframeHeight();
      }, 100); // 每100ms检查一次
    },
    updateIframeHeight() {
      console.log('updateIframeHeight获取高度方法');
      const iframe = this.$refs.myIframe;
      console.log('iframe.contentDocument', iframe.contentDocument);
      if (iframe && iframe.contentDocument) {
        const iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
        const newHeight = iframeDoc.body.scrollHeight;
        console.log('newHeight', newHeight);
        if (newHeight !== this.iframeHeight) {
          this.iframeHeight = newHeight;
        }
      }
    },

    handleHeightChange(height) {
      console.log('iframe高度发生变化:', height);
      // 在这里执行高度变化后的操作
      this.$emit('iframe-height-change', height);
    },

    updateScreenCompatibility() {
      const targetWidth = 1930;
      const targetHeight = 958; // 1080;
      const viewportWidth = window.innerWidth;
      const viewportHeight = window.innerHeight;

      const scale = Math.min(viewportWidth / targetWidth, viewportHeight / targetHeight);
      this.containerStyle = {
        // width: `${targetWidth}px`,
        // height: `${targetHeight}px`,
        // transform: `scale(${scale})`,
        width: `100%`,
        transformOrigin: '50% 0',
      };

      this.khfwStyle = {
        // width: `${targetWidth}px`,
        width: `100%`,
        // transform: `scale(${scale})`,
        transformOrigin: '50% 0',
        position: 'fixed',
        top: `0`,
      };
    },
    pageGotoChange(menuParams) {
      if (menuParams.menuPath) {
        let url = menuParams.menuPath; // 完整路劲
        if (menuParams.parmasStr) {
          url += `?${menuParams.parmasStr}`; // 追加参数
        }
        const iframe = this.$refs.myIframe;
        const newStr = url.replace('@@@', '&');
        this.iFrameSrc = newStr;
        this.mybreadList = menuParams.menuTitle;
      }
    },
    onIframeLoad() {
      const iframe = this.$refs.myIframe;
      const iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
      const iframeHeight = iframeDoc.body.scrollHeight;
      console.log('iframeHeight', iframeHeight);
      // 设置 iframe 高度为其内容的实际高度m
      iframe.style.height = Math.max(iframeHeight, 500) + 'px'; // 至少500px
    },
    goSelfChange(menuParams) {
      this.$router.replace({
        path: '/mhsy/mhNewMain',
        name: 'mhMainWin',
        query: {
          newUrl: menuParams.menuPath,
          parmasStr: menuParams.menuParmasStr,
        },
      });
      window.location.reload();
    },

    openNewWin(newUrl) {
      if (newUrl) {
        const { href } = this.$router.resolve({
          path: '/mhsy/mhNewMain',
          name: 'mhMainWin',
          params: {
            menuPath: newUrl,
          },
          query: {
            newUrl,
          },
        });
        window.open(href, '_blank');
      }
    },
  },
  beforeDestroy() {
    // 清除定时器
    if (this.heightCheckInterval) {
      clearInterval(this.heightCheckInterval);
    }
  },
};
</script>

<style lang="less" scoped>
.page-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
}

.main-content {
  position: relative;
  min-height: 0; // 允许内容区域收缩
  overflow: auto; // 只在这里启用滚动条
  flex: 1;
}

.iframe-container {
  display: block;
  width: 100%;
  min-height: 720px;
  margin-top: 75px;
  border: none;
}

.footer-section {
  flex-shrink: 0;
  background: #f5f5f5; // 可选：为footer添加背景色以便区分
}

.t-breadcrumb {
  height: 40px;
  padding-left: 30px;
  /deep/.t-breadcrumb__item {
    font-family: PingFangSC;
    color: #4285f4;
  }
  /deep/.myTitle.t-breadcrumb__item {
    font-family: PingFangSC;
    color: #333;
  }
}
// .main-page-content {
//   background-color: #263238;
//   overflow: auto;
// }
.dialog-line {
  display: flex;
  margin-bottom: 16px;
}
.dialog-line-title {
  margin-right: 8px;
}
.main-page-content {
  overflow: auto;
  background-color: #263238;

  /* 隐藏滚动条 */
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE 和 Edge */
}

/* Chrome, Safari 和 Opera */
.main-page-content::-webkit-scrollbar {
  width: 0;
  height: 0;
  background: transparent;
}

.main-page-content::-webkit-scrollbar-thumb {
  background: transparent;
}

.main-page-content::-webkit-scrollbar-track {
  background: transparent;
}
</style>
