<template>
  <basic-container class="list">
    <div class="flexBetween">
      <div class="flex">
        <el-select
          v-model="value"
          filterable
          style="width: 300px"
          placeholder="请选择项目"
          clearable
          @change="projectChange"
        >
          <el-option
            v-for="item in options"
            :key="item.id"
            :label="item.projectName"
            :value="item.id"
          >
          </el-option>
        </el-select>
        <el-select
          v-model="certificateTypeValue"
          filterable
          style="width: 300px"
          placeholder="请选择证书类型"
          clearable
          @change="typeChange"
        >
          <el-option label="个人证书" :value="1"> </el-option>
          <el-option label="企业证书" :value="2"> </el-option>
        </el-select>
        <div class="header-box-center">
          <el-input
            v-model="searchinput"
            style="width: 240px; margin-right: 10px"
            placeholder="请输入"
            clearable
            @clear="searchClick"
          />
          <el-button type="primary" class="el-icon-search" @click="searchClick"
            >搜索</el-button
          >
        </div>
      </div>

      <el-button
        type="primary"
        size="mini"
        class="el-icon-plus"
        @click="pushRouter(0)"
        >新增</el-button
      >
    </div>

    <el-table
      class="martop20 tableList"
      :data="tableData"
      header-color="red"
      style="width: 100%"
    >
      <el-table-column type="index" label="序号" width="180"> </el-table-column>
      <el-table-column prop="certificateUserName" label="证书所有者">
      </el-table-column>
      <el-table-column prop="certificateId" label="证书ID/企业统一社会信用代码">
      </el-table-column>
      <el-table-column prop="certificateType" label="证书类型">
        <template slot-scope="scope">
          <span v-if="scope.row.certificateType == 1">个人证书</span>
          <span v-else>企业证书</span>
        </template>
      </el-table-column>
      <el-table-column prop="isRegister" label="注册">
        <template slot-scope="scope">
          <el-button
            type="text"
            v-if="scope.row.isRegister == 0"
            @click="register(scope.row.id)"
            >注册</el-button
          >
          <el-button type="text" v-else disabled>已注册</el-button>
        </template>
      </el-table-column>
      <el-table-column prop="address" label="操作">
        <template slot-scope="scope">
          <el-button type="text" @click="pushRouter(scope.row.id)"
            >编辑</el-button
          >
          <el-button
            type="text"
            @click="deleteList(scope.row.id)"
            style="color: rgba(240, 99, 10, 1)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      style="float: right"
      background
      class="martop20 marbottom20"
      layout="prev, pager, next"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageindex"
      :page-size="pagesize"
    >
    </el-pagination>
  </basic-container>
</template>

<script>
import {
  queryProjectList,
  listpage,
  goRegister,
  remove,
} from "@/api/certificate/list";

export default {
  data() {
    return {
      searchinput: "",
      value: "",
      options: [],
      tableData: [],
      total: 0,
      pageindex: 1,
      pagesize: 20,
      certificateTypeValue: null, //证书类型
      nextId: null,

    };
  },
  watch: {
    // 监听路由变化，当从其他页面返回时更新状态
    '$route.query': {
      immediate: true,
      handler(newQuery) {
        if (newQuery.pageindex) {
          this.pageindex = Number(newQuery.pageindex);
        }
        if (newQuery.value) {
          this.value = newQuery.value;
        }
    
        if (newQuery.pagesize) {
          this.pagesize = Number(newQuery.pagesize);
        }
      }
    },
    searchinput: {
      immediate: true,
      handler(newQuery) {
        if (newQuery) {
          this.pageindex = 1;
          this.pagesize=20

        }
      }
    }
  },
  methods: {
    //#region 页码
    handleSizeChange(val) {
      this.pagesize = val;
      this.listpage();
    },
    handleCurrentChange(val) {
      this.pageindex = val;
      this.listpage();
    },
    typeChange() {
      this.pageindex = 1;
      this.pagesize = 20;
      this.listpage();
    },
    //#endregion

    //#region 头接口
   // 修改pushRouter方法，传递完整的查询状态
  // 在列表页的pushRouter方法中修改下一条ID的计算方式
pushRouter(id) {
  // 找到当前行在表格数据中的索引
  const currentIndex = this.tableData.findIndex(row => row.id === id);
  // 获取下一行数据的id（如果存在）
  let nextId = null;
  
  // 如果是最后一条记录，查询下一页的第一条
  if (currentIndex === this.tableData.length - 1) {
    // 检查是否有下一页
    if (this.pageindex * this.pagesize < this.total) {
      // 这里只是标记需要加载下一页，实际数据在编辑页处理
      nextId = 'nextPage';
    }
  } else {
    // 正常获取下一条
    const nextRow = this.tableData[currentIndex + 1];
    nextId = nextRow ? nextRow.id : null;
  }
  
  this.$router.push({
    path: "/certificate/list/addList",
    query: {
      id,
      value: this.value,
      certificateTypeValue: this.certificateTypeValue,
      searchinput: this.searchinput,
      pageindex: this.pageindex,
      pagesize: this.pagesize,
      nextId: nextId
    }
  });
},
    //#endregion

    //#region 列表接口
    projectChange() {
           this.pageindex = 1;
      this.pagesize = 20;
      //下拉框change事件
      this.listpage();
    },
    register(id) {
      //注册按钮
      this.goRegister(id);
    },
    deleteList(ids) {
      //删除按钮
      let _that = this;
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          _that.remove({ ids });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    async remove(ids) {
      const { data: res } = await remove(ids);
      console.log(res);
      if (res.code == 200) {
        this.$message({
          type: "success",
          message: "删除证书成功!",
        });
        this.listpage();
      }
    },
   async queryProjectList() {
  const { data: res } = await queryProjectList();
  if (res.code == 200) {
    this.options = res.data;
    // 处理路由参数
    if (this.$route.query.value) {
      this.value = this.$route.query.value;
      // 确保页码是数字类型
      this.pageindex = Number(this.$route.query.pageindex) || 1;
      this.pagesize = Number(this.$route.query.pagesize) || 20;
      this.certificateTypeValue = this.$route.query.certificateTypeValue 
        ? Number(this.$route.query.certificateTypeValue) 
        : null;
      this.searchinput = this.$route.query.searchinput || '';
    } else {
      this.value = this.options[0].id || '';
    }
    this.$nextTick(() => {
      this.listpage();
    });
  }
},

    async listpage() {
      //分页获取证书列表数据
      const { data: res } = await listpage({
        current: this.pageindex,
        size: this.pagesize,
        projectId: this.value,
        certificateUserName: this.searchinput,
        certificateType: this.certificateTypeValue,
      });

      if (res.code == 200) {
        this.tableData = res.data.records;
        this.total = res.data.total;
      }
    },
    async goRegister(id) {
      //注册
      const { data: res } = await goRegister({ key: id });
      console.log(res);
      if (res.code == 200) {
        this.$message({
          type: "success",
          message: "证书注册成功!",
        });
        this.listpage();
      }
    },
    searchClick() {
      this.listpage();
    },
    //#endregion
  },
  created() {
    this.queryProjectList();
  },
};
</script>

<style lang="scss" scoped>
.tableList {
  ::v-deep th.el-table__cell {
    font-size: 16px !important;
  }
}
.header-box-center {
  margin-left: 40px;
}
</style>
