<template>
  <div class="page-container">
    <van-sticky style="padding: 5px 10px 5px 10px;background-color: white;">
      <van-nav-bar title="项目作业台账" @click-right="handleAdd">
        
      </van-nav-bar>
      <van-field
        v-model="currentDeptName"
        label="当前组织"
        placeholder="请选择组织架构"
        readonly
        right-icon="arrow-down"
        @click="showPickerHandle()"
      />
    </van-sticky>
    
    <van-search
      v-model="fetchData.projectName"
      show-action
      placeholder="请输入项目名称"
      @search="onRefresh"
      @cancel="handdelect"
      style="padding: 5px 10px; box-sizing: border-box;"
    />
    
    <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"
        >
          <!-- 列表项：添加 disabled 禁用滑动，移除滑动相关事件和图标 -->
          <div v-for="(item, idx) in list" :key="item.id" class="list-item-wrapper">
            <van-swipe-cell
              title-style="color: #007aff"
              style="height: 110px;"
              disabled
            >
            <template #default>
              <div class="swipe-cell__content">
                <van-cell
                  style="height: 100%; padding: 10px 0; display: flex; align-items: center;"
                  @click="handleLookRow(item)"
                >
                  <template #title>
                    <div class="cell__title">
                      {{ item.projectName }}
                    </div>
                  </template>
                  <template #label>
                    <div class="cell__label">
                      <div>作业开始时间：{{ item.timeStart || '未设置' }}</div>
                      <div>作业负责人：{{ item.addName || '未知' }}</div>
                      <div style="color: black;">状态：<span :class="getStatusClass(item.workStatus)">{{ item.workStatus || '未定义' }}</span></div>
                    </div>
                  </template>
                </van-cell>
                <!-- 移除滑动触发箭头图标 -->
              </div>
            </template>

            <template #right>
              <van-button
                style="height:100%; width: 80px;"
                type="warning"
                square
                text="编辑"
                @click="handleEdit(item, idx)"
              />
              <van-button
                style="height:100%; width: 80px;"
                type="danger"
                square
                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>
<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: '',
  projectName: '',
})

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

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

/* 查询请求 */
const queryFetch = async () => {
  fetchData.value.regimeScope = postBackRegimeScope.value
  const url = '/sgsafe/ProjectWork/queryLedger'
  const param = {
    page: pageNum.value,
    rows: pageSize.value,
    params: JSON.stringify({
      projectName: fetchData.value.projectName,
      deptCode: JSON.parse(localStorage.getItem('dept'))[0].deptCode,
      regimeScope: fetchData.value.regimeScope
    })
  }
  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, idx) => {
  showDialogVisible.value = true
  deleteInfo.value = item.id
}

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

//点击详情跳转
const form = ref(null)
const handleLookRow = (row) => {
  
  form.value = { ...row };
  if (row.workId) {
    sessionStorage.setItem('workflowQuery', JSON.stringify({
      flowId: row.flowId,
      workId: row.workId,
      trackId: row.trackId,
      type: '1',
      date: new Date().getTime()
    }));
    proxy.$router.push({
      path: '/projectManage/todo_detail/index',
      query: {
        tySignature: false
      }
    });
  }else {
    proxy.$router.push({
      path: '/projectManage/projectConstructionOperation/projectConstructionOperation_detail3',
      query: {
        id: form.value.id
      }
    });
  }
}
const handleEdit = (row) => {
  form.value = { ...row };
  proxy.$router.push({
    name: 'taiZhang_indexEdit',
    query: {
      id: form.value.id,
    },
  })
}

//颜色事件
const getStatusClass = (status) => {
  switch (status) {
    case '作业起草':
      return 'text-start';
    case '作业中':
      return 'text-middle';
    case '作业结束':
      return 'text-end';
    case '2':
      return 'status-rectifying';
    case '3':
      return 'status-accepting';
    case '4':
      return 'status-closed';
    case '5':
      return 'status-finished';
    default:
      return 'status-unknown';
  }
};

//重置搜索框
const handdelect = () => {
  fetchData.value.projectName = '';
  onRefresh()
};

//新增
const handleAdd = () => {
  proxy.$router.push({
    path: '/projectManage/taiZhang_edit',
    query: {}
  });
}

/* 移除所有滑动相关逻辑（已禁用滑动，这些代码无用） */
</script>

<style scoped>
.page-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.scroll-container {
  overflow: auto;
  -webkit-overflow-scrolling: touch;
  padding-bottom: 10px;
}

.scroll-container::-webkit-scrollbar {
  display: none;
}

/* 列表项外层容器 */
.list-item-wrapper {
  margin: 0 10px 8px;
}

/* 滑动单元格内容区 */
.swipe-cell__content {
  display: flex;
  align-items: center;
  width: 100%;
  padding-left: 15px;
  background-color: #fff;
}

/* 标题样式 */
.cell__title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 标签区样式（适配三行文本） */
.cell__label {
  font-size: 12px;
  color: #666;
  line-height: 1.3;
  display: flex;
  flex-direction: column;
  gap: 3px;
}

/* 状态标签样式 */
.status-pending, .status-registered, .status-analyzing,
.status-rectifying, .status-accepting, .status-closed,
.status-finished, .status-unknown {
  display: inline-block;
  padding: 1px 6px;
  border-radius: 4px;
  font-size: 11px;
  color: #fff !important;
  margin-left: 4px;
}

/* 各状态具体颜色 */
.status-pending { background-color: #ffc107; }
.status-registered { background-color: #17a2b8; }
.status-analyzing { background-color: #ff8f00; }
.status-rectifying { background-color: #28a745; }
.status-accepting { background-color: #007bff; }
.status-closed { background-color: #dc3545; }
.status-finished { background-color: #6c757d; }
.status-unknown { background-color: #999; }

/* 修复vant组件样式 */
:deep(.van-cell) {
  padding: 0;
  background-color: transparent;
  flex: 1;
}

:deep(.van-swipe-cell__wrapper) {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  height: 110px;
}

:deep(.van-swipe-cell__right) {
  display: flex;
}

/* 按钮样式 */
:deep(.van-button--warning) {
  background-color: #ff9700 !important;
  color: #fff !important;
}

:deep(.van-button--danger) {
  background-color: #ff4d4f !important;
  color: #fff !important;
}

.text-start {
  background-color: yellow;
  color: black;
}

.text-middle {
  background-color: green;
}

.text-end {
  background-color: #8d8989;
}

.status-wrapper {
  display: inline-block;
  padding: 2px 8px; /* 用padding替代固定height */
  border-radius: 4px;
  color: white;
  margin-top: 2px;
}
</style>