<template>
  <div class="page-container">
    <van-sticky>
      <van-nav-bar
        title="事故报告台账"
        @click-left="onClickLeft" >
      </van-nav-bar>
    </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 in list" :key="item.id" class="card">
            <van-cell @click="handleLookRow(item)">
              <template #title>
                <span v-if="false" class="cell-title">{{ item.hdDescription }}</span>
              </template>
              <template #label>
                <div class="label-content">
                  <div>事故地点：{{ item.accidentLocation }}</div>
                  <div>发生时间：{{ item.accidentTime }}</div>
                  <div>事故类型：{{ item.accidentType }}</div>
                </div>
              </template>
            </van-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>
<script setup>
import { getCurrentInstance, onMounted, ref } from 'vue';
import { onBeforeRouteLeave, useRouter } from 'vue-router';
import { showConfirmDialog, showDialog, showFailToast, showSuccessToast } from 'vant';
import { useEmergencyStore } from '@/stores/emergencyManager.js';
const emergencyInfo =  useEmergencyStore()
const {
  proxy
} = getCurrentInstance()


/**
 * 组织树组件初始化返回方法
 * @param currentDeptInfo 用户部门信息(userCode-userName)
 */
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.regimeName = emergencyInfo.conditionalQueryAttributes
  }
  basicReset()
  onLoad()
}
/**
 * 数据传回组织树组件
 */
if (emergencyInfo.currentDeptCode) {
  cachedDeptCode.value = emergencyInfo.currentDeptCode
}

/**
 * 路由跳转前，pinia中缓存数据
 */
onBeforeRouteLeave((to, from, next) => {
  /* 跳转子页面赋值 */
  if (to.path === '/yinhuan/hdLedger_detail') {
    emergencyInfo.$patch({
      currentDeptCode: postBackRegimeScope.value.split('-')[0],
      currentDeptName: postBackRegimeScope.value.split('-')[1],
      conditionalQueryAttributes: fetchData.value.regimeName
    })
  } else {
    /* 跳转其他页面均清空，避免混乱赋值 */
    emergencyInfo.clearMainDeptInfo()
  }
  next()
})

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

/* 返回上一级页面 */
const router = useRouter()
const onClickLeft = () => {
  router.go(-1)
}

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

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

const resetCondition = () => {
  basicReset()
  fetchData.value = {
    regimeName:'',
    regimeScope: ''
  }
  onLoad()
}

/* 查询请求 */
const queryFetch = async () => {
  fetchData.value.regimeScope = postBackRegimeScope.value
  const url = '/sgsafe/AccidentReport/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 ]
      pageNum.value++;
    } else {
      list.value = [...list.value,...resultData.value ]
      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('你哦的Date',nodeData)
  currentDeptName.value = nodeData.split('-')[1]
  postBackRegimeScope.value = nodeData
  basicReset()
  await onLoad()
  showBottom.value = false
}

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) => {
  showDialogVisible.value = true
  deleteInfo.value = item
}

/* 数据删除 */
const onDelete = () => {
  const item = deleteInfo.value
  const url = '/safe/EmergencyDrillPlan/delete'
  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)
    }
  })
}

//点击详情跳转
const handleLookRow = (row) =>{
  proxy.$router.push({
    path: '/accidentManager/accidentBaoGaoLedger/accidentBaoGaoLedger_edit/index',
    query: {
      id:row.id,
      flag:'look'
    }
  })
}

//颜色事件
const getStatusClass = (status) => {
  switch (status) {
    case '-1':
      return 'status-pending';
    case '0':
      return 'status-registered';
    case '1':
      return 'status-analyzing';
    case '2':
      return 'status-rectifying';
    case '3':
      return 'status-accepting';
    case '4':
      return 'status-closed';
    case '5':
      return 'status-finished';
    default:
      return 'status-unknown';
  }
};

</script>

<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;
}

.card {
  margin: 10px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  background-color: #fff;
}
.label-content {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.cell-title {
  display: -webkit-box;                     /* 旧版弹性盒子模型 */
  -webkit-box-orient: vertical;             /* 内容垂直排列 */
  -webkit-line-clamp: 2;                    /* 限制显示行数 */
  overflow: hidden;                         /* 超出隐藏 */
  text-overflow: ellipsis;                  /* 省略号 */
  line-height: 1.5;                         /* 可选：设置行高 */
  max-height: calc(1.5em * 2);              /* 可选：根据行高限制最大高度 */
  font-size: 16px;
  font-weight: bold;
  color: #333;/* 字号 */
}


.status-pending {
  background-color: #fff3cd;
  color: #856404;
  padding: 2px 4px;
  border-radius: 4px;
}

.status-registered {
  background-color: #d1ecf1;
  color: #0c5460;
  padding: 2px 4px;
  border-radius: 4px;
}

.status-analyzing {
  background-color: #fff8e1;
  color: #ff8f00;
  padding: 2px 4px;
  border-radius: 4px;
}

.status-rectifying {
  background-color: #e8f5e9;
  color: #2e7d32;
  padding: 2px 4px;
  border-radius: 4px;
}

.status-accepting {
  background-color: #e3f2fd;
  color: #1565c0;
  padding: 2px 4px;
  border-radius: 4px;
}

.status-closed {
  background-color: #f8bbd0;
  color: #b71c1c;
  padding: 2px 4px;
  border-radius: 4px;
}

.status-finished {
  background-color: #e8eaf6;
  color: #311b92;
  padding: 2px 4px;
  border-radius: 4px;
}

.status-unknown {
  background-color: #efebe9;
  color: #424242;
  padding: 2px 4px;
  border-radius: 4px;
}


</style>
