<template>
  <view class="page-container">
    <view class="filter-bar">
      <picker class="filter-input" mode="date" :value="startDate" @change="handleStartDateChange">
        <view>{{ startDate || '起始日期' }}</view>
      </picker>
      <picker class="filter-input" mode="date" :value="endDate" @change="handleEndDateChange">
        <view>{{ endDate || '结束日期' }}</view>
      </picker>
      <button class="btn btn-primary search-btn" @click="handleQuery">查询</button>
    </view>

    <scroll-view scroll-y="true" class="page-body"  :style="{ height: scrollHeight + 'px' }" lower-threshold="150" @scrolltolower="handleLoadMore">
      <view class="scroll-content">
        <!-- 选择模式提示 -->
        <view class="tip-bar tip-bar-info" v-if="isSelectMode">
          <text>点击下方数据条目即可选择</text>
        </view>
        <view class="data-list">
          <view
            class="data-card"
            v-for="(item, index) in dataList"
            :key="index"
            @click="handleSelectItem(item)"
            :class="{ 'selectable': isSelectMode }"
          >
            <view class="data-card-text">
              <!-- <text>{{ item }}</text> -->
              <!-- 名称 -->
              <text>{{ item.fwmc }}</text>
              <!-- 代码 -->
              <text>{{ item.fwdm }}</text>
               <!-- 重量 单位 -->
               <text>{{ item.csl || item.rkl}}{{ item.jldw }}</text>
               <!-- 时间 -->
               <text>{{ item.cssj }}</text>
            </view>
            <!-- 选择模式下显示右侧箭头 -->
            <view class="select-arrow" v-if="isSelectMode">
              <uni-icons type="right" size="16" color="#cccccc"></uni-icons>
            </view>
          </view>
          <view class="no-data" v-if="dataList.length === 0 && !loading">
            <text>暂无数据</text>
          </view>
        </view>
        <uni-load-more :contentText="{contentdown: '显示更多'}" v-if="dataList.length > 0" :status="loadMoreStatus" @clickLoadMore="handleLoadMore" />
      </view>
    </scroll-view>
  </view>
</template>

<script>
import { api } from '@/api'
import { mapGetters } from 'vuex'
import { getDate } from '@/utils/common.js'
export default {
  computed: {
    ...mapGetters('user', ['enterpriseInfo']),
    loadMoreStatus() {
      if (this.loading) return 'loading'
      if (this.hasMore) return 'more'
      return 'noMore'
    }
  },
  data() {
    return {
      startDate: '',
      endDate: '',
      ledgerInfo: null,
      dataList: [],
      currentPage: 1,
      total: 0,
      hasMore: true,
      loading: false,
      scrollHeight: 0,
      /*手机高度*/
			phoneHeight: 0,
      /* 选择模式 */
      isSelectMode: false,
    }
  },
  onLoad(options) {
    if (options.item) {
      this.ledgerInfo = JSON.parse(decodeURIComponent(options.item))
      this.startDate = getDate()
      this.endDate = getDate()
    }
    // 选择模式：从库存调整等页面跳转过来，点击数据条目返回选中结果
    if (options.mode === 'select') {
      this.isSelectMode = true
      // 有台账类型时用其别名做标题，否则默认
      const title = this.ledgerInfo ? this.ledgerInfo.alias : '选择数据'
      uni.setNavigationBarTitle({ title })
      if (!options.item) {
        this.startDate = getDate()
        this.endDate = getDate()
      }
    } else if (options.item) {
      uni.setNavigationBarTitle({ title: this.ledgerInfo.alias })
    }
  },
  mounted() {
    this.init()
    this.loadData()
  },
  methods: {
    init() {
			let _this = this;
			uni.getSystemInfo({
				success(res) {
					_this.phoneHeight = res.windowHeight;
					// 计算组件的高度
					let view = uni.createSelectorQuery().select('.filter-bar');
					view.boundingClientRect(data => {
						let h = _this.phoneHeight - data.height;
						_this.scrollHeight = h;
					}).exec();
				}
			});
		},
    handleStartDateChange(e) {
      this.startDate = e.detail.value
    },
    handleEndDateChange(e) {
      this.endDate = e.detail.value
    },
    handleQuery() {
      if (!this.startDate && !this.endDate) {
        uni.showToast({ title: '请选择日期', icon: 'none' })
        return
      }
      this.currentPage = 1
      this.hasMore = true
      this.loadData(false)
    },
    loadData(isLoadMore = false) {
      if (this.loading) return
      if (isLoadMore && !this.hasMore) return
      this.loading = true
      api.ledgerList({
        lx: this.ledgerInfo ? this.ledgerInfo.lx : '',
        qyid: this.enterpriseInfo.enterpriseId,
        ksrq: this.startDate,
        jsrq: this.endDate,
        dqys: this.currentPage
      }).then(res => {
        console.log(res)
        const newList = res.data.list || []
        if (isLoadMore) {
          this.dataList = [...this.dataList, ...newList]
        } else {
          this.dataList = newList
        }
        this.total = res.data.total || 0
        this.hasMore = this.dataList.length < this.total 
      }).finally(() => {
        this.loading = false
      })
    },
    handleLoadMore() {
      if (this.loading || !this.hasMore) return
      this.currentPage += 1
      this.loadData(true)
    },
    /** 选择模式下点击数据条目，将数据回传给上一页 */
    handleSelectItem(item) {
      if (!this.isSelectMode) return
      const pages = getCurrentPages()
      const prevPage = pages[pages.length - 2]
      if (prevPage) {
        // 将选中项存入上一页，由上一页根据需要提取字段
        prevPage.$vm.selectedItem = item
        prevPage.$vm.isSelected = true
      }
      uni.navigateBack()
    },
    handleScan() { uni.showToast({ title: '扫码查询', icon: 'none' }) }
  }
}
</script>

<style lang="scss" scoped>
.scroll-content {
  // min-height: 100%;
}
.filter-btn {
  height: 40px;
  background: $primary-color;
  color: #ffffff;
  border: none;
  border-radius: $border-radius-sm;
  font-size: $font-size-sm;
}
.search-btn{
  width: 60px;
  height: 36px;
}

/* 选择模式下的卡片样式 */
.data-card {
  &.selectable {
    position: relative;
    transition: all 0.2s;
    &:active {
      background: $bg-primary;
      transform: scale(0.98);
    }
  }
}

.data-card-text{
  justify-content: space-between;
  display: flex;
}

/* 选择模式右侧箭头 */
.select-arrow {
  position: absolute;
  right: $spacing-md;
  top: 50%;
  transform: translateY(-50%);
}

.no-data{
  text-align: center;
  padding: $spacing-md 0;
}
</style>
