<script setup>
import { getCurrentInstance, onMounted, ref } from 'vue';
import { onBeforeRouteLeave, useRouter } from 'vue-router';
import { useEmergencyStore } from '@/stores/emergencyManager.js';

const emergencyInfo = useEmergencyStore();
const {
  proxy
} = getCurrentInstance();

const base_url = '/sgsafe/KeyMattersManagement';

/* 通用方法： 重置list数据 */
const basicReset = () => {
  finished.value = false;
  loading.value = true;
  pageNum.value = 1;
  list.value = [];
};

/* 返回上一级页面 */
const router = useRouter();

/* 查询数据 */
const pageNum = ref(1);
const pageSize = ref(10);
const total = ref(0);
const resultData = ref([]);
const fetchData = ref({
  itemTitle: '',
  itemSource: 'ASSIGNED',
});

const onSearch = () => {
  basicReset();
  onLoad();
};

const resetCondition = () => {
  basicReset();
  fetchData.value.itemTitle = '';
  onLoad();
};

/* 查询请求 */
const queryFetch = async () => {
  const url = base_url + '/query';
  const param = {
    page: pageNum.value,
    rows: pageSize.value,
    params: JSON.stringify(fetchData.value)
  };
  try {
    const res = await proxy.$axios.post(url, param);
    if (res.data.code === 0) {
      total.value = res.data.data.total;
      resultData.value = res.data.data.records;
    } else {
      console.log('查询失败!' + res.data.msg);
    }
  } catch (error) {
    console.error('请求出错:', error);
  }
};

/* 列表加载与下拉刷新 */
const list = ref([]);
const refreshing = ref(false);
const loading = ref(false);
const finished = ref(false);

const onRefresh = () => {
  basicReset();
  onLoad();
};

const onLoad = async () => {
  if (refreshing.value) {
    list.value = [];
    pageNum.value = 1;
    refreshing.value = false;
  }
  try {
    await queryFetch();
    if (pageSize.value * pageNum.value < total.value) {
      list.value = [...list.value, ...resultData.value];
      openStates.value = new Array(list.value.length).fill(true);
      pageNum.value++;
    } else {
      list.value = [...list.value, ...resultData.value];
      openStates.value = new Array(list.value.length).fill(true);
      finished.value = true;
    }
  } catch (error) {
    console.log(error);
    finished.value = true;
  } finally {
    loading.value = false;
  }
};

/**
 * 按钮实现swipe-cell滑动
 */
const openStates = ref([]);
const swipeCellRefs = ref([]);
const getSwipeCellRef = (el, index) => {
  if (el) {
    swipeCellRefs.value[index] = el;
  }
};
const openSwipe = (idx) => {
  openStates.value = new Array(list.value.length).fill(true);
  if (idx >= 0 && idx < swipeCellRefs.value.length) {
    openStates.value[idx] = false;
    swipeCellRefs.value[idx].open('right');
  }
  document.addEventListener('click', handleDocumentClick);
};
const closeSwipe = (idx) => {
  if (idx >= 0 && idx < swipeCellRefs.value.length) {
    openStates.value[idx] = true;
    swipeCellRefs.value[idx].close();
  }
};
/** 滑动监听 **/
const handleSwipeOpen = (idx) => {
  openStates.value[idx] = false;
};

const handleSwipeClose = (idx) => {
  openStates.value[idx] = true;
};

/**
 * 当点击滑动单元格时，开始监听点击事件
 */
const handleDocumentClick = (event) => {
  openStates.value = new Array(list.value.length).fill(true);
};

/**
 * pinia读取和缓存数据
 */
onMounted(() => {
  if (emergencyInfo.conditionalQueryAttributes) {
    fetchData.value.itemTitle = emergencyInfo.conditionalQueryAttributes;
  }
  basicReset();
  onLoad();
})
onBeforeRouteLeave((to, from, next) => {
  if (to.path === '/keyMatters/view' || to.path === '/keyMatters/report') {
    emergencyInfo.$patch({
      conditionalQueryAttributes: fetchData.value.itemTitle
    });
  } else {
    emergencyInfo.clearMainDeptInfo();
  }
  next();
});

</script>

<template>
  <div class="page-container">
    <van-sticky>
      <van-nav-bar title="重点事项汇报">
      </van-nav-bar>

      <van-search
        v-model="fetchData.itemTitle"
        @search="onSearch"
        @clear="resetCondition"
        placeholder="请输入事项标题"
      />
    </van-sticky>

    <div class="scroll-container">
      <van-pull-refresh
        v-model="refreshing"
        success-text="刷新成功"
        @refresh="onRefresh"
      >
        <van-list
          class="listDiv"
          :immediate-check="false"
          v-model:loading="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="onLoad"
        >
          <div v-for="(item,idx) in list" :key="item.id">
            <van-swipe-cell
              title-style="color: #007aff"
              class="goods-card"
              :ref="el => getSwipeCellRef(el, idx)"
              @open="handleSwipeOpen(idx)"
              @close="handleSwipeClose(idx)"
            >
              <template #default>
                <div class="swipe-cell-default">
                  <van-cell :to="{ path: '/keyMatters/view', query: { keyMatter: JSON.stringify(item) } }">
                    <template #title>
                      <span class="bold-title" style="margin-right: 10px">{{ item.itemTitle }}</span>
                      <van-tag style="margin-right: 10px" :type="item.isFinished === '已完成' ? 'success' : 'danger'">{{ item.isFinished }}</van-tag>
                      <van-tag :type="item.isOverdue === '逾期' ? 'danger' : 'success'">{{ item.isOverdue === '逾期' ? '逾期' : '未逾期' }}</van-tag>
                    </template>
                    <template #label>
                      <span style="margin-right: 10px">事项内容：{{ item.itemContent }}</span>
                    </template>
                  </van-cell>
                  <div class="swipe-cell-default-icon">
                    <van-icon v-if="openStates[idx]" name="arrow-double-left" @click.stop="openSwipe(idx)" />
                    <van-icon v-else name="arrow-double-right" @click.stop="closeSwipe(idx)" />
                  </div>
                </div>
              </template>

              <template #right>
                <van-button class="delete-button" square type="primary" text="汇报"
                            :to="{ path: '/keyMatters/report', query: { keyMatter: JSON.stringify(item) } }" />
              </template>
            </van-swipe-cell>
          </div>
        </van-list>
      </van-pull-refresh>
    </div>
  </div>
</template>

<style scoped>
.page-container {
  height: 100vh; /* 关键：外层容器高度设为视口高度 */
  display: flex;
  flex-direction: column;

}

/*  overflow-y: auto; !* 启用垂直滚动 *!*/


.scroll-container {
  flex: 1;
  overflow: auto;
  -webkit-overflow-scrolling: touch; /* iOS 平滑滚动 */
}

/* 可选：隐藏滚动条（视觉优化） */
.scroll-container::-webkit-scrollbar {
  display: none;
}

.goods-card {
  margin: 0;
}

.delete-button {
  height: 100%;
}

.bold-title {
  font-weight: bold;
  color: #333;
}

.swipe-cell-default {
  display: flex;
  background-color: #ffffff;
  justify-content: center;
  align-items: center;
}

.swipe-cell-default-icon {
  width: 60px;
  display: flex;
  justify-content: center;
}
</style>
