<template>
  <div>
    <van-sticky>
      <van-nav-bar :border="false">
        <!-- 全部履职 -->
        <template #left>
          <div
            @click="setActiveTab('all')"
            :class="['tab-item', { active: activeTab === 'all' }]"
          >
            全部履职
          </div>
        </template>

        <!-- 标题 -->
        <template #title>
          <span class="title">我的履职记录</span>
        </template>

        <!-- 待履职 -->
        <template #right>
          <div
            @click="setActiveTab('pending')"
            :class="['tab-item', { active: activeTab === 'pending' }]"
          >
            待履职
          </div>
        </template>
      </van-nav-bar>

<!--      <van-nav-bar title="我的履职记录">
        <template #right>
         <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-search
        v-model="searchKey"
        @search="dutySearch"
        @clear="searchClear"
        placeholder="请输入搜索关键词"
      />
    </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-cell class="card"
          v-for="data in datas"
          :key="data.id"
          border
          @click="goToLvzhi(data.id, data.resType,data.fileWhether,data.resDetail)"
        >
          <template #default>
            <div class="row-container">
              <!-- 左侧周期 -->
              <div class="cell-period-text">
                周期: {{ formatResType(data.resType, data.targetTimes) }}
              </div>

              <!-- 右侧按钮 -->
              <van-button
                class="mini-btn"
                :type="
    data?.targetTimes == 0
      ? 'info'
      : data?.state == 1
        ? 'success'
        : data?.state == 2
          ? 'warning'
          : 'primary'
  "
                size="mini"
              >
                {{
                  data?.targetTimes == 0
                    ? '不定期'
                    : data?.state == 1
                      ? '已履职'
                      : '待履职'
                }}
              </van-button>
            </div>
          </template>
          <!-- 自定义标题 -->
          <template #title>
            <div class="cell-title">{{ data.resDetail }}</div>
          </template>
        </van-cell>
      </van-list>
    </van-pull-refresh>
    <van-back-top bottom="12vh" />
  </div>
</template>

<script setup>
import { onMounted, ref, reactive, computed, getCurrentInstance } from 'vue';
import { useRouter, useRoute } from "vue-router";
import { MyDutyList, DeDutyLog, DeDutyLogRec } from "@/api/resumption";
import "@/assets/custom.less";
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 datas = ref([]);
const searchKey = ref("");
const {
  proxy
} = getCurrentInstance()

const query = ref({
  resTitle:'',
  resDetail:'',
  resStandard:'',
  userId:''
})

const setActiveTab = (tab) => {
  activeTab.value = tab;
  onTabChange(tab);
};
const activeTab = ref('pending');
const onTabChange  = async(name) => {
  console.log('当前页签:', name);
  activeTab.value=name;
  refreshing.value = true;
  await onRefresh();
  // 这里可以添加根据 tab 切换加载数据的逻辑
};
// const colorMap = ['red', 'yellow', 'green']; //1.是已完成，2是未完成
// 定义 colorMap，明确指定状态与其对应的颜色
const colorMap = {
  '1': "rgba(0, 128, 0, 0.7)", // 状态 1 对应绿色
  '2': "rgba(255, 0, 0, 0.7)",
};
const goLastYear = ref(0);
const showPopover = ref(false);
// 通过 actions 属性来定义菜单选项
const actions = [
  { text: "查询全部履职", value: 1 },
  { text: "查询未履职", value: 0 },
];
const formatResType = (resType,targetTime) => {
  switch (resType) {
    case '违章扣分':
      return '违章扣分';
    case '日常类':
      return '每日'+targetTime+'次';
    case '周类型':
      return '每周'+targetTime+'次';
    case '月类型':
      return '每月'+targetTime+'次';
    case '季度类':
      return '每季度'+targetTime+'次';
    case '半年类':
      return '半年'+targetTime+'次';
    case '年度类':
      return '每年'+targetTime+'次';
    default:
      return '不定期';
  }
};
const onSelect = async (action) => {
  goLastYear.value = action.value;
  refreshing.value = true;
  await onRefresh();
};
const goToLvzhi = (id, fileNumber,fileWhether,resDetail) => {

  router.push({ path: "/lz-rcd", query: { id: id, resType: fileNumber,fileWhether:fileWhether,resDetail: resDetail } });
};
const onLoad = async () => {

  if (refreshing.value) {
    datas.value.length = 0;
    pageNo.value = 1;
    refreshing.value = false;
  }
  const queryFetch = async () => {
    query.value.resTitle = searchKey.value;
    query.value.userId = userId;

    const url = '/sgsafe/RecordItems/queryNew';
    const param = {
      page: pageNo.value,
      rows: pageSize.value,
      params: JSON.stringify(query.value)
    };

    try {
      const res = await proxy.$axios.post(url, param); // 等待 axios 请求完成
      if (res.data.code === 0) {
        if (activeTab.value === 'pending') {
          const records = res.data.data.records;
          const filtered = records.filter(item => item.state == '2');
          tableData.value = filtered;
          totalRows.value =  res.data.data.total;
        }else {
          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 res=     await queryFetch()

  //  const res = await MyDutyList(params);

    const data = tableData.value;
    console.log(tableData.value);
    console.log(totalRows.value);
    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  userId=localStorage.getItem('userId');

const tableData = ref([]);
const totalRows = ref(0)


const onRefresh = async () => {
  finished.value = false;
  loading.value = true;
  onLoad();
};
async function dutyDelete(id) {
  showConfirmDialog({
    message: "确认要删除该履职记录结果吗？",
  })
    .then(async () => {
      // console.log('用户确认操作');
      const res = await DeDutyLogRec(id);
      if (res.code === 200) {
        showToast("删除成功");
        datas.value.length = 0;
        onRefresh();
      } else {
        showFailToast(res.message);
      }
    })
    .catch(() => {
      // console.log('用户取消操作');
    });
}
async function dutySearch() {
  datas.value.length = 0;

  onRefresh();
}
async function searchClear() {
  datas.value.length = 0;

  onRefresh();
}



</script>

<style lang="less" 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; /* 内容垂直居中 */
}
.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;                 /* 可选：保持按钮最小宽度一致 */
}
.tab-item {
  font-size: 14px;
  padding: 8px 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  border-bottom: 2px solid transparent;
  color: #666;
}

/* 选中时的样式 */
.tab-item.active {
  color: #1989fa; /* Vant 主色调 */
  font-weight: bold;
  border-bottom-color: #1989fa;
}
</style>
