<template>
  <view class="word-list-page">
    <view class="icon-title-navBar-box">
      <view @click="goBack" class="nav-bar-icon"></view>
      <text class="nav-bar-title">{{ listData.title || "" }}</text>
    </view>
    <view class="ezy-page-body word-body-box">
      <view
          class="word-tab-box"
          v-if="listData.danyuanNumberList && listData.danyuanNumberList.length > 0"
      >
        <!-- disabled-->
        <icon class="word-jt jt-left" :class="{ disabled: isFirstGroup }" @click="handleLeftClick"/>
		<view class="tab-item-list" id="tab-item-list">
          <!-- active -->
          <ezyActiveVue
              :id="'item-' + item.danyuanId"
              class="ezy-btn-active tab-item"
              v-for="(item, index) in listData.danyuanNumberList"
              :key="item.danyuanId"
              :class="{ active: listData.activeIndex == index }"
              v-show="
			    isTargetInSameGroup(
			      listData.danyuanNumberList,
			      listData.danyuanNumberList[listData.activeIndex],
			      item.danyuanId,
			    )
			  "
              @click="handleTabClick(index)"
          >
            {{ item.danyuanName }}
          </ezyActiveVue>
        </view>
        <!-- disabled-->
        <icon class="word-jt jt-right"
              :class="{ disabled: isLastGroup }"
              @click="handleRightClick"/>
      </view>

      <swiper
          class="word-list-swiper-box"
          :indicator-dots="false"
          :autoplay="false"
          :circular="false"
          :current="listData.activeIndex"
          @change="handleSwiperChange"
		  @touchstart="handleSwiperTouchStart"
		  @touchmove="handleSwiperTouchMove"
          :disable-touch="isSwiperDisabled"
      >
        <swiper-item
            class="word-list-swiper-item"
            v-for="citem in unitList"
            :key="citem.danyuanId"
            @touchstart="handleTouchStart"
            @touchend="handleTouchEnd"
        >
          <view
              class="word-list-body"
              v-if="citem.wordList && citem.wordList.length > 0"
          >
            <!-- num -->
            <view class="word-num-box">
              <icon></icon
              >
              <text
              >{{ citem.studyCount || 0 }}/{{ citem.count || 0 }}词
              </text
              >
            </view>

            <!-- 单词 -->
            <ezyActiveVue
                class="ezy-list-item-active word-list-item"
                v-for="(item, index) in citem.wordList"
                :key="index"
                @click="toWord(item)"
                :class="{ active: item.wcFlag == 1 }"
            >
              <view class="item-word">
                <view class="word-text">
                  <text
                      v-for="(word, wordIndex) in item.chaifen"
                      :key="wordIndex"
                      class="word-color"
                  >
                    {{ word }}
                  </text>
                </view>
                <view class="phonetic-alphabet">{{
                    item.yinbiao || ""
                  }}
                </view>
              </view>
              <view class="item-explain">
                <view class="item-explain-content">
                  <view
                      class="explain-text"
                      v-for="(meaning, meaningIndex) in item.jianyi"
                      :key="meaningIndex"
                  >{{ meaning }}
                  </view
                  >
                </view>
              </view>
              <view class="item-arrow">
                <icon></icon>
              </view>
            </ezyActiveVue>
          </view>
          <!-- 没有单词 -->
          <view class="no-word-box" v-else> 暂无单词</view>
        </swiper-item>
      </swiper>
    </view>
    <tip-small-dialog ref="goPayDialogRef" @confirm-btn="goPayPage" content="需要购买当前课程才能学习" qrBtnName="前往购买"></tip-small-dialog>
    <view class="ezy-tip-mask-box" v-if="isShowTishi" @click="updateDate"></view>
  </view>
</template>

<script setup>
import {reactive, ref, nextTick, computed, getCurrentInstance} from "vue";
import {
  toast,
  getDataFromStr,
  useActiveDomIntoView,
  isTargetInSameGroup,
} from "@/utils/common";
import {onLoad, onShow} from "@dcloudio/uni-app";
import {getWordZhangList} from "@/api/chaojidanci.js";
import cacheManager from "@/utils/cacheManager.js";
import {useSwiper} from "@/utils/useSwiper";
import tipSmallDialog from "@/components/dialog/tipSmallDialog.vue";
import ezyActiveVue from "@/components/ezyActive/ezyActive.vue";
import {useShowTishi} from "./useTishi.js"
import {yingyuSave2} from "../../../api/chanpinneirong";

const goPayDialogRef = ref(null);
const listData = reactive({
  danyuanNumberList: [], //节名称
  title: "", // 版本+年级+学期
  wordList: [], // 单词列表，默认值设为空数组
  activeIndex: 0,
});
let danyuanId = ref(null);
let routerOpt = ref(false);
let wordLeft = ref(0);
const unitList = ref([]);
const info = reactive({
  levelId: null,
  zhangId: null,
});

const {
  isShowTishi,
  updateDate,
} = useShowTishi()

const {swiperData, handleTouchStart, handleTouchEnd, userCode} = useSwiper(
    listData,
    (userCode) => {
    },
);

// 计算属性，控制 swiper 是否禁用触摸
const isSwiperDisabled = computed(() => {
  // 检查下一个项是否被锁定
  const nextIndex = listData.activeIndex + 1;
  if (nextIndex < listData.danyuanNumberList.length) {
    const nextItem = listData.danyuanNumberList[nextIndex];
    if (nextItem.lock) {
      return true;
    }
  }
  return !swiperData.isAllowed;
});

// 记录swiper触摸开始位置
let startX = 0;

// 计算属性，判断是否在第一组
const isFirstGroup = computed(() => {
  const chunkSize = 4;
  const currentGroup = Math.floor(listData.activeIndex / chunkSize);
  return currentGroup === 0;
});

// 计算属性，判断是否在最后一组
const isLastGroup = computed(() => {
  const chunkSize = 4;
  const currentGroup = Math.floor(listData.activeIndex / chunkSize);
  const totalGroups = Math.ceil(listData.danyuanNumberList.length / chunkSize);
  return currentGroup >= totalGroups - 1;
});


// 处理左侧箭头点击
function handleLeftClick() {
  const chunkSize = 4;
  const currentGroup = Math.floor(listData.activeIndex / chunkSize);
  if (currentGroup > 0) {
    const prevGroupStartIndex = (currentGroup - 1) * chunkSize;
    const item = listData.danyuanNumberList[prevGroupStartIndex];
    if (item.lock) {
      // 弹出弹窗让用户确认是否去购买
      goPayDialogRef.value.handleShow();
      return;
    }
    listData.activeIndex = prevGroupStartIndex;
    centerActiveTab();
    updataShuju(listData.danyuanNumberList[prevGroupStartIndex]);
  }
}

// 处理右侧箭头点击
function handleRightClick() {
  const chunkSize = 4;
  const currentGroup = Math.floor(listData.activeIndex / chunkSize);
  const totalGroups = Math.ceil(listData.danyuanNumberList.length / chunkSize);
  if (currentGroup < totalGroups - 1) {
    const nextGroupStartIndex = (currentGroup + 1) * chunkSize;
    const item = listData.danyuanNumberList[nextGroupStartIndex];
    if (item.lock) {
      // 弹出弹窗让用户确认是否去购买
      goPayDialogRef.value.handleShow();
      return;
    }
    listData.activeIndex = nextGroupStartIndex;
    centerActiveTab();
    updataShuju(listData.danyuanNumberList[nextGroupStartIndex]);
  }
}


// 处理swiper触摸开始
function handleSwiperTouchStart(e) {
  startX = e.touches[0].clientX;
}

// 处理swiper触摸移动
function handleSwiperTouchMove(e) {
  const currentX = e.touches[0].clientX;
  const diffX = currentX - startX;

  // 向左滑动
  if (diffX < -50) {
    // 检查下一个项是否被锁定
    const nextIndex = listData.activeIndex + 1;
    if (nextIndex < listData.danyuanNumberList.length) {
      const nextItem = listData.danyuanNumberList[nextIndex];
      if (nextItem.lock) {
        // 阻止滑动
        e.preventDefault();
        // 弹出弹窗
        goPayDialogRef.value.handleShow();
      }
    }
  }
}

onLoad((options) => {
  routerOpt.value = options;
  // 非游客
  danyuanId.value = routerOpt.value.danyuanId;

});

onShow(() => {
  getWordListData();
})

// Swiper 切换
function handleSwiperChange(e) {
  // 只有当 swiper 的变化是由用户手动滑动引起的，才调用 updataShuju 函数
  // 避免由数据更新引起的 swiper 变化触发二次请求
  if (e.detail.source === 'touch') {
	  
	  const currentIndex = e.detail.current;
	  const item = listData.danyuanNumberList[currentIndex];
	     if (item.lock) {
	       // 弹出弹窗让用户确认是否去购买
	       goPayDialogRef.value.handleShow();
	       // 回退到原索引
	       nextTick(() => {
	         listData.activeIndex = e.detail.current - 1 >= 0 ? e.detail.current - 1 : 0;
	       });
	       return;
		return;
	  }
	  
	  listData.activeIndex = e.detail.current;
	  if (!swiperData.isAllowed) {
		// 不满足条件时回退到原索引
		nextTick(() => {
		  listData.activeIndex = 0; // 强制回退
		});
		swiperData.isAllowed = false; // 重置状态
	  }
	  // findWordLeft(listData.activeIndex);
	  centerActiveTab();
	  updataShuju(listData.danyuanNumberList[listData.activeIndex]);
  }
}

// 处理tab点击
function handleTabClick(index) {
  const item = listData.danyuanNumberList[index];
  if (item.lock) {
	// 弹出弹窗让用户确认是否去购买
	goPayDialogRef.value.handleShow();
	return;
  }
  listData.activeIndex = index;
  centerActiveTab();
  updataShuju(listData.danyuanNumberList[index]);
}

// 使激活的tab居中显示
function centerActiveTab() {
  nextTick(() => {
     const query = uni.createSelectorQuery().in(getCurrentInstance());
        query.select('#tab-item-list').boundingClientRect();
        query.select('.tab-item.active').boundingClientRect();
        query.exec((res) => {
          if (res && res[0] && res[1]) {
            const containerWidth = res[0].width;
            const activeLeft = res[1].left - res[0].left;
            const activeWidth = res[1].width;
            const scrollLeft = activeLeft - (containerWidth / 2) + (activeWidth / 2);
            
            // 边界处理
            const finalScrollLeft = Math.max(0, scrollLeft);
            
            // 使用 uni-app 的 API 来设置滚动位置
            uni.createSelectorQuery().in(getCurrentInstance())
              .select('#tab-item-list')
              .fields({ node: true }, (result) => {
                if (result && result.node) {
                  const node = result.node;
                  node.scrollLeft = finalScrollLeft;
                }
              })
              .exec();
          }
		})
  });
}


// 返回
function goBack() {
  // uni.redirectTo({
  //   url: `/pages/study/index`,
  // });
  uni.navigateBack()
}

// 修改缓存zid  用于定位岛
async function updataCache(da) {
  console.log('da', da)
  let req = {
    "banbenId": routerOpt.value.banbenId,
    "danyuanId": danyuanId.value
  }
  const res = await yingyuSave2(req);
  if (res.code == 0) {

    const cacheData = cacheManager.get('contentInfo') || {};
    cacheData.curDanyuanName = da.intro; // 此处显示介绍，单元名
    cacheData.danyuanId = da.danyuanId;
    cacheData.curDanyuanId = da.danyuanId;
    cacheManager.updateObject('contentInfo', cacheData);
  } else {
    return false;
  }
}

//tab click
function handleTitleClick(item) {
  updataShuju(item);
}

// 修改数据 &&定位岛
function updataShuju(data) {
  // 非游客
  danyuanId.value = data.danyuanId;
  // 修改缓存zid  用于定位岛
  updataCache(data);
  getWordListData();
}

// 返回节index
function findIndexByDanyuanId(list, danyuanId) {
  const findIndex = list.findIndex((item) => item.danyuanId == danyuanId);
  // unit滚动到指定位置
  findWordLeft(findIndex);
  return findIndex;
}

// 获取滚动距离
function findWordLeft(data) {
  // useActiveDomIntoView(".word-title-box", ".title-item.active");
  // 替换为 uni-app 兼容的滚动方法
  centerActiveTab();
}

function getWordListData() {
  const opt = {
    danyuanId: danyuanId.value, // routerOpt.danyuanId
    banbenId: routerOpt.value.banbenId, // routerOpt.banbenId
  };
  getWordZhangList(opt)
      .then((res) => {
        if (res.code === 0) {
          listData.title = res.data.title;
          unitList.value = res.data.danyuanWordsList;
          listData.danyuanNumberList = res.data.danyuanNumberList;
          unitList.value.forEach((item) => {
            if (item.danyuanId == danyuanId.value) {
              listData.activeIndex = findIndexByDanyuanId(
                  listData.danyuanNumberList,
                  danyuanId.value
              );
            }
          });
        }
      })
      .catch((err) => {
        console.log('err', err)
        toast("获取单词列表数据失败");
      });
}

// 单词
function toWord(data) {
  uni.navigateTo({
    url: `/pages/chaojidanci/newEnglish/index?danyuanId=${danyuanId.value}&wordId=${data.id}`,
  });
}

// 去支付
function goPayPage() {
  uni.navigateTo({
    url: "/pages/chanpinShop/cp3/dingdan"
  });
}
</script>
