<template>
  <view class="jobInfo-container">
    <!-- 搜索框区域 -->
    <view class="search-box">
      <van-search
        :value="abc"
        placeholder="输入关键字查询"
        id="sreach"
        @clear="handleClear"
        @change="handleSearch"
      />
    </view>

    <!-- 列表区域 -->
    <view class="jobInfo-list">
      <scroll-view
        class="jobInfo-scroll"
        scroll-y
        @scrolltolower="loadNextPage"
        @refresherrefresh="onRefresh"
        refresher-enabled
        :refresher-triggered="isRefreshing"
      >
        <view
          class="jobInfo-item"
          v-for="item in jobInfoList"
          :key="item.id"
        >
          <view class="item-main" @click="handlejobInfoClick(item)">
            <view class="jobInfo-title">{{ item.title }}</view>
            <view class="jobInfo-time">汇报日期：{{ item.jobDate }}</view>
          </view>
          <view class="item-btns">
            <button class="btn-preview" @click.stop="btnView(item)">
              生成预览
            </button>
            <button class="btn-share" @click.stop="btnShare(item)">
              分享PDF
            </button>
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 加载更多状态组件 -->
    <uni-load-more :status="loadMoreStatus" />

    <!-- 新增按钮 -->
    <button class="add-btn" @click="handleAdd">新增</button>
  </view>
</template>

<script>
import { formatDate } from '@/utils/ruoyi.js'
import config from '@/config'
import { JobInfoApi } from '@/api/jobinfo/index.js'

export default {
  data() {
    return {
      isRefreshing: false, // 是否正在刷新
      searchValue: '', // 搜索关键字
      abc: '',
      jobInfoList: [], // 政策法规列表数据
      pageNum: 1, // 当前页码
      pageSize: 10, // 每页显示条数
      total: 0, // 总数据条数
      loadMoreStatus: 'more', // 加载更多状态：more-加载前 loading-加载中 noMore-没有更多
      itemImgUrl:
        config.imgUrl +
        '/miniohb/c103c92335bdd30d33ff8a062c219ead0626bf0a1898536bd7590285ca11c9db.png'
    }
  },
  // 页面加载时获取列表数据
  onShow() {
    console.log(this.itemImgUrl)
    this.getjobInfoList()
  },

  methods: {
    handleAdd() {
      uni.navigateTo({
        url: '/sub/owner/job-detail'
      })
    },
    btnView(itml) {
      console.log('查看', itml)
      let url = itml.pdfUrl
      // 示例代码
      wx.downloadFile({
        // 替换为你的PDF文件URL
        url: url,
        success: function (res) {
          const filePath = res.tempFilePath
          wx.openDocument({
            filePath: filePath,
            fileType: 'pdf', // 指定文件类型为PDF
            success: function (res) {
              console.log('打开文档成功')
            },
            fail: function (err) {
              console.error('打开文档失败', err)
            }
          })
        },
        fail: function (err) {
          console.error('下载文件失败', err)
        }
      })
    },

    btnShare(item) {
      let url = item.pdfUrl
      let fileName = item.title + '.pdf'
      // 示例代码
      wx.downloadFile({
        url: url, // 文件的下载链接
        success(res) {
          if (res.statusCode === 200) {
            wx.shareFileMessage({
              filePath: res.tempFilePath, // 下载后的文件临时路径
              fileName: fileName, // 可选，自定义文件名
              success() {
                console.log('文件分享成功')
              },
              fail(err) {
                console.error('文件分享失败', err)
              }
            })
          }
        },
        fail(err) {
          console.error('文件下载失败', err)
        }
      })
    },

    // 下拉刷新
    onRefresh() {
      this.isRefreshing = true
      this.pageNum = 1
      this.getjobInfoList()
    },
    loadNextPage() {
      console.log('列表值', this.jobInfoList.length)
      if (this.jobInfoList.length < this.total) {
        this.pageNum++
        this.getjobInfoList()
      }
    },
    // 获取政策法规列表数据
    async getjobInfoList() {
      try {
        console.log('jobInfoApi', JobInfoApi)
        this.loadMoreStatus = 'loading'
        const res = await JobInfoApi.getJobInfoPage({
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          title: this.searchValue // 搜索关键字
        })

        if (res.code === 0 && res.data.total > 0) {
          // 限制标题长度，超出显示省略号
          const formattedData = res.data.list.map(item => ({
            ...item,
            title:
              item.title.length > 15
                ? item.title.slice(0, 15) + '...'
                : item.title,
            jobDate: formatDate(item.jobDate, 'YYYY年MM月DD日')
          }))

          // 判断是首次加载还是加载更多
          if (this.pageNum === 1) {
            this.jobInfoList = formattedData
          } else {
            this.jobInfoList = [...this.jobInfoList, ...formattedData]
          }
          console.log('列表信息', res)
          this.total = res.data.total
          // 更新加载状态
          this.loadMoreStatus =
            this.jobInfoList.length >= this.total ? 'noMore' : 'more'
        }
      } catch (error) {
        console.error(error)
        this.loadMoreStatus = 'more'
        uni.showToast({
          title: '获取列表失败',
          icon: 'none'
        })
      } finally {
        this.loadMoreStatus =
          this.jobInfoList.length >= this.total ? 'noMore' : 'more'
        // 无论成功失败都关闭刷新状态
        // 确保在数据加载完成后关闭刷新状态
        setTimeout(() => {
          this.isRefreshing = false
        }, 300) // 添加短暂延时，确保动画效果完整
      }
    },
    // 搜索事件处理
    handleSearch(e) {
      if (e.detail && e.detail.length > 1) {
        this.pageNum = 1 // 重置页码
        this.searchValue = e.detail // 更新搜索关键字
        this.getjobInfoList()
      }
    },
    // 清除搜索事件处理
    handleClear() {
      this.pageNum = 1 // 重置页码
      this.searchValue = '' // 清空搜索关键字
      this.getjobInfoList()
    },
    // 点击政策条目跳转详情
    handlejobInfoClick(item) {
      uni.navigateTo({
        url: `/sub/owner/job-detail?id=${item.id}`
      })
    }
  }
}
</script>
<style lang="scss">
.jobInfo-container {
  background: #f9f9f9;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  padding-bottom: calc(88rpx + 68rpx); // 底部按钮高度 + 间距

  .search-box {
    padding: 24rpx;
    background: #ffffff;
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 1;
  }

  .jobInfo-list {
    flex: 1;
    margin-top: 120rpx; // 搜索框高度 + padding

    .jobInfo-scroll {
      height: calc(
        100vh - 120rpx - 156rpx
      ); // 视口高度 - 搜索框高度 - 底部按钮区域高度
      box-sizing: border-box;
    }

    .jobInfo-item {
      background: #ffffff;
      padding: 24rpx;
      margin: 24rpx;
      border-radius: 16rpx;

      .item-main {
        margin-bottom: 24rpx;
      }

      .jobInfo-title {
        font-size: 28rpx;
        color: #333333;
        line-height: 40rpx;
        margin-bottom: 8rpx;
      }

      .jobInfo-time {
        font-size: 24rpx;
        color: #999999;
        line-height: 34rpx;
      }

      .item-btns {
        display: flex;
        gap: 16rpx;

        button {
          flex: 1;
          height: 64rpx;
          line-height: 64rpx;
          text-align: center;
          font-size: 28rpx;
          border-radius: 8rpx;
          border: none;
        }

        .btn-preview {
          background: rgba(255, 111, 30, 0.1);
          color: #ff6f1e;
        }

        .btn-share {
          background: rgba(23, 198, 83, 0.1);
          color: #17c653;
        }
      }
    }
  }
}

.add-btn {
  position: fixed;
  bottom: 68rpx; // 修改为 34px = 68rpx
  left: 24rpx;
  right: 24rpx;
  height: 88rpx;
  line-height: 88rpx;
  background: #17c653;
  color: #ffffff;
  font-size: 32rpx;
  border-radius: 8rpx;
  text-align: center;
  border: none;
}

.search-box {
  padding: 24rpx;
  background: #ffffff;

  ::v-deep .van-search {
    padding: 0;
    background: transparent;

    .van-search__content {
      background: #f5f5f5;
      border-radius: 8rpx;
    }
  }
}
</style>
