import { documentsList,findDataInfo} from '../../api/documentManagement'

/**
 * 本地存储选中的问题ID的键名
 * @type {string}
 */
const SELECTED_PROBLEM_ID_KEY = 'announcementDetails:selectedId'
export default {  
    data() {
      return {
        problems: [
          {
            id: 1,
            title: "如何开始挖矿？",
            content: "详细步骤：注册、配置矿机、连接矿池。",
          },
          {
            id: 2,
            title: "如何查看收益？",
            content: "登录后在个人中心查看收益统计。",
          },
          {
            id: 3,
            title: "如何联系客服？",
            content: "可通过在线客服或提交工单联系我们。",
          },
        ],
        listParams:{
            type:"3",//常见问题
            lang:this.$i18n.locale,
            pageNum:1,
            pageSize:50
          },
          problemLoading:false,
          DetailsParams:{
            id:"",
            lang:this.$i18n.locale,
          },
          info:""
      };
    },
    mounted() {
        // this.DetailsParams.id = this.$route.query.id;
        // console.log(this.$route.query.id,"this.DetailsParams.id");
        // if (this.DetailsParams.id) {
        //     this.fetchProblemDetails(this.DetailsParams)
        // }
        this.fetchProblemsList(this.listParams)
    },
    methods: {
        async fetchProblemsList(params) {
            this.setLoading('problemLoading', true);
            const res = await documentsList(params)
            if(res && res.code === 200){
                this.problems = res.rows;
                // 优先级：URL 参数 > 本地存储 > 列表首项
                const routeId = this.$route && this.$route.query && this.$route.query.id ? String(this.$route.query.id) : ''
                const savedId = this.getSavedSelectedId()

                let resolvedId = routeId || savedId || ''

                if (!resolvedId && this.problems && this.problems.length > 0) {
                    resolvedId = String(this.problems[0].id)
                }

                // 如果存在但不在当前列表中，则回退到首项
                if (resolvedId) {
                    const existsInList = (this.problems || []).some(item => String(item.id) === String(resolvedId))
                    if (!existsInList && this.problems && this.problems.length > 0) {
                        resolvedId = String(this.problems[0].id)
                    }
                }

                this.DetailsParams.id = resolvedId

                // 同步到URL与本地存储
                this.persistSelectedId(this.DetailsParams.id)
                this.updateRouteQueryId(this.DetailsParams.id)

                if (this.DetailsParams.id) {
                    this.fetchProblemDetails(this.DetailsParams)
                }
            }
            this.setLoading('problemLoading', false);
        },

        async fetchProblemDetails(params) {
            this.setLoading('problemLoading', true);
            const res = await findDataInfo(params)
            if(res && res.code === 200){
               console.log(res,"res");
                this.info = res.data.content || ""
            }
            this.setLoading('problemLoading', false);
        },




      /**
       * 跳转到问题详情页
       * @param {number} id 问题ID
       */
      handleClick(id) {
        // 更新当前选中ID
        this.DetailsParams.id = id
        // 持久化并同步URL
        this.persistSelectedId(this.DetailsParams.id)
        this.updateRouteQueryId(this.DetailsParams.id)
        // 获取详情
        this.fetchProblemDetails(this.DetailsParams)
      },

      /**
       * 将选中的问题ID持久化到本地存储
       * @param {string|number} id 问题ID
       * @returns {void}
       */
      persistSelectedId(id) {
        try {
          window.localStorage.setItem(SELECTED_PROBLEM_ID_KEY, String(id))
        } catch (error) {
          // 上报或静默处理本地存储异常
          console.error('persistSelectedId error', error)
        }
      },

      /**
       * 读取本地存储中保存的选中问题ID
       * @returns {string}
       */
      getSavedSelectedId() {
        try {
          return window.localStorage.getItem(SELECTED_PROBLEM_ID_KEY) || ''
        } catch (error) {
          console.error('getSavedSelectedId error', error)
          return ''
        }
      },

      /**
       * 使用 replace 同步更新当前路由的查询参数中的 id
       * 避免产生新的历史记录条目
       * @param {string|number} id 问题ID
       * @returns {void}
       */
      updateRouteQueryId(id) {
        try {
          if (!this.$route) return
          const targetId = String(id)
          const currentId = this.$route && this.$route.query && this.$route.query.id ? String(this.$route.query.id) : ''
          if (currentId === targetId) return

          const nextQuery = { ...(this.$route.query || {}), id: targetId }
          if (this.$router && typeof this.$router.replace === 'function') {
            const maybePromise = this.$router.replace({ query: nextQuery })
            if (maybePromise && typeof maybePromise.catch === 'function') {
              maybePromise.catch(() => {})
            }
          }
        } catch (error) {
          console.error('updateRouteQueryId error', error)
        }
      },
    },
  };