<template>
  <van-sticky>
    <van-nav-bar title="我的履职记录">
      <template #right>
        <van-icon
          name="add"
          size="24"
          color="var(--van-nav-bar-icon-color)"
          @click="toNewLog()"
        />
        <van-popover
          v-model:show="showPopover"
          :actions="actions"
          placement="bottom-end"
          @select="onSelect"
        >
          <template #reference>
            <van-icon name="filter-o" size="24px" />
          </template>
        </van-popover>
      </template>
    </van-nav-bar>
  </van-sticky>
  <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
    <van-list
      v-model:loading="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
      class="listDiv deep"
    >
      <van-swipe-cell v-for="(data,index) in datas" :key="data.id" right-width="60" >
        <template #right>
          <van-button
            @click="deleteLog(data)"
            square
            type="danger"
            style="height: 100%; line-height: inherit"
            >删除</van-button
          >
        </template>
        <van-cell class="card"
                  :label="`填写时间: ${data.addTime || '未知'} | 是否履职: ${data.resultWhether}`"
                  @click="toLog(data, index)">
          <template #title>
            <span class="bold-title">{{ data.resultDetail }}</span>
          </template>
        </van-cell>
      </van-swipe-cell>
    </van-list>
  </van-pull-refresh>
  <!-- </div> -->
  <van-back-top bottom="12vh" />
  <!-- <div>
    <van-popup
      v-model:show="showPopup"
      position="right"
      :style="{ width: '100%', height: '100%' }"
    >
      <DutyRecord
        :key="logKey"
        :file="fileControl"
        :rcd="currentLog"
        @update="nowLog"
        @close="closeLog"
      />
    </van-popup>
  </div> -->
</template>

<script setup>
import { ref, onMounted, reactive, getCurrentInstance } from 'vue';
const {
  proxy
} = getCurrentInstance()
import { useRouter, useRoute } from "vue-router";
import {
  TheDutyLog,
  DutyFileDetail,
  DeDutyLog,
  DeDutyLogRec,
} from "@/api/resumption";
import { showConfirmDialog, showSuccessToast } from 'vant';

import Toast from 'vant/es/toast';
import DutyRecord from "@/view/lvzhi/newDutyRecord.vue";
const route = useRoute();
const router = useRouter();
const isfinish = ref(false);
const pageNo = ref(1);
const pageSize = ref(10);
const loading = ref(false);
const finished = ref(false);
const refreshing = ref(false);

const resultLogId = route.query.id;
const fileControl = route.query.resType;
const fileWhether=route.query.fileWhether;
const resDetail=route.query.resDetail;
const showPopup = ref(false);
const logKey = ref(0);
const datas = ref([]);
const addLog = ref(false);
// const lvzhiLog = reactive({
//   // id:"",
//   userId: localStorage.getItem("userId"),
//   userName: localStorage.getItem("userName"),
//   jobResult: "",
//   resultLogId: resultLogId,
// });
const currentLog = reactive({});
const showPopover = ref(false);
const actions = [
  { text: "显示当前记录", value: 0 },
  { text: "查询全部记录", value: 1 },
];
const QueryJieguo=ref({
  resultWhether:'',
  startTime:'',
  endTime:'',
  qingdanId:'',
  resType:'',
  queryAll:'0'

})
const onSelect = async (action) => {
  QueryJieguo.value.queryAll = action.value;

  refreshing.value = true;
  await onRefresh();
};


const onLoad = async () => {
  if (refreshing.value) {
    datas.value.length = 0;
    pageNo.value = 1;
    refreshing.value = false;
  }


  const tableData = ref([]);
  const totalRows = ref(0)
  onMounted(() => {
    queryFetch();
  });
  const queryFetch = async () => {
    QueryJieguo.value.qingdanId = resultLogId
    QueryJieguo.value.resType = fileControl;

    const url = '/sgsafe/ItemsResult/query1';
    const param = {
      page: pageNo.value,
      rows: pageSize.value,
      params: JSON.stringify(QueryJieguo.value)
    };

    try {
      const res = await proxy.$axios.post(url, param);
      if (res.data.code === 0) {
        totalRows.value = res.data.data.total;
        tableData.value = res.data.data.records;
      } else {
        console.log('操作失败!' + res.data.msg);
      }
    } catch (error) {
      console.error('请求出错:', error);
    }
  };



  try {

    await  queryFetch();
    const data = tableData.value;
    console.log(data);
    if (pageSize.value * pageNo.value < totalRows.value) {
      datas.value.push(...data);
      pageNo.value++;
    } else {
      datas.value.push(...data);
      finished.value = true;
    }
    loading.value = false;
  } catch (error) {

    console.log(error);
    finished.value = true;
  } finally {
    loading.value = false;
  }
};
const onRefresh = async () => {
  finished.value = false;
  loading.value = true;
  onLoad();
};

// 打开已有
const toLog = (data, index) => {
  console.log(data);
  // logKey.value = Math.random();
  // Object.keys(currentLog).forEach((key) => {
  //   currentLog[key] = undefined;
  // });
  // Object.assign(currentLog, data);
  // showPopup.value = true;
  console.log("进入已有记录子页面的index", index)
  router.push({
    path:"/lz-rcd-detail",
    query:{
      data:JSON.stringify(data),
      fileWhether:fileWhether,
      isnew:index,
      resDetail:resDetail
    }
  })
};
const generateSecureRandomString = (length) => {
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  const charactersLength = characters.length;
  const array = new Uint32Array(length);
  window.crypto.getRandomValues(array);

  let result = '';
  for (let i = 0; i < length; i++) {
    result += characters[array[i] % charactersLength];
  }

  return result;
};
// 打开新增
const toNewLog = () => {
  // logKey.value = Math.random();
  // Object.keys(currentLog).forEach((key) => {
  //   currentLog[key] = undefined;
  // });
  // // 这里会导致发送给子组件的对象中有一些属性为undefined
  // Object.assign(currentLog, lvzhiLog);
  // showPopup.value = true;
    router.push({
    path:"/lz-rcd-detail",
    query:{
      result :generateSecureRandomString(10),
      itemsId:resultLogId,
      fileWhether:fileWhether,
      isnew:"-1",
      resDetail:resDetail
    }
  })
};
const nowLog = () => {
  showPopup.value = false;
  // fetchdataList();
  datas.value.length = 0;
  onLoad();
};
// const closeLog = () => {
//   showPopup.value = false;
// };
const  dataLog= ref({});

async function deleteLog(data) {
  console.log(data);
  dataLog.value=data
  showConfirmDialog({
    message: "确认要删除该我的履职记录结果列表吗？",
  })
    .then(async () => {
      dataLog.value.cancelFlag='1'
      var url = '/sgsafe/ItemsResult/delectByEnt';
      var param = {
        json: JSON.stringify(dataLog.value)
      };
      proxy.$axios.post(url, param).then(response => {
        if (response.data.code == '0') {

          showSuccessToast('删除成功')
          datas.value.length = 0;
          onRefresh();
        } else {
          showFailToast(response.data.msg)
        }
      })
    })
    .catch(() => {
      // console.log('用户取消操作');
    });
}

</script>

<style scoped>
.data-list {
  padding: 16px;
}
.deep ::v-deep .van-cell__value {
  flex: 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; /* 内容垂直居中 */
}
.bold-title {
  font-weight: bold;

  color: #333;
}
</style>
