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

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

const equipment_url = '/sgsafe/EquipmentRecords';
const activity_url = '/sgsafe/ActivityRecords';

/* 通用方法： 重置list数据 */
const basicResetActivities = () => {
  finishedActivities.value = false;
  loadingActivities.value = true;
  pageNumActivities.value = 1;
  listActivities.value = [];
};

const basicResetEquipments = () => {
  finishedActivities.value = false;
  loadingEquipments.value = true;
  pageNumEquipments.value = 1;
  listEquipments.value = [];
};

/* 查询数据 */
const pageNumActivities = ref(1);
const pageSizeActivities = ref(10);
const totalActivities = ref(0);
const resultDataActivities = ref([]);
const fetchDataActivities = ref({
  inspectionCycle: '',
  responsibleUnitCode: ''
});

const pageNumEquipments = ref(1);
const pageSizeEquipments = ref(10);
const totalEquipments = ref(0);
const resultDataEquipments = ref([]);
const fetchDataEquipments = ref({
  inspectionCycle: '',
  responsibleUnitCode: ''
});

const onRefreshActivities = () => {
  basicResetActivities();
  onLoadActivities();
};

const onRefreshEquipments = () => {
  basicResetEquipments();
  onLoadEquipments();
};

/* 查询请求 */
const queryFetchActivities = async () => {
  fetchDataActivities.value.responsibleUnitCode = currentDeptCode.value;
  let activitiesUrl = activity_url + '/query';
  const paramActivities = {
    page: pageNumActivities.value,
    rows: pageSizeActivities.value,
    params: JSON.stringify(fetchDataActivities.value)
  };
  try {
    const resActivities = await proxy.$axios.post(activitiesUrl, paramActivities);
    if (resActivities.data.code === 0) {
      totalActivities.value = resActivities.data.data.total;
      resultDataActivities.value = resActivities.data.data.records;
    } else {
      console.log('操作失败!' + resActivities.data.msg);
    }
  } catch (error) {
    console.error('请求出错:', error);
  }
};

const queryFetchEquipments = async () => {
  fetchDataEquipments.value.responsibleUnitCode = currentDeptCode.value;
  let equipmentsUrl = equipment_url + '/query';
  const paramEquipments = {
    page: pageNumEquipments.value,
    rows: pageSizeEquipments.value,
    params: JSON.stringify(fetchDataEquipments.value)
  };
  try {
    const resEquipments = await proxy.$axios.post(equipmentsUrl, paramEquipments);
    if (resEquipments.data.code === 0) {
      totalEquipments.value = resEquipments.data.data.total;
      resultDataEquipments.value = resEquipments.data.data.records;
    } else {
      console.log('操作失败!' + resEquipments.data.msg);
    }
  } catch (error) {
    console.error('请求出错:', error);
  }
};

/* 列表加载与下拉刷新 */
const listActivities = ref([]);
const refreshingActivities = ref(false);
const loadingActivities = ref(false);
const finishedActivities = ref(false);

const listEquipments = ref([]);
const refreshingEquipments = ref(false);
const loadingEquipments = ref(false);
const finishedEquipments = ref(false);

const onLoadActivities = async () => {
  if (refreshingActivities.value) {
    listActivities.value = [];
    pageNumActivities.value = 1;
    refreshingActivities.value = false;
  }
  try {
    await queryFetchActivities();
    if (pageSizeActivities.value * pageNumActivities.value < totalActivities.value) {
      listActivities.value = [...listActivities.value, ...resultDataActivities.value];
      openStatesActivities.value = new Array(listActivities.value.length).fill(true);
      pageNumActivities.value++;
    } else {
      listActivities.value = [...listActivities.value, ...resultDataActivities.value];
      openStatesActivities.value = new Array(listActivities.value.length).fill(true);
      finishedActivities.value = true;
    }
  } catch (error) {
    console.log(error);
    finishedActivities.value = true;
  } finally {
    loadingActivities.value = false;
  }
};

const onLoadEquipments = async () => {
  if (refreshingEquipments.value) {
    listEquipments.value = [];
    pageNumEquipments.value = 1;
    refreshingEquipments.value = false;
  }
  try {
    await queryFetchEquipments();
    if (pageSizeActivities.value * pageNumEquipments.value < totalEquipments.value) {
      listEquipments.value = [...listEquipments.value, ...resultDataEquipments.value];
      openStatesEquipments.value = new Array(listEquipments.value.length).fill(true);
      pageNumEquipments.value++;
    } else {
      listEquipments.value = [...listEquipments.value, ...resultDataEquipments.value];
      openStatesEquipments.value = new Array(listEquipments.value.length).fill(true);
      finishedEquipments.value = true;
    }
  } catch (error) {
    console.log(error);
    finishedEquipments.value = true;
  } finally {
    loadingEquipments.value = false;
  }
};

/* 组织树选择 */
const showBottom = ref(false);
const currentDeptName = ref('');
const currentDeptCode = ref();
import OrganizationalWithLeaf from '@/components/OrganizationalWithLeaf.vue';
import { showFailToast, showSuccessToast } from 'vant';

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

const handleTableDataUserDeptUpdate = async (nodeData) => {
  // console.log('nodeData', nodeData);
  currentDeptCode.value = nodeData.split('-')[0];
  currentDeptName.value = nodeData.split('-')[1];
  if (active.value === 0) {
    onRefreshActivities();
  } else if (active.value === 1) {
    onRefreshEquipments();
  }
  showBottom.value = false;
};

const cachedDeptCode = ref('');
const getDeptInfo = (currentDeptInfo) => {
  currentDeptCode.value = currentDeptInfo.split('-')[0];
  currentDeptName.value = currentDeptInfo.split('-')[1];
  /* Pinia初始化属性 */
  if (emergencyInfo.currentDeptCode) {
    currentDeptCode.value = emergencyInfo.currentDeptCode;
    currentDeptName.value = emergencyInfo.currentDeptName;
    if (emergencyInfo.conditionalQueryAttributes) {
      const mark = emergencyInfo.conditionalQueryAttributes.split('-');
      active.value = Number(mark[0]);
      if (mark[0] === '0') {
        fetchDataActivities.value.inspectionCycle = mark[1];
      } else if (mark[0] === '1') {
        fetchDataEquipments.value.inspectionCycle = mark[1];
      }
    }
  }

  if (active.value === 0) {
    basicResetActivities();
    onLoadActivities();
  } else if (active.value === 1) {
    basicResetEquipments();
    onLoadEquipments();
  }
};

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

/**
 * 路由跳转前，pinia中缓存数据
 */
onBeforeRouteLeave((to, from, next) => {
  if (to.path === '/yinhuan/riskChecklistRecordsView') {
    if (active.value === 0) {
      emergencyInfo.$patch({
        currentDeptCode: currentDeptCode.value,
        currentDeptName: currentDeptName.value,
        conditionalQueryAttributes: '0-' + fetchDataActivities.value.inspectionCycle
      });
    } else if (active.value === 1) {
      emergencyInfo.$patch({
        currentDeptCode: currentDeptCode.value,
        currentDeptName: currentDeptName.value,
        conditionalQueryAttributes: '1-' + fetchDataEquipments.value.inspectionCycle
      });
    }
  } else {
    emergencyInfo.clearMainDeptInfo();
  }
  next();
});

const active = ref(0);
const onClickTab = (value) => {
  if (value.name === 1) {
    onRefreshEquipments();
  } else if (value.name === 0) {
    onRefreshActivities();
  }
};

const options1 = [
  { text: '全部', value: '' },
  { text: '天', value: '天' },
  { text: '周', value: '周' },
  { text: '月', value: '月' },
  { text: '季度', value: '季度' },
  { text: '年', value: '年' },
  { text: '不定期', value: '不定期' }
];

const jumpActivities = (item) => {
  sessionStorage.setItem('activityInfo', JSON.stringify(item));
  router.push('/yinhuan/riskChecklistRecordsView');
};

const jumpEquipments = (item) => {
  sessionStorage.setItem('equipmentInfo', JSON.stringify(item));
  router.push('/yinhuan/riskChecklistRecordsView');
};

const returnInspectionCycle = (inspectionCycle) => {
  if (!inspectionCycle) return '';
  if (inspectionCycle === '不定期') return '不定期';
  return '每' + inspectionCycle + '一次';
};

/**
 * 按钮实现swipe-cell滑动(作业活动)
 */
const openStatesActivities = ref([]);
const swipeCellRefsActivities = ref([]);
const getSwipeCellRefActivities = (el, index) => {
  if (el) {
    swipeCellRefsActivities.value[index] = el;
  }
};
const openSwipeActivities = (idx) => {
  openStatesActivities.value = new Array(listActivities.value.length).fill(true);
  if (idx >= 0 && idx < swipeCellRefsActivities.value.length) {
    openStatesActivities.value[idx] = false;
    swipeCellRefsActivities.value[idx].open('right');
  }
  document.addEventListener('click', handleDocumentClickActivities);
};
const closeSwipeActivities = (idx) => {
  if (idx >= 0 && idx < swipeCellRefsActivities.value.length) {
    openStatesActivities.value[idx] = true;
    swipeCellRefsActivities.value[idx].close();
  }
};
/** 滑动监听 **/
const handleSwipeOpenActivities = (idx) => {
  openStatesActivities.value[idx] = false;
};

const handleSwipeCloseActivities = (idx) => {
  openStatesActivities.value[idx] = true;
};

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

/**
 * 按钮实现swipe-cell滑动(设备设施)
 */
const openStatesEquipments = ref([]);
const swipeCellRefsEquipments = ref([]);
const getSwipeCellRefEquipments = (el, index) => {
  if (el) {
    swipeCellRefsEquipments.value[index] = el;
  }
};
const openSwipeEquipments = (idx) => {
  openStatesEquipments.value = new Array(listEquipments.value.length).fill(true);
  if (idx >= 0 && idx < swipeCellRefsEquipments.value.length) {
    openStatesEquipments.value[idx] = false;
    swipeCellRefsEquipments.value[idx].open('right');
  }
  document.addEventListener('click', handleDocumentClickEquipments);
};
const closeSwipeEquipments = (idx) => {
  if (idx >= 0 && idx < swipeCellRefsEquipments.value.length) {
    openStatesEquipments.value[idx] = true;
    swipeCellRefsEquipments.value[idx].close();
  }
};
/** 滑动监听 **/
const handleSwipeOpenEquipments = (idx) => {
  openStatesEquipments.value[idx] = false;
};

const handleSwipeCloseEquipments = (idx) => {
  openStatesEquipments.value[idx] = true;
};

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

/**
 * 数据单个删除
 */
const showDialogVisible = ref(false);
const deleteInfo = ref();
/* 准备删除 */
const handleDeleteActivities = (item, idx) => {
  openStatesActivities.value[idx] = !openStatesActivities.value[idx];
  showDialogVisible.value = true;
  deleteInfo.value = item;
};

const handleDeleteEquipment = (item, idx) => {
  openStatesEquipments.value[idx] = !openStatesEquipments.value[idx]
  showDialogVisible.value = true;
  deleteInfo.value = item;
};

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

</script>

<template>
  <div class="page-container">
    <van-sticky>
      <van-nav-bar title="风险隐患排查记录" />
      <van-field
        v-model="currentDeptName"
        label="当前组织"
        placeholder="请选择组织架构"
        readonly
        right-icon="arrow-down"
        @click="showPickerHandle()"
      />
    </van-sticky>

    <van-tabs v-model:active="active" @click-tab="onClickTab">
      <van-tab title="作业活动">
        <van-dropdown-menu>
          <van-dropdown-item v-model="fetchDataActivities.inspectionCycle" :options="options1"
                             @change="onRefreshActivities" />
        </van-dropdown-menu>
        <div class="scroll-container">
          <van-pull-refresh
            v-model="refreshingActivities"
            success-text="刷新成功"
            @refresh="onRefreshActivities"
          >
            <van-list
              class="listDiv"
              :immediate-check="false"
              v-model:loading="loadingActivities"
              :finished="finishedActivities"
              finished-text="没有更多了"
              @load="onLoadActivities"
            >
              <div v-for="(item, idx) in listActivities" :key="item.evaluationId">
                <van-swipe-cell
                  title-style="color: #007aff"
                  class="goods-card"
                  :ref="el => getSwipeCellRefActivities(el, idx)"
                  @open="handleSwipeOpenActivities(idx)"
                  @close="handleSwipeCloseActivities(idx)"
                >
                  <template #default>
                    <div class="swipe-cell-default">
                      <van-cell @click="jumpActivities(item)">
                        <template #title>
                          <span class="bold-title" style="margin-right: 10px">{{ item.jobSteps }}</span>
                        </template>
                        <template #label>
                          <div class="cell-label">
                            <span>所属风险点：{{ item.activityName }}</span>
                            <span>作业频次：{{ returnInspectionCycle(item.inspectionCycle) }}</span>
                            <span>排查日期：{{ item.inspectionDate }}</span>
                          </div>
                        </template>
                      </van-cell>
                      <div class="swipe-cell-default-icon">
                        <van-icon v-if="openStatesActivities[idx]" name="arrow-double-left"
                                  @click.stop="openSwipeActivities(idx)" />
                        <van-icon v-else name="arrow-double-right" @click.stop="closeSwipeActivities(idx)" />
                      </div>
                    </div>
                  </template>
                  <template #right>
                    <van-button class="delete-button" square type="danger" text="删除"
                                @click="handleDeleteActivities(item,idx)" />
                  </template>
                </van-swipe-cell>
              </div>
            </van-list>
          </van-pull-refresh>
        </div>
      </van-tab>
      <van-tab title="设备设施">
        <van-dropdown-menu>
          <van-dropdown-item v-model="fetchDataEquipments.inspectionCycle" :options="options1"
                             @change="onRefreshEquipments" />
        </van-dropdown-menu>
        <div class="scroll-container">
          <van-pull-refresh
            v-model="refreshingEquipments"
            success-text="刷新成功"
            @refresh="onRefreshEquipments"
          >
            <van-list
              class="listDiv"
              :immediate-check="false"
              v-model:loading="loadingEquipments"
              :finished="finishedEquipments"
              finished-text="没有更多了"
              @load="onLoadEquipments"
            >
              <div v-for="(item,idx) in listEquipments" :key="item.evaluationId">
                <van-swipe-cell
                  title-style="color: #007aff"
                  class="goods-card"
                  :ref="el => getSwipeCellRefEquipments(el, idx)"
                  @open="handleSwipeOpenEquipments(idx)"
                  @close="handleSwipeCloseEquipments(idx)"
                >
                  <template #default>
                    <div class="swipe-cell-default">
                      <van-cell @click="jumpEquipments(item)">
                        <template #title>
                          <span class="bold-title" style="margin-right: 10px">{{ item.inspectItem }}</span>
                          <van-tag v-if="item.inspectionCycle !== '不定期'"
                                   :type="item.isChecked === '未排查' ? 'danger' : 'success'">{{ item.isChecked }}
                          </van-tag>
                        </template>
                        <template #label>
                          <div class="cell-label">
                            <span>所属风险点：{{ item.riskPointsName }}</span>
                            <span>作业频次：{{ returnInspectionCycle(item.inspectionCycle) }}</span>
                            <span>排查日期：{{ item.inspectionDate }}</span>
                          </div>
                        </template>
                      </van-cell>
                      <div class="swipe-cell-default-icon">
                        <van-icon v-if="openStatesEquipments[idx]" name="arrow-double-left" @click.stop="openSwipeEquipments(idx)" />
                        <van-icon v-else name="arrow-double-right" @click.stop="closeSwipeEquipments(idx)" />
                      </div>
                    </div>
                  </template>
                  <template #right>
                    <van-button class="delete-button" square type="danger" text="删除" @click="handleDeleteEquipment(item,idx)"/>
                  </template>
                </van-swipe-cell>
              </div>
            </van-list>
          </van-pull-refresh>
        </div>
      </van-tab>
    </van-tabs>

    <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; !* 启用垂直滚动 *!*/

.cell-label {
  display: flex;
  justify-content: space-between;
}

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

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

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

.goods-card {
  margin: 0;
}

.delete-button {
  height: 100%;
}

.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>
