<template>
  <Water></Water>
  <view class="scan-range-page">
    <view class="loading-page" v-if="getLoading()">
      <image class="loading-icon" src="../../../static/images/loading.png" />
    </view>
    <scroll-view v-else class="content" scroll-y="true" @scrolltolower="onScrollToLower">
      <view class="item" v-for="(item, i) in companyList" :key="i" @click="toggle(i)">
        <view class="item-header">
          <text class="item-title">{{ i + 1 }}.&nbsp;{{ item.entName || "" }}</text>
          <uni-icons type="down" size="22" color="#999" :style="{
            transform: expanded[i] ? 'rotate(180deg)' : 'rotate(0deg)',
            transition: 'transform 0.3s ease-in-out',
          }"></uni-icons>
        </view>
        <scroll-view class="item-collapse" scroll-y="true" :style="{
          height: getCollapseHeight(i),
        }" @scrolltolower="getDrugInfoNameList(i)">
          <view class="cv-item" v-for="(d, di) in products[i]" :key="'drug-' + di">
            <view class="cv-index-wrap">
              <text class="cv-index">{{ di + 1 }}</text>
            </view>
            <view class="cv-body">
              <view class="cv-row">
                <text class="cv-label">药品名称：</text>
                <text class="cv-value">{{ d.physicName || "" }}</text>
              </view>
              <view class="cv-row">
                <text class="cv-label">药品规格：</text>
                <text class="cv-value">{{ d.pkgSpec || "" }}</text>
              </view>
            </view>
          </view>
        </scroll-view>
      </view>
      <view class="loading-row" v-if="companyHasMore">
        <view class="loading-wrapper">
          <image class="loading-icon" src="../../../static/images/loading.png" />
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script>
import request from "../../../request/index.js";
import { getPaginatedList } from "../../../utils/utils.js";
import Water from "@/components/water/water.vue";
export default {
  components: {
    Water,
  },
  data() {
    return {
      companyList: [],
      companyPageNum: 1,
      companyPageSize: 20,
      companyTotalCount: 0,
      companyHasMore: true,
      companyLoading: false,
      fetchedCount: 0,
      allCompanies: [],
      loading: true,
      expanded: {},
      products: {},
      productPages: [],
    };
  },
  onLoad() {
    this.fetchInitial();
  },
  methods: {
    normalizeEntName(s) {
      return String(s || "")
        .trim()
        .replace(/\(/g, "（")
        .replace(/\)/g, "）");
    },
    getDrugInfoNameList(i) {
      const res = getPaginatedList({
        page: this.productPages[i] || 0,
        initData: this.companyList[i]?.drugInfoNameList || [],
        data: this.products[i] || [],
      });
      if (!res || !Array.isArray(res.data)) return;
      this.$set(this.productPages, i, res.page || this.productPages[i] || 0);
      this.$set(this.products, i, res.data);
    },
    getCollapseHeight(i) {
      if (!this.expanded[i]) return "0";
      const n = this.companyList[i]?.drugInfoNameList?.length || 0;
      const perItemRpx = 132;
      const maxRpx = 560;
      return Math.min(maxRpx, n * perItemRpx) + "rpx";
    },
    getLoading() {
      return this.loading;
    },
    fetchInitial() {
      this.fetchCustomers();
    },
    fetchCustomers() {
      if (!this.companyHasMore || this.companyLoading) return;
      this.companyLoading = true;
      request("/customer/info/getEnterpriseData", {
        pageNum: this.companyPageNum,
        pageSize: this.companyPageSize,
        path: "/traceabilityCodeQuery/pages/scanRange/index.vue",
      }).then((res) => {
        if (res.code == 200) {
          const { total, list } = res.data || {};
          this.companyTotalCount = total || 0;
          const rawList = Array.isArray(list) ? list : [];
          this.fetchedCount = (this.fetchedCount || 0) + rawList.length;

          this.companyList = [...this.companyList, ...rawList];

          if (
            rawList.length > 0 &&
            this.fetchedCount < this.companyTotalCount
          ) {
            this.companyPageNum++;
            this.companyHasMore = true;
          } else {
            this.companyHasMore = false;
          }
          this.companyList.forEach((item, i) => {
            this.getDrugInfoNameList(i);
          });

          if (
            this.companyHasMore &&
            (filtered.length === 0 || this.companyList.length < 10)
          ) {
            this.companyLoading = false;
            this.fetchCustomers();
            return;
          }
        }
        this.companyLoading = false;
        this.loading = false;
      });
    },
    onScrollToLower() {
      this.fetchCustomers();
    },
    toggle(i) {
      this.$set(this.expanded, i, !this.expanded[i]);
    },
  },
};
</script>

<style>
.scan-range-page {
  box-sizing: border-box;
  padding: 24rpx;
  height: 100vh;
  background: #f3f6f9;
}

.content {
  max-height: calc(100vh - env(safe-area-inset-bottom));
  background: #fff;
  border-radius: 16rpx;
}

.item {
  padding: 10rpx 20rpx;
  border-bottom: 1rpx solid #eef0f4;
}

.item-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  line-height: 60rpx;
}

.item-title {
  font-size: 30rpx;
  color: #333;
}

.item-collapse {
  margin-top: 12rpx;
  height: 0;
  transition: height 0.3s ease-in-out;
}

.cv-item {
  box-sizing: border-box;
  padding: 20rpx 12rpx 20rpx 8rpx;
  display: flex;
  align-items: flex-start;
  color: #666;
  border-bottom: 1rpx solid #f0f2f5;
}

.cv-item:last-child {
  border-bottom: none;
}

.cv-index-wrap {
  flex-shrink: 0;
  padding-top: 6rpx;
  margin-right: 16rpx;
}

.cv-index {
  display: flex;
  align-items: center;
  justify-content: center;
  min-width: 25rpx;
  height: 36rpx;
  padding: 0 6rpx;
  line-height: 1;
  font-size: 20rpx;
  text-align: center;
  border-radius: 50%;
  border: 1rpx solid #999;
}

.cv-body {
  flex: 1;
  min-width: 0;
}

.cv-row {
  display: flex;
  align-items: flex-start;
  font-size: 28rpx;
  line-height: 1.5;
}

.cv-row+.cv-row {
  margin-top: 10rpx;
}

.cv-label {
  flex-shrink: 0;
  width: 150rpx;
  color: #727a86;
}

.cv-value {
  flex: 1;
  min-width: 0;
  color: #333;
  word-break: break-all;
  white-space: normal;
}

.loading-page {
  width: 100%;
  height: 200rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.loading-row {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20rpx;
}

.loading-wrapper {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

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

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

  to {
    transform: rotate(360deg);
  }
}
</style>
