<template>
  <full-page mainClass="bg-white">
    <view class="article-detail-page">
      <view v-if="loading" class="loading-container">
        <uni-icons type="spinner-cycle" size="40" color="#999" />
        <text class="loading-text">加载中...</text>
      </view>

      <view v-else-if="error" class="error-container">
        <text class="error-text">{{ error }}</text>
        <button class="retry-btn" @click="loadArticle">重试</button>
      </view>

      <scroll-view v-else scroll-y class="article-content">
        <view class="article-header">
          <text class="article-title">{{ articleData.title }}</text>
          <text class="article-date">{{ articleData.date }}</text>
        </view>
        <view class="article-body">
          <view class="rich-text-wrapper">
            <rich-text :nodes="articleData.content"></rich-text>
          </view>
        </view>
      </scroll-view>
    </view>
  </full-page>
</template>

<script setup>
import { onLoad } from "@dcloudio/uni-app";
import FullPage from "@/components/full-page.vue";
import api from "@/utils/api.js";
import { set } from "@/utils/cache";
import { toast } from "@/utils/widget.js";
import { ref } from "vue";
import { storeToRefs } from "pinia";
import useAccountStore from "@/store/account.js";
const { account } = storeToRefs(useAccountStore());
const { login } = useAccountStore()
const loading = ref(true);
const error = ref("");
const articleData = ref({
  title: "",
  content: "",
  date: "",
});

let articleId = "";
const corpId = ref("");

const markArticleRead = async (sendId) => {
  const unionid = account.value?.unionid;
  if (!unionid || !articleId) return;
  try {
    await api(
      "addArticleReadRecord",
      { corpId: corpId.value, articleId, unionid, sendId },
      false
    );
  } catch (err) {
    console.warn("markArticleRead failed:", err?.message || err);
  }
};

// 处理富文本内容，使图片自适应
const processRichTextContent = (html) => {
  if (!html) return "";

  // 给所有 img 标签添加样式
  let processedHtml = html.replace(
    /<img/gi,
    '<img style="max-width:100%;height:auto;display:block;margin:10px 0;"'
  );

  // 移除可能存在的固定宽度样式
  processedHtml = processedHtml.replace(
    /style="[^"]*width:\s*\d+px[^"]*"/gi,
    (match) => {
      return match.replace(/width:\s*\d+px;?/gi, "max-width:100%;");
    }
  );

  // 处理表格，添加自适应样式
  processedHtml = processedHtml.replace(
    /<table/gi,
    '<table style="max-width:100%;overflow-x:auto;display:block;"'
  );

  // 给整体内容添加容器样式
  processedHtml = `<div style="width:100%;overflow-x:hidden;word-wrap:break-word;word-break:break-all;">${processedHtml}</div>`;

  return processedHtml;
};

// 加载文章
const loadArticle = async () => {
  loading.value = true;
  error.value = "";
  try {
    const res = await api("getArticle", {
      id: articleId,
      corpId: corpId.value,
    });

    if (res.success && res.data) {
      // 格式化日期
      let date = "";

      if (res.data.createTime) {
        const d = new Date(res.data.createTime);
        const year = d.getFullYear();
        const month = String(d.getMonth() + 1).padStart(2, "0");
        const day = String(d.getDate()).padStart(2, "0");
        date = `${year}-${month}-${day}`;
      }

      articleData.value = {
        title: res.data.title || "宣教文章",
        content: processRichTextContent(res.data.content || ""),
        date: date,
      };
      if (isWechatChannels(res.data)) {
        uni.openChannelsActivity({
          finderUserName: res.data.wechatChannels.finderUserName,
          feedId: res.data.wechatChannels.feedId,
          fail: err => {
            const errMsg = err.errMsg || '';
            if (/cancel/i.test(errMsg)) {
              return
            }
            toast(`打开视频号失败:${errMsg}`)
          }
        })
        return
      }
      // if (res.data.link) {
      //   uni.openOfficialAccountArticle({
      //     url: res.data.link,
      //     fail: err => {
      //       const errMsg = err.errMsg || '';
      //       console.error(errMsg)
      //       console.log(errMsg)
      //       if (/cancel/i.test(errMsg)) {
      //         return
      //       }
      //       toast(`打开文章失败:${errMsg}`)
      //     }
      //   })
      // }
    } else {
      error.value = res.message || "加载文章失败";
    }
  } catch (err) {
    console.error("加载文章失败:", err);
    error.value = "加载失败，请重试";
  } finally {
    loading.value = false;
  }
};

function isWechatChannels(item) {
  return item?.wechatChannels?.finderUserName && item?.wechatChannels?.feedId;
}

async function handleSend(sendId) {
  try {
    await login();
    markArticleRead(sendId);
    authToTeam(sendId)
  } catch (e) {
    console.log(e)
  }
}

// 通过发送记录 将微信用户关联到团队
async function authToTeam(sendId) {
  const res = await api("relateWechatAccountWithTeam", {
    sendId,
    openid: account.value?.openid,
    unionid: account.value?.unionid,
    appid: account.value?.appId,
  })
  if (res.success) {
    set('home-invite-team-info', { teamId: res.data })
  }
}


onLoad((options) => {
  corpId.value = options.corpId;
  if (options.id) {
    articleId = options.id;
    if (options.sendId) {
      handleSend(options.sendId)
    }
    loadArticle();
  } else {
    error.value = "文章信息不完整";
    loading.value = false;
  }
});
</script>

<style scoped lang="scss">
.article-detail-page {
  width: 100%;
  height: 100vh;
  background-color: #fff;
}

.loading-container,
.error-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100vh;
  padding: 40rpx;
}

.loading-text {
  margin-top: 20rpx;
  font-size: 30rpx;
  color: #999;
}

.error-text {
  font-size: 30rpx;
  color: #999;
  margin-bottom: 30rpx;
  text-align: center;
}

.retry-btn {
  padding: 16rpx 60rpx;
  background-color: #0877f1;
  color: #fff;
  border: none;
  border-radius: 8rpx;
  font-size: 30rpx;
}

.article-content {
  height: 100vh;
}

.article-header {
  padding: 40rpx 30rpx 20rpx;
  border-bottom: 1px solid #eee;
}

.article-title {
  display: block;
  font-size: 38rpx;
  font-weight: bold;
  color: #333;
  line-height: 1.6;
  margin-bottom: 20rpx;
}

.article-date {
  display: block;
  font-size: 26rpx;
  color: #999;
}

.article-body {
  padding: 0;
}

.rich-text-wrapper {
  padding: 30rpx;
  width: 100%;
  box-sizing: border-box;
  overflow: hidden;
}

.rich-text-wrapper ::v-deep rich-text {
  width: 100%;
}

.rich-text-wrapper ::v-deep rich-text img {
  max-width: 100% !important;
  height: auto !important;
  display: block;
}
</style>
