<template>
  <Water></Water>
  <view class="nav" :style="{ paddingTop: statusBarHeight + 'px' }">
    <text class="nav-back" :style="{ top: statusBarHeight + 'px' }" @click="onBack"></text>
    <view class="nav-title">{{ title }}</view>
  </view>
  <view class="page">
    <view class="header-card" :style="{ paddingTop: statusBarHeight + 60 + 'px' }">
      <view class="meta">
        <view class="dot"></view>
        <text class="meta-text">客户名称：{{ title }}</text>
      </view>
      <view class="meta">
        <view class="dot"></view>
        <text class="meta-text">信用代码：{{ creditCode }}</text>
      </view>
    </view>
    <view class="list-container" :style="{ paddingTop: statusBarHeight - 30 + 'px' }">
      <view v-if="loading" class="empty-row">加载中...</view>
      <view v-else-if="products.length === 0" class="empty-row">暂无数据</view>
      <view v-else v-for="(prd, i) in products" :key="'prd-' + i">
        <view class="section-title">{{ prd.productType }}{{ prd.pkgSpec ? '(' + prd.pkgSpec + ')' : '' }}</view>

        <view class="card product-card">
          <view v-for="(c, j) in prd.upstreamDTOList" :key="'cust-' + j">
            <view class="customer-row" @click.stop="toggleCustomer(i, j)">
              <view class="customer-info-main">
                <view class="main-row">
                  <text class="customer-label">上游客户：</text>
                  <text class="customer-name highlight">{{ c.upstreamCustomer }}</text>
                </view>
                <view class="info-sub-grid">
                  <view class="sub-item">
                    <text class="sub-label">客户类型：</text>
                    <text class="sub-value">{{ c.customerNature || '--' }}</text>
                  </view>
                  <view class="sub-item">
                    <text class="sub-label">客户级别：</text>
                    <text class="sub-value">{{ c.customerLevel || '--' }}</text>
                  </view>
                  <view class="sub-item">
                    <text class="sub-label">责任经理：</text>
                    <text class="sub-value">{{ c.responsibleManager || '--' }}</text>
                  </view>
                </view>
              </view>
              <uni-icons type="down" size="22" color="#999" :style="{
                transform: c.expanded ? 'rotate(180deg)' : 'rotate(0deg)',
                transition: 'transform 0.3s ease-in-out',
              }"></uni-icons>
            </view>
            <view class="table-card" v-show="c.expanded">
              <scroll-view scroll-x="true" class="table-scroll">
                <view class="blk-table">
                  <view class="blk-header">
                    <view class="th col-region">货源片区</view>
                    <view class="th col-qty">数量（盒）</view>
                    <view class="th col-batch">批号</view>
                    <view class="th col-sample">追溯码（抽样）</view>
                    <view class="th col-terminal">终端到达数量（盒）</view>
                  </view>
                  <view class="blk-body">
                    <view class="blk-row" v-for="(row, idx) in c.detailLineDTOList" :key="'row-' + idx">
                      <view class="td col-region">{{ row.supplyArea }}</view>
                      <view class="td col-qty">{{ row.quantity }}</view>
                      <view class="td col-batch">{{ row.batchNumber }}</view>
                      <view class="td col-sample copyable-code" @click="copyTraceCode(row.supervisionCodeSample)">{{
                        row.supervisionCodeSample }}</view>
                      <view class="td col-terminal">{{ row.quantity || '--' }}</view>
                    </view>
                    <view v-if="!c.detailLineDTOList || c.detailLineDTOList.length === 0" class="empty-row">暂无数据</view>
                  </view>
                </view>
              </scroll-view>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
  <BottomScrollTip :text="'左右滑动表格查看更多内容'" />
</template>

<script>
import Water from "@/components/water/water.vue";
import BottomScrollTip from "../../../../wigets/BottomScrollTip.vue";
import request from "../../../../request/index";

export default {
  components: {
    Water,
    BottomScrollTip
  },
  data() {
    return {
      statusBarHeight: 20,
      title: "黑名单详情",
      products: [],
      creditCode: "",
      loading: false,
    };
  },
  onLoad(options) {
    const info = uni.getSystemInfoSync();
    this.statusBarHeight = info.statusBarHeight || 20;
    const name = this.safeDecode(options && options.name);
    this.title = name || "黑名单详情";
    this.creditCode = options.id || "";
    this.dateStr = options.dateStr || ''

    this.fetchDetail(this.creditCode, options.dateStr); // 使用固定日期测试，或使用 dateStr
  },
  onShareAppMessage() {
    return {
      title: this.title || "黑名单详情",
      path: this.buildSharePath(),
    };
  },
  onShareTimeline() {
    return {
      title: this.title || "黑名单详情",
      query: this.buildShareQuery(),
    };
  },
  methods: {
    safeDecode(value) {
      const raw = value == null ? "" : String(value);
      if (!raw) return "";
      try {
        return decodeURIComponent(raw);
      } catch (e) {
        return raw;
      }
    },
    buildShareQuery() {
      const name = encodeURIComponent(this.title || "");
      const id = encodeURIComponent(this.creditCode || "");
      const dateStr = encodeURIComponent(this.dateStr || "");
      return `id=${id}&dateStr=${dateStr}&name=${name}`;
    },
    buildSharePath() {
      return `/traceCodePackages/traceabilityReport/pages/blacklist/detail/index?${this.buildShareQuery()}`;
    },
    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" });
        },
      });
    },
    onBack() {
      try {
        uni.navigateBack();
      } catch (e) { }
    },
    toggleCustomer(i, j) {
      const cur = this.products[i].upstreamDTOList[j];
      this.$set(this.products[i].upstreamDTOList[j], "expanded", !cur.expanded);
    },
    fetchDetail(creditCode, billTime) {
      if (!creditCode) return;
      this.loading = true;
      request("/blacklist-report/get-export-company-detail", {
        creditCode,
        billTime,
        path: "traceabilityReport/pages/blacklist/detail/index.vue",
      }).then((res) => {
        if (res.code == 200) {
          this.products = this.processData(res.data || []);
        }
        this.loading = false;
      });
    },
    processData(data) {
      return data.map((prd, i) => ({
        ...prd,
        upstreamDTOList: (prd.upstreamDTOList || []).map((cust, j) => ({
          ...cust,
          expanded: i === 0 && j === 0, // 默认展开第一个
        })),
      }));
    },
  },
};
</script>

<style scoped>
.header-card {
  background: #2c69ff;
  border-bottom-left-radius: 32rpx;
  border-bottom-right-radius: 32rpx;
  padding: 36rpx;
  color: #fff;
}

.meta {
  display: flex;
  align-items: center;
  margin: 14rpx 0;
}

.dot {
  width: 8rpx;
  height: 8rpx;
  border-radius: 50%;
  background: #fff;
  margin-right: 20rpx;
}

.meta-text {
  font-size: 32rpx;
}

.nav {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 44px;
  background-color: #2c69ff;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10;
}

.nav-title {
  font-size: 36rpx;
  color: #fff;
  font-weight: 700;
}

.nav-back {
  position: absolute;
  left: 40rpx;
  top: 12rpx;
  width: 20rpx;
  height: 20rpx;
  color: #fff;
  border-left: 3rpx solid #fff;
  border-bottom: 3rpx solid #fff;
  transform: rotate(45deg) translateY(56rpx);
  margin-left: 40rpx;
  margin-top: -6rpx;
}

.page {
  min-height: 100vh;
  background: #f3f6f9;
}

.section-title {
  position: relative;
  font-size: 30rpx;
  font-weight: bold;
  color: #2c69ff;
  margin-left: 24rpx;
}

.section-title::after {
  content: "";
  position: absolute;
  left: -20rpx;
  bottom: 11rpx;
  width: 8rpx;
  height: 50%;
  background: #2c69ff;
  border-radius: 10px;
}

.list-container {
  padding: 0 24rpx 24rpx;
  box-sizing: border-box;
}

.card {
  margin: 24rpx;
  background: #fff;
  border-radius: 16rpx;
  font-size: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.product-card {
  padding: 24rpx;
}

.product-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 16rpx;
}

.customer-row {
  display: flex;
  align-items: flex-start;
  padding: 24rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
  justify-content: space-between;
}

.customer-info-main {
  flex: 1;
  margin-right: 20rpx;
}

.main-row {
  margin-bottom: 16rpx;
  display: flex;
  align-items: center;
}

.customer-label {
  font-size: 28rpx;
  color: #999;
  flex-shrink: 0;
}

.customer-name {
  font-size: 28rpx;
  color: #333;
}

.customer-name.highlight {
  color: #2c69ff;
  font-weight: 600;
  font-size: 30rpx;
}

.info-sub-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx 24rpx;
}

.sub-item {
  display: flex;
  align-items: center;
  min-width: 45%;
}

.sub-label {
  font-size: 24rpx;
  color: #bbb;
  flex-shrink: 0;
}

.sub-value {
  font-size: 24rpx;
  color: #666;
  font-weight: 500;
}

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

.expand-tag {
  margin-left: auto;
  font-size: 26rpx;
  color: #2c69ff;
}

.table-card {
  padding: 0;
  overflow: hidden;
  margin-top: 16rpx;
}

.table-scroll {
  width: 100%;
}

.blk-table {
  min-width: 1150rpx;
  border-top: 1rpx solid #eee;
  border-left: 1rpx solid #eee;
}

.blk-header {
  display: flex;
  background: #f5f7fa;
  font-size: 26rpx;
  font-weight: bold;
  color: #2c69ff;
}

.blk-body {
  font-size: 26rpx;
  color: #666;
}

.blk-row {
  display: flex;
  border-bottom: 1rpx solid #eee;
}

.blk-row:nth-child(even) {
  background-color: #f7f7f7;
}

.th,
.td {
  padding: 16rpx 10rpx;
  border-right: 1rpx solid #eee;
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
  word-break: break-all;
  box-sizing: border-box;
  flex-shrink: 0;
}

.th {
  border-bottom: 1rpx solid #eee;
}

.empty-row {
  padding: 30rpx;
  text-align: center;
  color: #999;
}

.col-region {
  width: 200rpx;
}

.col-qty {
  width: 160rpx;
}

.col-batch {
  width: 200rpx;
}

.col-sample {
  width: 325rpx;
}

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

.col-terminal {
  width: 265rpx;
}
</style>
