<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="grid-scroll">
      <scroll-view v-show="category == 1" scroll-y class="grid-scroll-view" @scrolltolower="onTableScrollToLower">
        <view>
          <view v-if="!loading && rows.length > 0" class="card-list">
            <view class="company-card" v-for="(company, cIdx) in rows" :key="cIdx">
              <view class="company-header" @click="toggleExpand(company)">
                <view class="company-title">
                  <text class="company-name">入库方：{{ company.name }}</text>
                  <view class="company-products" v-if="company.products && company.products.length">
                    <text class="company-product-item" v-for="(prod, pIdx) in company.products" :key="pIdx">
                      {{ prod.name }} {{ prod.spec }}
                    </text>
                  </view>
                  <view class="company-meta">
                    <view class="company-meta-row">
                      <text class="company-meta-item">客户性质：{{ company.customerNature || "--" }}</text>
                      <text class="company-meta-item">客户等级：{{ company.customerLevel || "--" }}</text>
                    </view>
                    <view class="company-meta-row">
                      <text class="company-meta-item">责任经理：{{ company.responsibleManager || "--" }}</text>
                    </view>
                  </view>
                  <!-- <text class="company-total">总数量：{{ company.totalQty }}</text> -->
                </view>
                <uni-icons :type="company.expanded ? 'up' : 'down'" size="20" color="#999"></uni-icons>
              </view>
              <view v-if="company.expanded" class="company-body">
                <view class="exporter-section" v-for="(exp, eIdx) in company.exporters" :key="eIdx">
                  <view class="exporter-title" @click="toggleSubExpand(exp)">
                    <text>{{ category == 1 ? '出库方' : '入库方' }}：{{ exp.name }}</text>
                    <uni-icons :type="exp.expanded ? 'up' : 'down'" size="16" color="#666"></uni-icons>
                  </view>
                  <view class="exporter-meta">
                    <view class="exporter-meta-row">
                      <text class="exporter-meta-item">客户性质：{{ exp.fromCustomerNature || "--" }}</text>
                      <text class="exporter-meta-item">客户等级：{{ exp.fromCustomerLevel || "--" }}</text>
                    </view>
                    <view class="exporter-meta-row">
                      <text class="exporter-meta-item">责任经理：{{ exp.fromResponsibleManager || "--" }}</text>
                    </view>
                  </view>
                  <view v-if="exp.expanded" class="product-group" v-for="(pg, pIdx) in exp.products" :key="pIdx">
                    <!-- Product Header Removed as requested, info is now in company header -->
                    <!-- <view class="product-header">
                      <text class="product-name">{{ pg.name }}</text>
                      <text class="product-spec">{{ pg.spec }}</text>
                    </view> -->
                    <scroll-view scroll-x class="batch-scroll">
                      <view class="batch-table">
                        <view class="batch-header-row">
                          <text class="th-cell col-batch">批号</text>
                          <text class="th-cell col-region">货源地区</text>
                          <text class="th-cell col-qty">货源数量（盒）</text>
                          <text class="th-cell col-qty">终端到达数量（盒）</text>
                          <text class="th-cell col-time">出库时间</text>
                          <text class="th-cell col-code">追溯码抽样</text>
                        </view>
                        <view class="batch-row" v-for="(batch, bIdx) in pg.batches" :key="bIdx">
                          <text class="td-cell col-batch">{{ batch.produceBatchNo }}</text>
                          <text class="td-cell col-region">{{ batch.regionName }}</text>
                          <text class="td-cell col-qty">{{ batch.fromQty }}</text>
                          <text class="td-cell col-qty">{{ batch.toQty }}</text>
                          <text class="td-cell col-time">{{ batch.billTime }}</text>
                          <text class="td-cell col-code copyable-code" @click="copyTraceCode(batch.tracCode)">
                            {{ batch.tracCode }}
                          </text>
                        </view>
                      </view>
                    </scroll-view>
                  </view>
                </view>
              </view>
            </view>
            <view class="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 v-show="category == 2" class="grid-scroll" scroll-y="true" scroll-x="true" :show-scrollbar="false"
        enhanced @scrolltolower="onTableScrollToLower">
        <view>
          <view v-if="!_loading && _rows.length > 0" class="card-list">
            <view class="company-card" v-for="(company, cIdx) in _rows" :key="cIdx">
              <view class="company-header" @click="toggleExpand(company)">
                <view class="company-title">
                  <text class="company-name">出库方：{{ company.name }}</text>
                  <view class="company-products" v-if="company.products && company.products.length">
                    <text class="company-product-item" v-for="(prod, pIdx) in company.products" :key="pIdx">
                      {{ prod.name }} {{ prod.spec }}
                    </text>
                  </view>
                  <view class="company-meta">
                    <view class="company-meta-row">
                      <text class="company-meta-item">客户性质：{{ company.customerNature || "--" }}</text>
                      <text class="company-meta-item">客户等级：{{ company.customerLevel || "--" }}</text>
                    </view>
                    <view class="company-meta-row">
                      <text class="company-meta-item">责任经理：{{ company.responsibleManager || "--" }}</text>
                    </view>
                  </view>
                  <!-- <text class="company-total">总数量：{{ company.totalQty }}</text> -->
                </view>
                <uni-icons :type="company.expanded ? 'up' : 'down'" size="20" color="#999"></uni-icons>
              </view>
              <view v-if="company.expanded" class="company-body">
                <view class="exporter-section" v-for="(exp, eIdx) in company.exporters" :key="eIdx">
                  <view class="exporter-title" @click="toggleSubExpand(exp)">
                    <text>{{ category == 1 ? '出库方' : '入库方' }}：{{ exp.name }}</text>
                    <uni-icons :type="exp.expanded ? 'up' : 'down'" size="16" color="#666"></uni-icons>
                  </view>
                  <view class="exporter-meta">
                    <view class="exporter-meta-row">
                      <text class="exporter-meta-item">客户性质：{{ exp.fromCustomerNature || "--" }}</text>
                      <text class="exporter-meta-item">客户等级：{{ exp.fromCustomerLevel || "--" }}</text>
                    </view>
                    <view class="exporter-meta-row">
                      <text class="exporter-meta-item">责任经理：{{ exp.fromResponsibleManager || "--" }}</text>
                    </view>
                  </view>
                  <view v-if="exp.expanded" class="product-group" v-for="(pg, pIdx) in exp.products" :key="pIdx">
                    <scroll-view scroll-x class="batch-scroll">
                      <view class="batch-table">
                        <view class="batch-header-row">
                          <text class="th-cell col-batch">批号</text>
                          <text class="th-cell col-region">货源地区</text>
                          <text class="th-cell col-qty">货源数量</text>
                          <text class="th-cell col-qty">终端到达数量</text>
                          <text class="th-cell col-time">入库时间</text>
                          <text class="th-cell col-code">追溯码抽样</text>
                        </view>
                        <view class="batch-row" v-for="(batch, bIdx) in pg.batches" :key="bIdx">
                          <text class="td-cell col-batch">{{ batch.produceBatchNo }}</text>
                          <text class="td-cell col-region">{{ batch.regionName }}</text>
                          <text class="td-cell col-qty">{{ batch.fromQty }}</text>
                          <text class="td-cell col-qty">{{ batch.toQty }}</text>
                          <text class="td-cell col-time">{{ batch.billTime }}</text>
                          <text class="td-cell col-code copyable-code" @click="copyTraceCode(batch.tracCode)">
                            {{ batch.tracCode }}
                          </text>
                        </view>
                      </view>
                    </scroll-view>
                  </view>
                </view>
              </view>
            </view>
            <view class="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>
  <BottomScrollTip :text="'左右滑动表格查看更多内容'" />
</template>

<script>
import EmptyView from "../../../../wigets/empty.vue";
import BottomScrollTip from "../../../../wigets/BottomScrollTip.vue";
import Water from "@/components/water/water.vue";
import request from "../../../../request/index.js";
import { formatDate } from "../../../../utils/utils.js";

export default {
  components: {
    EmptyView,
    BottomScrollTip,
    Water,
  },
  data() {
    return {
      shareTitle: "报表详情",
      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 = this.safeDecode(options && options.title) || "报表详情";
    this.shareTitle = title;
    this.taskId = options && options.id ? options.id : "";
    uni.setNavigationBarTitle({ title });
    this.tableBodyHeight = 14 * 80;
    this.fetchList();
  },
  onShareAppMessage() {
    return {
      title: this.shareTitle || "报表详情",
      path: this.buildSharePath(),
    };
  },
  onShareTimeline() {
    return {
      title: this.shareTitle || "报表详情",
      query: this.buildShareQuery(),
    };
  },
  computed: {
    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: {
    safeDecode(value) {
      const raw = value == null ? "" : String(value);
      if (!raw) return "";
      try {
        return decodeURIComponent(raw);
      } catch (e) {
        return raw;
      }
    },
    buildShareQuery() {
      const id = encodeURIComponent(this.taskId || "");
      const title = encodeURIComponent(this.shareTitle || "");
      return `id=${id}&title=${title}`;
    },
    buildSharePath() {
      return `/traceCodePackages/traceabilityReport/pages/reportExport/detail/index?${this.buildShareQuery()}`;
    },
    selectTab(t) {
      if (this.isLoading) return;
      this.category = t.value;
      this.fetchList();
    },
    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;
    },
    processData(list) {
      const res = [];
      if (!list || !list.length) return res;
      list.forEach((company) => {
        const companyNode = {
          name: company.enterpriseName,
          customerLevel: company.customerLevel || "",
          customerNature: company.customerNature || "",
          responsibleManager: company.responsibleManager || "",
          totalQty: 0,
          expanded: false, // Default collapsed
          exporters: [],
          products: [], // Collect unique products here
        };
        const uniqueProducts = {};

        (company.enterpriseList || []).forEach((exp) => {
          const expNode = {
            name: exp.fromEntName,
            fromCustomerLevel: exp.fromCustomerLevel || "",
            fromCustomerNature: exp.fromCustomerNature || "",
            fromResponsibleManager: exp.fromResponsibleManager || "",
            expanded: false, // Default collapsed
            products: [],
          };
          const productGroups = {};
          (exp.enterpriseList || []).forEach((item) => {
            const key = (item.physicName || "") + "|" + (item.pkgSpec || "");
            // Collect global unique products for the company header
            if (!uniqueProducts[key]) {
              uniqueProducts[key] = {
                name: item.physicName,
                spec: item.pkgSpec || "",
              };
            }

            if (!productGroups[key]) {
              productGroups[key] = {
                name: item.physicName,
                spec: item.pkgSpec || "",
                batches: [],
              };
            }
            const { minBillTime, maxBillTime } = item;
            const billTime = `${formatDate(minBillTime, "YYYY-MM-DD")}——${formatDate(maxBillTime, "YYYY-MM-DD")}`;
            const qty = Number(item.toQty) || 0;
            companyNode.totalQty += qty;
            productGroups[key].batches.push({
              ...item,
              billTime,
            });
          });
          Object.values(productGroups).forEach((pg) => {
            expNode.products.push(pg);
          });
          companyNode.exporters.push(expNode);
        });
        companyNode.products = Object.values(uniqueProducts);
        res.push(companyNode);
      });
      return res;
    },
    toggleExpand(item) {
      this.$set(item, "expanded", !item.expanded);
    },
    toggleSubExpand(item) {
      this.$set(item, "expanded", !item.expanded);
    },
    copyTraceCode(code) {
      const text = String(code || "").trim();
      if (!text) {
        uni.showToast({ title: "无可复制内容", icon: "none" });
        return;
      }
      uni.setClipboardData({
        data: text,
        success: () => {
          uni.showToast({ title: "追溯码已复制", icon: "none" });
        },
      });
    },
    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.processData(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) {
        console.log(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));
}

.grid-scroll {
  padding-bottom: 80rpx;
}

.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;
}

/* New Card Styles */
.card-list {
  padding: 24rpx;
  background: #f5f7fa;
  min-height: 100vh;
}

.company-card {
  background: #fff;
  border-radius: 16rpx;
  margin-bottom: 24rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
}

.company-header {
  padding: 24rpx 30rpx;
  background: #fff;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1rpx solid #f0f0f0;
}

.company-title {
  display: flex;
  flex-direction: column;
}

.company-name {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 8rpx;
}

.company-products {
  margin-bottom: 8rpx;
}

.company-meta {
  margin-bottom: 8rpx;
}

.company-meta-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 6rpx;
}

.company-meta-row:last-child {
  margin-bottom: 0;
}

.company-meta-item {
  font-size: 26rpx;
  color: #666;
  margin-right: 24rpx;
  display: inline-block;
}

.company-product-item {
  font-size: 26rpx;
  color: #666;
  margin-right: 16rpx;
  display: inline-block;
}

.company-total {
  font-size: 24rpx;
  color: #999;
}

.company-body {
  background: #fff;
  padding: 0 24rpx 24rpx;
}

.exporter-section {
  margin-top: 24rpx;
  border: 1rpx solid #eef0f4;
  border-radius: 12rpx;
  overflow: hidden;
}

.exporter-title {
  background: #f8f9fb;
  padding: 16rpx 24rpx;
  font-size: 28rpx;
  font-weight: 600;
  color: #333;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1rpx solid #eef0f4;
}

.exporter-meta {
  background: #f8f9fb;
  padding: 8rpx 24rpx 16rpx;
  border-bottom: 1rpx solid #eef0f4;
}

.exporter-meta-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 6rpx;
}

.exporter-meta-row:last-child {
  margin-bottom: 0;
}

.exporter-meta-item {
  font-size: 26rpx;
  color: #666;
  margin-right: 24rpx;
  display: inline-block;
}

.product-group {
  padding: 0;
}

.product-header {
  padding: 16rpx 24rpx;
  display: flex;
  justify-content: space-between;
  font-size: 26rpx;
  color: #666;
  border-bottom: 1rpx solid #f0f0f0;
}

.batch-scroll {
  width: 100%;
}

.batch-table {
  min-width: 1550rpx;
}

.batch-header-row {
  display: flex;
  background: #f7f9fc;
  color: #2c69ff;
}

.batch-row {
  display: flex;
  border-bottom: 1rpx solid #f0f0f0;
}

.batch-row:nth-child(even) {
  background-color: #f7f9fc;
}

.batch-row:last-child {
  border-bottom: none;
}

.th-cell {
  padding: 16rpx 10rpx;
  font-size: 24rpx;
  text-align: center;
  flex-shrink: 0;
  font-weight: 600;
}

.td-cell {
  padding: 16rpx 10rpx;
  font-size: 24rpx;
  color: #333;
  text-align: center;
  flex-shrink: 0;
  word-break: break-all;
  display: flex;
  align-items: center;
  justify-content: center;
}

.col-batch {
  width: 220rpx;
}

.col-region {
  width: 180rpx;
}

.col-qty {
  width: 210rpx;
}

.col-time {
  width: 340rpx;
}

.col-code {
  width: 280rpx;
}

.copyable-code {
  color: #2c69ff;
}

.loading-row {
  padding: 24rpx;
  display: flex;
  justify-content: center;
}

.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: 280rpx;
  z-index: 91;
  width: 100%;
  background-color: transparent;
  border-bottom-left-radius: 16rpx;
  border-bottom-right-radius: 16rpx;
}

.empty-data {
  top: 280rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: transparent;
}
</style>
