<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()

/* 通用方法： 重置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({
  tempName:'',
  yearValue:'',
  userId:'',
  deptCode:'',
  addName:'',
})

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

const resetCondition = () => {
  basicReset()
  fetchData.value = {
    tempName:'',
    yearValue:'',
    userId:'',
    deptCode:'',
    addName:'',
  }
  onLoad()
}

/* 查询请求 */
const queryFetch = async () => {
  fetchData.value.deptCode = postBackRegimeScope.value
  console.log(fetchData.value);
  const url = '/sgsafe/RecordMaster/queryByDeptNew'
  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("++++++++++++++++++++++++");
  console.log(nodeData);
  currentDeptName.value = nodeData.split('-')[1]
  postBackRegimeScope.value = nodeData.split('-')[0]
  basicReset()
  await onLoad()
  showBottom.value = false
}

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

const goToLvzhi = (id) => {

  router.push({ path: "/lz-rcdcx", query: { id: id} });
};
const cachedDeptCode = ref('')
/**
 * 数据传回组织树组件
 */
if (emergencyInfo.currentDeptCode) {
  cachedDeptCode.value = emergencyInfo.currentDeptCode
}
const getDeptInfo = (currentDeptInfo) => {
  console.log("++++++++++++++++++++++++21");
  console.log(currentDeptInfo.split('-')[0]);
  postBackRegimeScope.value = currentDeptInfo.split('-')[0]
  currentDeptName.value = currentDeptInfo.split('-')[1]
  /* Pinia初始化属性 */
  if (emergencyInfo.currentDeptCode) {
    postBackRegimeScope.value = emergencyInfo.currentDeptCode + '-' + emergencyInfo.currentDeptName
    currentDeptName.value = emergencyInfo.currentDeptName
    console.log(currentDeptName.value);
    //fetchData.value.resourceName = emergencyInfo.conditionalQueryAttributes
  }
  basicReset()
  onLoad()
}
const colorMap = {
  '1': "rgba(0, 128, 0, 0.7)", // 状态 1 对应绿色
  '2': "rgba(255, 0, 0, 0.7)",
};

const getContentState = (state) => {
  const contentMap = {
    '1': '未审验',
    '2': '待审验',
    '3': '已审验'
  }

  return contentMap[state] || ''
}
const getTagType = (state) => {
  const typeMap = {
    '1': 'danger',
    '2': 'warning',
    '3': 'success'
  };
  return typeMap[state] || ''
}

</script>

<template>
  <div class="page-container">
    <van-sticky>
      <van-nav-bar
        title="履职记录查询"
        left-text="返回"
        left-arrow
        @click-left="onClickLeft" />

      <van-search
        v-model="fetchData.addName"
        @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"
        >
          <van-cell class="card"
            v-for="item in list"
            :key="item.id"
            border
            @click="goToLvzhi(item.id, )"
          >
<!--            <template #label>
              <span>实际得分：{{ item.grossScore }}  | 岗位：{{item.post}}</span>

            </template>-->
            <template #default>
              <div class="row-container">
                <!-- 左侧周期 -->
                <div class="cell-period-text">
                  <span>实际得分：{{ item.grossScore }}  | 岗位：{{item.post}}</span>
                </div>

                <!-- 右侧按钮 -->
                <van-button
                  class="mini-btn"
                  :type="item.state == 1 ? 'success' : item.state == 2 ? 'warning' : 'primary'"
                  size="mini"
                >
                  {{ item.state == 1 ? '已完成' :  '未完成'}}
                </van-button>
              </div>
            </template>
            <template #title>
              <div class="cell-title">{{ item.addName }}</div>

            </template>
          </van-cell>

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

.card {
  margin: 10px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  background-color: #fff;

  /* 固定卡片大小 */
  width: 100%;             /* 或具体值如 300px */
  min-width: 300px;        /* 最小宽度 */
  height: 110px;           /* 固定高度 */
  display: flex;
  flex-direction: column;
  justify-content: center; /* 内容垂直居中 */
}
.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;/* 字号 */
}
.row-container {
  display: flex;
  justify-content: space-between; /* 关键：左右分布 */
  align-items: center;             /* 垂直居中 */

}

.cell-period-text {
  font-size: 14px;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;

}

.mini-btn {
  height: 22px;
  font-size: 12px;
  padding: 0 8px;
  min-width: 60px;                 /* 可选：保持按钮最小宽度一致 */
}
</style>
