<template>
  <view class="preview-page">
    <scroll-view class="preview-scroll" scroll-y>
      <view class="preview-content">
        <view v-if="loading" class="state-text">加载中...</view>
        <view v-else-if="errorMessage" class="state-text" @click="loadDetail">{{ errorMessage }}</view>
        <jyf-parser
          v-else
          :html="agreementHtml"
          :tag-style="tagStyle"
          selectable
          @linkpress="handleLinkPress"
        />
      </view>
    </scroll-view>

    <view class="footer-area">
      <button class="return-button" hover-class="button-hover" @click="handleBack">返回</button>
    </view>
  </view>
</template>

<script>
import parser from '@/components/jyf-parser/jyf-parser.vue';
import { getContractDetail } from '@/api/contract.js';
import { refreshCurrentWebviewToken } from '@/utils/token.js';

export default {
  components: {
    'jyf-parser': parser
  },
  data() {
    return {
      id: '',
      detailHtml: '',
      loading: false,
      errorMessage: '',
      tagStyle: {
        p: 'margin:0 0 7px 0;line-height:1.42;text-align:justify;font-size:15px;color:#111;',
        strong: 'font-weight:700;',
        div: 'font-size:15px;line-height:1.45;color:#111;',
        img: 'max-width:100%;height:auto;display:block;',
        table: 'width:100%;border-collapse:collapse;',
        video: 'max-width:100%;'
      }
    };
  },
  computed: {
    agreementHtml() {
      return this.detailHtml || '<p>暂无协议内容</p>';
    }
  },
  onLoad(options = {}) {
    refreshCurrentWebviewToken(options.token ? '?token=' + encodeURIComponent(options.token) : '');
    this.id = options.id || '';
    uni.setNavigationBarTitle({
      title: '商户协议预览'
    });
    this.loadDetail();
  },
  methods: {
    async loadDetail() {
      if (!this.id) {
        this.errorMessage = '协议ID为空';
        return;
      }

      this.loading = true;
      this.errorMessage = '';
      try {
        const response = await getContractDetail({
          id: this.id
        });
        const detail = this.unwrapPayload(response);
        this.detailHtml = this.normalizeDetailHtml(detail);
        this.setPageTitle(detail);
      } catch (error) {
        this.errorMessage = this.getErrorMessage(error, '协议详情加载失败，点击重试');
      } finally {
        this.loading = false;
      }
    },
    unwrapPayload(response) {
      if (response && typeof response === 'object' && response.data !== undefined) {
        return response.data;
      }
      return response;
    },
    normalizeDetailHtml(detail) {
      const content = this.pickDetailContent(detail);
      if (!content) return '<p>暂无协议内容</p>';

      if (/<[a-z][\s\S]*>/i.test(content)) {
        return content;
      }

      return String(content)
        .split(/\n+/)
        .map(item => item.trim())
        .filter(Boolean)
        .map(item => '<p>' + this.escapeHtml(item) + '</p>')
        .join('');
    },
    pickDetailContent(detail) {
      if (typeof detail === 'string') return detail;
      if (!detail || typeof detail !== 'object') return '';

      const candidates = [
        detail.content,
        detail.contract_content,
        detail.agreement_content,
        detail.html,
        detail.detail,
        detail.body,
        detail.template,
        detail.text,
        detail.data
      ];

      for (let index = 0; index < candidates.length; index += 1) {
        if (typeof candidates[index] === 'string' && candidates[index].trim()) {
          return candidates[index];
        }
      }

      if (detail.data && typeof detail.data === 'object') {
        return this.pickDetailContent(detail.data);
      }

      return '';
    },
    setPageTitle(detail) {
      if (!detail || typeof detail !== 'object') return;
      const title =
        detail.content_name ||
        detail.title ||
        detail.name ||
        detail.contract_name ||
        detail.agreement_name ||
        detail.contract_title;
      if (title) {
        uni.setNavigationBarTitle({
          title: String(title)
        });
      }
    },
    escapeHtml(text) {
      return String(text)
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#39;');
    },
    getErrorMessage(error, defaultMessage) {
      if (error && error.msg) return error.msg;
      if (error && error.message) return error.message;
      if (typeof error === 'string') return error;
      return defaultMessage;
    },
    handleLinkPress(e) {
      if (e && typeof e.ignore === 'function') {
        e.ignore();
      }
    },
    handleBack() {
      const pages = getCurrentPages();
      if (pages.length > 1) {
        uni.navigateBack();
        return;
      }
      uni.redirectTo({
        url: '/pages/agreement/index'
      });
    }
  }
};
</script>

<style scoped>
page {
  background: #ffffff;
}

.preview-page {
  min-height: 100vh;
  padding-bottom: 84px;
  background: #ffffff;
  color: #111111;
}

.preview-scroll {
  height: calc(100vh - 84px);
}

.preview-content {
  padding: 14px 16px 30px;
}

.state-text {
  padding: 28px 0;
  color: #666666;
  font-size: 14px;
  line-height: 1.5;
  text-align: center;
}

.footer-area {
  position: fixed;
  right: 0;
  bottom: 0;
  left: 0;
  display: flex;
  justify-content: center;
  height: 84px;
  padding-top: 16px;
  background: #ffffff;
}

.return-button {
  width: 142px;
  height: 34px;
  padding: 0;
  border: 1px solid #bfbfbf;
  border-radius: 19px;
  background: #ffffff;
  color: #111111;
  font-size: 14px;
  line-height: 32px;
}

.return-button::after {
  border: 0;
}

.button-hover {
  background: #f6f6f6;
}
</style>
