<template>
  <Water></Water>
  <view class="detail-page">
    <view class="tabs">
      <view class="tab" v-for="(t, i) in tabs" :key="t.label" :class="{ active: category == t.value }"
        :style="{ opacity: isLoading ? 0.5 : 1 }" @click="selectTab(t)">
        {{ t.label }}
      </view>
    </view>
    <view class="card" :style="{ height: tableBodyHeight + 'rpx' }">
      <scroll-view class="grid-scroll" scroll-y="true" scroll-x="true" :show-scrollbar="false" :style="{
        maxHeight: tableBodyHeight + 'rpx',
        opacity: category == 1 ? 1 : 0,
      }" enhanced @scrolltolower="onTableScrollToLower">
        <view :style="{
          width: '1180px',
        }">
          <view class="grid-header">
            <text class="hcell hcell-sticky-left">查询企业名称</text>
            <text class="hcell">出库方企业名称</text>
            <text class="hcell">产品名称</text>
            <text class="hcell">规格</text>
            <text class="hcell">批号</text>
            <text class="hcell">货源地区</text>
            <text class="hcell">货源数量</text>
            <text class="hcell">终端到达数量</text>
            <text class="hcell">出库时间</text>
            <text class="hcell">追溯码抽样</text>
          </view>
          <view v-if="!loading && rows.length > 0" class="grid-body">
            <view v-for="(row, idx) in rows" :key="idx + '-' + (row.produceBatchNo || '')" class="grow">
              <view v-if="row.flags.enterpriseName" class="gcell gcol-1 gspan" :class="['sticky-left']"
                :style="{ gridRowEnd: 'span ' + row.spans.enterpriseName }">{{ row.enterpriseName }}</view>
              <view v-if="row.flags.fromEntName" class="gcell gcol-2 gspan"
                :style="{ gridRowEnd: 'span ' + row.spans.fromEntName }">{{ row.fromEntName }}</view>
              <view v-if="row.flags.physicName" class="gcell gcol-3 gspan"
                :style="{ gridRowEnd: 'span ' + row.spans.physicName }">{{ row.physicName }}</view>
              <view v-if="row.flags.spec" class="gcell gcol-4 gspan" :style="{ gridRowEnd: 'span ' + row.spans.spec }">
                {{ row.spec }}</view>
              <view class="gcell gcol-5">{{ row.produceBatchNo }}</view>
              <view class="gcell gcol-6">{{ row.fromRegionName }}</view>
              <view class="gcell gcol-7">{{ row.fromQuantity }}</view>
              <view class="gcell gcol-8">{{ row.toQuantity }}</view>
              <view class="gcell gcol-9">{{ row.billTime }}</view>
              <view class="gcell gcol-10">{{ row.tracCode }}</view>
            </view>
            <view class="gcell gcell-full loading-row" v-if="hasMore">
              <view class="loading-wrapper">
                <image class="loading-icon" src="../../../../static/images/loading.png" />
              </view>
            </view>
          </view>
        </view>
      </scroll-view>
      <scroll-view class="grid-scroll" scroll-y="true" scroll-x="true" :show-scrollbar="false" :style="{
        maxHeight: tableBodyHeight + 'rpx',
        opacity: category == 2 ? 1 : 0,
        position: 'absolute',
        top: '0',
        left: '0',
        zIndex: category == 2 ? '92' : '-1',
      }" enhanced @scrolltolower="onTableScrollToLower">
        <view :style="{
          width: '1180px',
        }">
          <view class="grid-header">
            <text class="hcell hcell-sticky-left">查询企业名称</text>
            <text class="hcell">入库方企业名称</text>
            <text class="hcell">产品名称</text>
            <text class="hcell">规格</text>
            <text class="hcell">批号</text>
            <text class="hcell">货源地区</text>
            <text class="hcell">货源数量</text>
            <text class="hcell">终端到达数量</text>
            <text class="hcell">入库时间</text>
            <text class="hcell">追溯码抽样</text>
          </view>

          <view v-if="!_loading && _rows.length > 0" class="grid-body">
            <view v-for="(row, idx) in _rows" :key="idx + '-' + (row.produceBatchNo || '')" class="grow">
              <view v-if="row.flags.enterpriseName" class="gcell gcol-1 gspan" :class="['sticky-left']"
                :style="{ gridRowEnd: 'span ' + row.spans.enterpriseName }">{{ row.enterpriseName }}</view>
              <view v-if="row.flags.fromEntName" class="gcell gcol-2 gspan"
                :style="{ gridRowEnd: 'span ' + row.spans.fromEntName }">{{ row.fromEntName }}</view>
              <view v-if="row.flags.physicName" class="gcell gcol-3 gspan"
                :style="{ gridRowEnd: 'span ' + row.spans.physicName }">{{ row.physicName }}</view>
              <view v-if="row.flags.spec" class="gcell gcol-4 gspan" :style="{ gridRowEnd: 'span ' + row.spans.spec }">
                {{ row.spec }}</view>
              <view class="gcell gcol-5">{{ row.produceBatchNo }}</view>
              <view class="gcell gcol-6">{{ row.fromRegionName }}</view>
              <view class="gcell gcol-7">{{ row.fromQuantity }}</view>
              <view class="gcell gcol-8">{{ row.toQuantity }}</view>
              <view class="gcell gcol-9">{{ row.billTime }}</view>
              <view class="gcell gcol-10">{{ row.tracCode }}</view>
            </view>
            <view class="gcell gcell-full loading-row" v-if="_hasMore">
              <view class="loading-wrapper">
                <image class="loading-icon" src="../../../../static/images/loading.png" />
              </view>
            </view>
          </view>
        </view>
      </scroll-view>
      <view v-if="isLoading" class="loading-wrap">
        <view class="loading-row">
          <view class="loading-wrapper">
            <image class="loading-icon" src="../../../../static/images/loading.png" />
          </view>
        </view>
      </view>
      <view v-if="showEmptyData" class="empty-data">
        <EmptyView text="无相关数据" />
      </view>
    </view>
  </view>
</template>

<script>
import EmptyView from "../../../../wigets/empty.vue";
import Water from "@/components/water/water.vue";
export default {
  components: {
    EmptyView,
    Water,
  },
  data() {
    return {
      taskId: "",
      tableBodyHeight: 0,
      baseRowHeight: 76,
      tabs: [
        {
          label: "药品购进",
          value: "1",
        },
        {
          label: "药品销售",
          value: "2",
        },
      ],
      category: "1",
      loading: true,
      rows: [],
      totalCount: 0,
      fetchLoading: false,
      hasMore: true,
      pageNum: 1,
      pageSize: 10,
      _loading: true,
      _rows: [],
      _totalCount: 0,
      _fetchLoading: false,
      _hasMore: true,
      _pageNum: 1,
      _pageSize: 10,
    };
  },
  onLoad(options) {
    const title =
      options && options.title ? decodeURIComponent(options.title) : "报表详情";
    this.taskId = options && options.id ? options.id : "";
    uni.setNavigationBarTitle({ title });
    this.tableBodyHeight = 14 * 80;
    // this.rows = this.buildRows(this.genHierData());
    //this._rows = this.buildRows(this.genHierData());
    this.fetchList();
  },
  computed: {
    // isFixedHeight() {
    //   const arr = Array.isArray(this.rows) ? this.rows : [];
    //   const countLeaves = (node) => {
    //     if (!node || !node.enterpriseList || node.enterpriseList.length === 0) return 1;
    //     let sum = 0;
    //     for (let i = 0; i < node.enterpriseList.length; i++) {
    //       sum += countLeaves(node.enterpriseList[i]);
    //     }
    //     return sum;
    //   };
    //   let total = 0;
    //   for (let i = 0; i < arr.length; i++) {
    //     total += countLeaves(arr[i]);
    //   }
    //   return total >= 12;
    // },
    isLoading() {
      return this.loading && this.category == 1 || this._loading && this.category == 2;
    },
    showEmptyData() {
      if (this.isLoading) return false;
      if (this.category == 1 && this.rows.length === 0 || this.category == 2 && this._rows.length === 0) return true;
      return false;
    },
  },
  methods: {
    selectTab(t) {
      if (this.isLoading) return;
      this.category = t.value;
      this.fetchList();
    },
    genHierData() {
      return [
        {
          enterpriseName: "上海海王星辰药房有限公司",
          enterpriseList: [
            {
              fromEntName: "福建广药洁达医药有限公司",
              enterpriseList: [
                {
                  physicName: "感冲",
                  produceBatchNo: "2502104H",
                  fromRegionName: "广东",
                  fromQuantity: 1000,
                  toQuantity: 30,
                  billTime: "区间内第一次出库时间——区间内最后一次出库时间",
                  tracCode: "A",
                },
                {
                  physicName: "皮炎平",
                  produceBatchNo: "2502105H",
                  fromRegionName: "广西",
                  fromQuantity: 200,
                  toQuantity: 20,
                  billTime: "区间内第一次出库时间——区间内最后一次出库时间",
                  tracCode: "B",
                },
                {
                  physicName: "感冲",
                  produceBatchNo: "2502105H",
                  fromRegionName: "广西",
                  fromQuantity: 200,
                  toQuantity: 20,
                  billTime: "区间内第一次出库时间——区间内最后一次出库时间",
                  tracCode: "B",
                },
                {
                  physicName: "感冲",
                  produceBatchNo: "2502105H",
                  fromRegionName: "广西",
                  fromQuantity: 200,
                  toQuantity: 20,
                  billTime: "区间内第一次出库时间——区间内最后一次出库时间",
                  tracCode: "B",
                },
              ],
            },
            {
              fromEntName: "B有限公司",
              enterpriseList: [
                {
                  physicName: "感冲",
                  produceBatchNo: "2502104H",
                  fromRegionName: "广东",
                  fromQuantity: 1000,
                  toQuantity: 30,
                  billTime: "区间内第一次出库时间——区间内最后一次出库时间",
                  tracCode: "A",
                },
              ],
            },
          ],
        },
        {
          enterpriseName: "大参林连锁药店",
          enterpriseList: [
            {
              fromEntName: "C有限公司",
              enterpriseList: [
                {
                  physicName: "感冲",
                  produceBatchNo: "2502105H",
                  fromRegionName: "广东",
                  fromQuantity: 1000,
                  toQuantity: 30,
                  billTime: "区间内第一次出库时间——区间内最后一次出库时间",
                  tracCode: "A",
                },
                {
                  physicName: "皮炎平",
                  produceBatchNo: "2502105H",
                  fromRegionName: "广西",
                  fromQuantity: 200,
                  toQuantity: 20,
                  billTime: "区间内第一次出库时间——区间内最后一次出库时间",
                  tracCode: "B",
                },
              ],
            },
            {
              fromEntName: "D有限公司",
              enterpriseList: [
                {
                  physicName: "皮炎平",
                  produceBatchNo: "2502105H",
                  fromRegionName: "广西",
                  fromQuantity: 200,
                  toQuantity: 20,
                  billTime: "区间内第一次出库时间——区间内最后一次出库时间",
                  tracCode: "B",
                },
              ],
            },
          ],
        },
      ];
    },
    computeLeafCount(node) {
      if (!node || !node.enterpriseList || !node.enterpriseList.length)
        return 1;
      let sum = 0;
      node.enterpriseList.forEach((c) => {
        sum += this.computeLeafCount(c);
      });
      node.leafCount = sum;
      return sum;
    },
    buildRows(data) {
      const res = [];
      (data || []).forEach((companyNode) => {
        const cLeaves = this.computeLeafCount(companyNode);
        let companyStarted = false;
        (companyNode.enterpriseList || []).forEach((expNode) => {
          const eLeaves = this.computeLeafCount(expNode);
          let exporterStarted = false;
          const groups = {};
          const specGroups = {};
          (expNode.enterpriseList || []).forEach((item) => {
            const key = item.physicName || "";
            if (!groups[key]) groups[key] = [];
            groups[key].push(item);
            if (!specGroups[key]) specGroups[key] = [];
            specGroups[key].push(item.pkgSpec || '');
          });
          Object.keys(groups).forEach((prodName) => {
            const group = groups[prodName];
            let productStarted = false;
            group.forEach((batch) => {
              const { minBillTime, maxBillTime } = batch
              const billTime = `${formatDate(minBillTime, 'YYYY-MM-DD')}——${formatDate(maxBillTime, 'YYYY-MM-DD')}`
              res.push({
                enterpriseName: companyNode.enterpriseName,
                fromEntName: expNode.fromEntName,
                physicName: prodName,
                spec: batch.pkgSpec || '',
                produceBatchNo: batch.produceBatchNo,
                fromRegionName: batch.regionName,
                fromQuantity: batch.fromQty,
                toQuantity: batch.toQty,
                billTime,
                tracCode: batch.tracCode,
                spans: {
                  enterpriseName: companyStarted ? 0 : cLeaves,
                  fromEntName: exporterStarted ? 0 : eLeaves,
                  physicName: productStarted ? 0 : group.length,
                  spec: productStarted ? 0 : group.length,
                },
                flags: {
                  enterpriseName: !companyStarted,
                  fromEntName: !exporterStarted,
                  physicName: !productStarted,
                  spec: !productStarted,
                },
              });
              companyStarted = true;
              exporterStarted = true;
              productStarted = true;
            });
          });
        });
      });
      return res;
    },
    onTableScrollToLower(e) {
      if (e?.detail?.direction === 'right') return
      // if (this.isLoading) return;
      // if (this.rows.length >= this.totalCount) return;
      // this.isLoading = true;
      // const remain = this.totalCount - this.rows.length;
      // const toAdd = Math.min(15, remain);
      // setTimeout(() => {
      //   const more = this.rows.slice(0, toAdd);
      //   this.rows = this.rows.concat(more);
      //   this.isLoading = false;
      // }, 800);
      this.fetchList();
    },
    fetchList() {
      let obj = {
        pageNum: "pageNum",
        pageSize: "pageSize",
        totalCount: "totalCount",
        hasMore: "hasMore",
        fetchLoading: "fetchLoading",
        rows: "rows",
        loading: 'loading'
      };
      if (this.category == 2) {
        obj.pageNum = "_pageNum";
        obj.pageSize = "_pageSize";
        obj.totalCount = "_totalCount";
        obj.hasMore = "_hasMore";
        obj.fetchLoading = "_fetchLoading";
        obj.rows = "_rows";
        obj.loading = '_loading'
      }
      if (this[obj.fetchLoading] || !this[obj.hasMore]) return;
      this[obj.fetchLoading] = true;
      let url = `/report/getTaskTableData`;
      try {
        request(url, {
          id: this.taskId,
          category: this.category,
          pageNum: this[obj.pageNum],
          pageSize: this[obj.pageSize],
          path: '/reportExport/detail/index.vue',
        }).then(res => {
          if (res.code == 200) {
            const { total, list } = res.data || {};
            this[obj.totalCount] = total || 0;
            let _list = [];
            if (Array.isArray(list)) {
              _list = this.buildRows(list);
            }
            this[obj.rows] = [...this[obj.rows], ..._list];
            if (this[obj.rows].length < this[obj.totalCount]) {
              this[obj.hasMore] = true;
              this[obj.pageNum]++;
            } else {
              this[obj.hasMore] = false;
            }
          }
          this[obj.fetchLoading] = false;
          this[obj.loading] = false;
        })
      } catch (res) {
        this[obj.fetchLoading] = false;
        this[obj.loading] = false;
      }
      // this.rows = [];
      // setTimeout(() => {
      //   const n = Math.min(15, this.totalCount);
      //   this.rows = this.buildRows(this.genHierData()).slice(0, n);
      //   this.fetchLoading = false;
      // }, 1000);
    },
  },
};
</script>

<style scoped>
.detail-page {
  box-sizing: border-box;
  padding: 24rpx;
  position: relative;
  min-height: 100vh;
  background: #f3f6f9;
  padding-bottom: calc(50rpx + env(safe-area-inset-bottom));
}

.tabs {
  display: flex;
  align-items: center;
  background: #fff;
  border-radius: 90rpx;
  padding: 10rpx;
  margin-bottom: 30rpx;
}

.tab {
  flex: 1;
  height: 70rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 24rpx;
  border-radius: 70rpx;
  font-size: 28rpx;
  color: #333;
}

.tab+.tab {
  margin-left: 12rpx;
}

.tab.active {
  background: #2c69ff;
  color: #fff;
}

.card {
  position: relative;
  margin-top: 12rpx;
  font-size: 30rpx;
  overflow: hidden;
}

.grid-header {
  position: sticky;
  top: 0;
  z-index: 10;
  display: grid;
  grid-template-columns: 340rpx 300rpx 220rpx 220rpx 220rpx 220rpx 220rpx 220rpx 340rpx 200rpx;
}

.grid-header .hcell {
  background: #eaf2ff;
  font-weight: bold;
  color: #2c69ff;
}

.hcell {
  height: 76rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.hcell:last-child {
  border-right: none;
}

.hcell-sticky-left {
  position: sticky;
  left: 0;
  z-index: 11;
}

.grid-scroll {
  border-radius: 16rpx;
  margin-top: 8rpx;
  overflow: hidden;
}

.grid-body {
  background: #fff;
  display: grid;
  grid-template-columns: 340rpx 300rpx 220rpx 220rpx 220rpx 220rpx 220rpx 220rpx 340rpx 200rpx;
  grid-auto-rows: auto;
}

.grow {
  display: contents;
}

.gcell {
  display: flex;
  align-items: center;
  justify-content: center;
  border-bottom: 1rpx solid #eef0f4;
  border-right: 1rpx solid #eef0f4;
  background: #fff;
  color: #333;
  padding: 0 20rpx;
  text-align: center;
  line-height: 50rpx;
  word-break: break-all;
}

.gcell:last-child {
  border-right: none;
}

.gcell.gcell-full {
  grid-column: 1 / -1;
  background: transparent;
  border: none;
}

.gspan {
  background: #fff;
}

.gcol-1 {
  grid-column: 1;
}

.gcol-2 {
  grid-column: 2;
}

.gcol-3 {
  grid-column: 3;
}

.gcol-4 {
  grid-column: 4;
}

.gcol-5 {
  grid-column: 5;
}

.gcol-6 {
  grid-column: 6;
}

.gcol-7 {
  grid-column: 7;
}

.gcol-8 {
  grid-column: 8;
}

.gcol-9 {
  grid-column: 9;
}

.gcol-10 {
  grid-column: 10;
}

.sticky-left {
  position: sticky;
  left: 0;
  z-index: 9;
  background: #fff;
}

.loading-row {
  justify-content: flex-start;
}

.loading-wrapper {
  position: sticky;
  top: 50%;
  left: 0;
  width: calc(100vw - 48rpx);
  height: 76rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.loading-icon {
  width: 40rpx;
  height: 40rpx;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(360deg);
  }
}

.empty-data,
.loading-wrap {
  position: absolute;
  left: 0;
  top: 85rpx;
  z-index: 91;
  width: 100%;
  background-color: #fff;
  border-bottom-left-radius: 16rpx;
  border-bottom-right-radius: 16rpx;
}
</style>
