<template>
  <div class="h5-container">
    <van-nav-bar title="任务项" @click-left="onClickLeft"
                 @click-right="handAdd">
      
    </van-nav-bar>

    <!-- 项目列表 -->
    <van-pull-refresh v-model="isRefreshing" success-text="刷新成功" @refresh="onRefresh">
      <van-list
        v-model:loading="isLoading"
        :finished="isFinished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <div v-for="item in resultData" :key="item.id" class="card">
            <van-cell
              :label="`检查类型: ${item.checkType}, 受检单位: ${item.checkedDept}
              , 类别: ${item.type}, 检查人: ${item.checkPersonName}, 检查时间: ${item.checkTime}, 项目: ${item.item}
              , 状态: ${item.state}`"
              @click="edits(item)"
            >
              <template #title>
                <span class="cell-title">{{ item.checkContent }}</span>
              </template>
              <template #label>
                <div class="label-content">
                  <div>项目：{{ item.item }}</div>
                  <div>状态：{{ item.state }}</div>
                </div>
              </template>
              <!-- 【已废弃】单条下发改为一键下发（safeCheckTask.vue 任务列表） -->
            </van-cell>
        </div>
      </van-list>
    </van-pull-refresh>


    <!-- 删除确认弹窗 -->
    <van-dialog
      v-model:show="deleteDialogVisible"
      title="删除确认"
      show-cancel-button
      @confirm="confirmDelete"
    >
      <div>确定要删除该项目吗？</div>
    </van-dialog>

    <!-- 【已废弃】原单条下发弹窗（hazardImmediatelyCM + 整改建议/时限/责任人），已改任务列表一键下发 copy_hazardImmediatelyCM + hdConfirm -->
  </div>
</template>

<script setup>
import { ref, onMounted, getCurrentInstance } from 'vue';
import { showToast } from 'vant';

const { proxy } = getCurrentInstance();

const onClickLeft = () => {
  history.back();
};
const headers = ref({
  token: localStorage.getItem('token'),
  userId: localStorage.getItem('userId'),
  dept: JSON.parse(localStorage.getItem('dept'))[0].deptCode
});
const query2 = ref({
  taskId: '',
  checkedDept: '',
  type: '',
  checkedDeptCode: '',
  checkContent: '',
})

onMounted(() => {
  
})

const tableData = ref([]);
const deleteDialogVisible = ref(false);
const currentDeleteItem = ref([]);

const kz = ref(true);
const handAdd = async () => {
  kz.value = false;
  resetForma();
  proxy.$router.push({
    path: '/safeCheck/safeCheckTaskEdit',
  })
};

const form = ref({
  taskTemplateId: '',
  checkType: '',
  checkedDept: '',
  notes: '',
  checkedDeptCode: '',
  checkThing: '',
  checkPerson:'',
  checkTime:'',
});
const resetForma = () => {
  form.value = {
    taskTemplateId: '',
    checkType: '',
    checkedDept: '',
    notes: '',
    checkedDeptCode: '',
    checkThing: '',
    checkPerson:'',
    checkTime:'',
  }
};

const isRefreshing = ref(false);
const isLoading = ref(false);
const isFinished = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const totalRows = ref(0);
const resultData = ref([]);

const getTableData = async () => {
  query2.value.userId = headers.value.userId
  query2.value.taskId = proxy.$route.query.id
  const url = 'sgsafe/CheckResultItem/query';
  const param = {
    page: currentPage.value,
    rows: pageSize.value,
    params: JSON.stringify(query2.value)
  };
  const response = await proxy.$axios.get(url, param)
  if (response.data.code === 0) {
    tableData.value = response.data.data.records;
    totalRows.value = response.data.data.total;
    tableData.value.forEach(item => {
      switch (item.status) {
        case '0':
          item.status = '隐患登记';
          break;
        case '1':
          item.status = '隐患分析确认';
          break;
        case '2':
          item.status = '隐患整改';
          break;
        case '3':
          item.status = '隐患验收';
          break;
        case '4':
          item.status = '隐患销号';
          break;
        case '5':
          item.status = '结束';
          break;
        case '-1':
          item.status = '待提交';
          break;
      }
    });
  } else {
    showToast({
      type: 'fail',
      message: '操作失败！' + response.data.msg
    });
  }
};

const onRefresh = () => {
  basicReset()
  onLoad();
};

const onLoad = async () => {
  if (isRefreshing.value) {
    resultData.value = [];
    currentPage.value = 1;
    isRefreshing.value = false;
  }
  try {
    await getTableData();
    if (pageSize.value * currentPage.value < totalRows.value) {
      resultData.value = [...resultData.value, ...tableData.value]
      currentPage.value++;
    } else {
      resultData.value = [...resultData.value, ...tableData.value]
      isFinished.value = true;
    }
  } catch (error) {
    console.log(error);
    isFinished.value = true;
  } finally {
    isLoading.value = false;
  }
};

const basicReset = () => {
  isFinished.value = false;
  isLoading.value = true;
  currentPage.value = 1
  resultData.value = []
}

const confirmDelete = () => {
  var url = '/sgsafe/CheckTask/remove';
  var param = {
    id: JSON.stringify(currentDeleteItem.value.map(x => x.id))
  };
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == 0) {
      showToast({
        type: 'success',
        message: '删除成功'
      });
      getTableData()
      deleteDialogVisible.value = false
      currentDeleteItem.value = []
    } else {
      showToast({
        type: 'fail',
        message: '操作失败！' + response.data.msg
      });
    }
  });
};

const edits = (row) => {
  kz.value = true;
  form.value = { ...row };
  proxy.$router.push({
    path: '/safeCheck/safeCheckTaskEdit',
    query: {
      id: form.value.id
    }
  });
};

</script>

<style scoped>
.h5-container {
  width: 100%;
  padding: 5px;
  box-sizing: border-box;
}

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