<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/EvaluationOfEquipmentFacilities';
const activity_url = '/sgsafe/EvaluationOfActivityActivities';

/* 通用方法： 重置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({
  category: '周期性',
  inspectionCycle: '',
  responsibleUnitCode: ''
});

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

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

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

/* 查询请求 */
const queryFetchActivities = async () => {
  fetchDataActivities.value.responsibleUnitCode = currentDeptCode.value;
  let activitiesUrl = activity_url + '/queryActivitiesChecklist';
  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 + '/queryEquipmentsChecklist';
  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];
      pageNumActivities.value++;
    } else {
      listActivities.value = [...listActivities.value, ...resultDataActivities.value];
      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];
      pageNumEquipments.value++;
    } else {
      listEquipments.value = [...listEquipments.value, ...resultDataEquipments.value];
      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';

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) {
    basicResetActivities();
    await onLoadActivities();
  } else if (active.value === 1) {
    basicResetEquipments();
    await onLoadEquipments();
  }
  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/riskChecklistView') {
    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: '年' }
];

const options2 = [
  { text: '定期', value: '周期性' },
  { text: '不定期', value: '非周期性' }
];

const onSwitchRegularActivities = () => {
  fetchDataActivities.value.inspectionCycle = ''
  onRefreshActivities()
};

const onSwitchRegularEquipments = () => {
  fetchDataEquipments.value.inspectionCycle = ''
  onRefreshEquipments()
}

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

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

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

</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-item v-model="fetchDataActivities.category" :options="options2" @change="onSwitchRegularActivities" />
        </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 in listActivities" :key="item.evaluationId">
                <van-cell @click="jumpActivities(item)">
                  <template #title>
                    <span class="bold-title" style="margin-right: 10px">{{ item.jobSteps }}</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.activityName }}</span>
                      <span>作业频次：{{ returnInspectionCycle(item.inspectionCycle) }}</span>
                    </div>
                  </template>
                </van-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-item v-model="fetchDataEquipments.category" :options="options2" @change="onSwitchRegularEquipments" />
        </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 in listEquipments" :key="item.evaluationId">
                <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>
                    </div>
                  </template>
                </van-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>
  </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;
}
</style>
