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

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

const base_url = '/sgsafe/EmergencyDrills';

/* 通用方法： 重置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({
  planName: '',
  drillDeptCode: ''
});

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

const resetCondition = () => {
  basicReset();
  fetchData.value = {
    planName: '',
    drillDeptCode: ''
  };
  onLoad();
};

/* 查询请求 */
const queryFetch = async () => {
  fetchData.value.drillDeptCode = postBackRegimeScope.value.split('-')[0];
  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;
  }
};

/* 组织树选择 */
const showBottom = ref(false);
const currentDeptName = ref('');
const postBackRegimeScope = ref();
import OrganizationalWithLeaf from '@/components/OrganizationalWithLeaf.vue';

const showPickerHandle = () => {
  showBottom.value = true;
};

const handleTableDataUserDeptUpdate = async (nodeData) => {
  console.log('nodeData', nodeData);
  postBackRegimeScope.value = nodeData;
  currentDeptName.value = nodeData.split('-')[1];
  basicReset();
  await onLoad();
  showBottom.value = false;
};

const cachedDeptCode = ref('');
const getDeptInfo = (currentDeptInfo) => {
  postBackRegimeScope.value = currentDeptInfo;
  currentDeptName.value = currentDeptInfo.split('-')[1];
  /* Pinia初始化属性 */
  if (emergencyInfo.currentDeptCode) {
    postBackRegimeScope.value = emergencyInfo.currentDeptCode + '-' + emergencyInfo.currentDeptName;
    currentDeptName.value = emergencyInfo.currentDeptName;
    fetchData.value.planName = emergencyInfo.conditionalQueryAttributes;
  }
  basicReset();
  onLoad();
};

/**
 * 数据传回组织树组件
 */
if (emergencyInfo.currentDeptCode) {
  cachedDeptCode.value = emergencyInfo.currentDeptCode;
}

const getTypeState = (state) => {
  const typeMap = {
    '0': 'danger',
    '1': 'success'
  };
  return typeMap[state] || '';
};

const getPlanState = (state) => {
  const typeMap = {
    '0': '未完成',
    '1': '已完成'
  };
  return typeMap[state] || '';
};

const showDialogVisible = ref(false);
const deleteInfo = ref();
const handleDelete = (item, idx) => {
  openStates.value[idx] = !openStates.value[idx];
  showDialogVisible.value = true;
  deleteInfo.value = item;
};

/* 数据删除 */
const onDelete = () => {
  const item = deleteInfo.value;
  const url = base_url + '/remove';
  const param = {
    json: JSON.stringify(item)
  };
  proxy.$axios.post(url, param).then(res => {
    if (res.data.code === 0) {
      showSuccessToast('删除成功');
      basicReset();
      onLoad();
    } else {
      showFailToast('操作失败!' + res.data.msg);
    }
  });
};

/**
 * 按钮实现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);
};

const judgeDrillsIdExisting = async (id) => {
  const url = '/sgsafe/OnsiteDisposalContent/judgeExisting';
  const param = {
    json: id
  };
  const res = await proxy.$axios.post(url, param);
  if (res.data.code === 0) {
      if (res.data.data === 0) {
       showFailToast('当前暂无演练过程')
       return
      }
      await router.push({path: '/specificStepsView', query: { drillsId: id }})
  }
};


/**
 * 路由跳转前，pinia中缓存数据
 */
onBeforeRouteLeave((to, from, next) => {
  if (to.path === '/emergencyDrillPlanEdit' || to.path === '/emergencyDrillActEdit') {
    emergencyInfo.$patch({
      currentDeptCode: postBackRegimeScope.value.split('-')[0],
      currentDeptName: postBackRegimeScope.value.split('-')[1],
      conditionalQueryAttributes: fetchData.value.planName
    });
  } else {
    emergencyInfo.clearMainDeptInfo();
  }
  next();
});

</script>

<template>
  <div class="page-container">
    <van-sticky>
      <van-nav-bar title="应急演练">
        <template #right>
          <van-icon
            name="add"
            size="24"
            color="var(--van-nav-bar-icon-color)"
            @click="router.push('/emergencyDrillPlanEdit')"
          />
        </template>
      </van-nav-bar>

      <van-search
        v-model="fetchData.planName"
        @search="onSearch"
        @clear="resetCondition"
        placeholder="请输入演练计划名称"
      />

      <van-field
        v-model="currentDeptName"
        label="当前组织"
        placeholder="请选择组织架构"
        readonly
        right-icon="arrow-down"
        @click="showPickerHandle()"
      />
    </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: '/emergencyDrillPlanEdit', query: { planInfo: JSON.stringify(item) } }">
                    <template #title>
                      <span class="bold-title" style="margin-right: 10px">{{ item.planName }}</span>
                      <van-tag :type="getTypeState(item.state)">{{ getPlanState(item.state) }}</van-tag>
                    </template>
                    <template #label>
                      <span style="margin-right: 10px">月度：{{ item.planYear + '年' + item.planMonth + '月' }}</span>
                      <span style="margin-right: 10px">层级：{{ item.planLevel }}</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: '/emergencyDrillActEdit', query: { planInfo: JSON.stringify(item) } }" />
                <van-button class="delete-button" square type="success" text="查看演练过程"
                            @click="judgeDrillsIdExisting(item.id)" />
                <van-button class="delete-button" square type="danger" text="删除" @click="handleDelete(item,idx)" />
              </template>
            </van-swipe-cell>
          </div>
        </van-list>
      </van-pull-refresh>
    </div>

    <van-popup :close-on-click-overlay="false" :lazy-render="false" v-model:show="showBottom" position="bottom">
      <OrganizationalWithLeaf :cached-dept-code="cachedDeptCode" @init="getDeptInfo" @close="showBottom = false"
                              @update:selected-node="handleTableDataUserDeptUpdate" />
    </van-popup>

    <van-dialog v-model:show="showDialogVisible" title="提示" show-cancel-button
                confirm-button-color="#ee0124" message="确定删除本条数据吗" @confirm="onDelete" />
  </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>
