<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">客户扫码率</view>
  </view>
  <view class="page" @click="closeDropdown">
    <view
      class="header-card"
      :style="{ paddingTop: statusBarHeight + 60 + 'px' }"
    >
      <view class="meta">
        <view class="dot"></view>
        <text class="meta-text"
          >等级：{{
            scanType == 1 ? "VIP" : scanType == 2 ? "二级" : "三级"
          }}客户</text
        >
      </view>
      <view class="meta">
        <view class="dot"></view>
        <text class="meta-text">片区：{{ regionName }}</text>
      </view>
      <view class="meta">
        <view class="dot"></view>
        <text class="meta-text">品种：{{ physicName || "全品种" }}</text>
      </view>
      <view class="meta">
        <view class="dot"></view>
        <text class="meta-text">时间区间：{{ dateRange }}</text>
      </view>
      <view class="selector-wrap" @click.stop>
        <input
          class="selector-input"
          v-model="customerInput.customerName"
          placeholder="选择客户"
          @focus="openDropdown"
          @input="onInputChange"
        />
        <view
          class="selector-arrow"
          :class="{ open: dropdownOpen }"
          @click="toggleDropdown"
        ></view>
        <view class="dropdown" v-show="dropdownOpen" @click.stop>
          <scroll-view
            v-if="customers.length && !customerLoading"
            scroll-y
            :style="{ maxHeight: '300rpx' }"
            lower-threshold="20"
            @scrolltolower="getCustomerInfo"
          >
            <view
              class="dropdown-item"
              v-for="(c, i) in customers"
              :key="i"
              @click="selectCustomer(c)"
              >{{ c.customerName || "--" }}</view
            >
            <view v-if="customerHasMore" class="customer-loading-wrap">
              <image
                src="../../../../static/images/loading.png"
                mode="scaleToFill"
                class="loading-icon"
              />
            </view>
          </scroll-view>
          <view v-else-if="customerLoading" class="customer-loading-wrap">
            <image
              src="../../../../static/images/loading.png"
              mode="scaleToFill"
              class="loading-icon"
            />
          </view>
          <view v-else class="dropdown-item">暂无数据</view>
        </view>
      </view>
    </view>

    <view class="card">
      <ScanRateTable
        :api="`/bills/getScanRateDetail`"
        :columns="columns"
        :tableBodyHeight="tableBodyHeight"
        :showHeader="false"
        bodyFontColor="#000"
        summaryBold="true"
        tableType="customerDetail"
        :params="queryParams"
      />
    </view>
  </view>
</template>

<script>
import ScanRateTable from "../wigets/ScanRateTable.vue";
import Water from "@/components/water/water.vue";
import request from "../../../../request/index.js";
export default {
  components: {
    ScanRateTable,
    Water,
  },
  data() {
    return {
      customerLevel: "",
      rangeType: "",
      regionCode: "",
      drugEntBaseInfoId: "",
      scanType: "",
      statusBarHeight: 20,
      regionName: "",
      physicName: "",
      customerPage: 1,
      customerPageSize: 10,
      customerTotal: null,
      customerHasMore: true,
      customerLoading: false,
      customers: [],
      customerInput: { customerName: "" },
      customerDebounceTimer: null,
      selectedCustomer: "",
      dropdownOpen: false,
      totalCount: 30,
      isLoading: false,
      list: [],
      columns: [
        {
          key: "custemerName",
          title: "客户名称",
          underline: false,
          fixed: false,
          width: "",
        },
        {
          key: "outScanRate",
          title: "出库扫码率",
          fixed: false,
          width: "",
          unit: "%",
        },
        {
          key: "inScanRate",
          title: "入库扫码率",
          fixed: false,
          width: "",
          unit: "%",
        },
        {
          key: "selfExaminationRate",
          title: "自验证率",
          fixed: false,
          width: "",
          unit: "%",
        },
      ],
    };
  },
  onLoad(options) {
    const info = uni.getSystemInfoSync();
    this.statusBarHeight = info.statusBarHeight || 20;
    // this.list = this.genRows(Math.min(10, this.totalCount));

    this.rangeType = options.type || 1;
    this.regionCode = options.regionCode || "";
    this.drugEntBaseInfoId = options.drugEntBaseInfoId || "";
    this.scanType = options.scanType || "1";
    this.physicName = decodeURIComponent(options.physicName || "");
    this.regionName = decodeURIComponent(options.regionName || "");
    this.customerLevel =
      this.scanType == 1 ? "VIP" : this.scanType == 2 ? "二级" : "三级";
    this.getCustomerInfo();
  },
  watch: {
    "customerInput.customerName": {
      handler(newVal, oldVal) {
        if (!newVal || newVal !== oldVal) {
          if (this.customerDebounceTimer)
            clearTimeout(this.customerDebounceTimer);
          this.customerDebounceTimer = setTimeout(() => {
            this.customerPage = 1;
            this.customers = [];
            this.customerHasMore = true;
            this.getCustomerInfo();
          }, 500);
        }
      },
      deep: true,
    },
  },
  computed: {
    dateRange() {
      const t = Number(this.rangeType) || 1;
      const now = new Date();
      const pad = (n) => (n < 10 ? "0" + n : "" + n);
      const fmt = (d) =>
        `${d.getFullYear()}.${pad(d.getMonth() + 1)}.${pad(d.getDate())}`;
      let start;
      let end;
      if (t === 2) {
        const y = now.getFullYear();
        const m = now.getMonth();
        start = new Date(y, m, 1);
        end = new Date(y, m + 1, 0);
      } else if (t === 3) {
        const y = now.getFullYear();
        const m = now.getMonth();
        start = new Date(y, m - 1, 1);
        end = new Date(y, m, 0);
      } else if (t === 4) {
        end = now;
        start = new Date(now.getTime() - 59 * 24 * 60 * 60 * 1000);
      } else {
        end = now;
        start = new Date(now.getTime() - 6 * 24 * 60 * 60 * 1000);
      }
      return `${fmt(start)}-${fmt(end)}`;
    },
    queryParams() {
      return {
        type: this.rangeType,
        regionCode: this.regionCode,
        drugEntBaseInfoId: this.drugEntBaseInfoId,
        customerName: this.customerInput?.customerName,
        scanType: this.scanType,
        levelType: this.customerLevel,
      };
    },
    tableBodyHeight() {
      const rowHeight = 76; // rpx
      if (this.totalCount >= 9) return `${rowHeight * 8.5}rpx`;
      return "auto";
    },
  },
  methods: {
    getCustomerInfo() {
      if (!this.customerHasMore || this.customerLoading) return;
      this.customerLoading = true;
      request("/customer/info/getCustomerInfo", {
        customerName: this.customerInput?.customerName,
        name: this.physicName,
        pageNum: this.customerPage,
        pageSize: this.customerPageSize,
        customerLevel: this.customerLevel,
        provinceCode: this.regionCode,
        path: "/traceabilityReport/pages/customerScanningRate/detail/index.vue",
      }).then((res) => {
        if (res.code == 200) {
          const _data = res.data || {};
          this.customerTotal = _data.total;
          if (this.customerTotal <= this.customers.length) {
            this.customerHasMore = false;
            return;
          } else {
            const list = Array.isArray(_data.list) ? _data.list : [];
            this.customers = [...this.customers, ...list];

            if (this.customerTotal <= this.customers.length) {
              this.customerHasMore = false;
            } else {
              this.customerPage++;
              this.customerHasMore = true;
            }
            // }
          }
        }
        setTimeout(() => {
          this.customerLoading = false;
        }, 200);
      });
    },
    openDropdown() {
      this.dropdownOpen = true;
    },
    toggleDropdown() {
      this.dropdownOpen = !this.dropdownOpen;
    },
    onInputChange(e) {
      const v = e?.detail?.value ?? this.customerInput;
      this.customerInput.customerName = v;
    },
    selectCustomer(c) {
      this.selectedCustomer = c;
      this.customerInput = c;
      this.dropdownOpen = false;
    },
    closeDropdown() {
      this.dropdownOpen = false;
    },
    onBack() {
      try {
        uni.navigateBack();
      } catch (e) {}
    },
    onTableScrollToLower() {
      if (this.isLoading) return;
      if (this.list.length >= this.totalCount) return;
      this.isLoading = true;
      const remain = this.totalCount - this.list.length;
      const toAdd = Math.min(10, remain);
      setTimeout(() => {
        const more = this.genRows(toAdd);
        this.list = this.list.concat(more);
        this.isLoading = false;
      }, 800);
    },
    genRows(n) {
      const res = [];
      const regions = [
        "山东医药",
        "江苏医药",
        "浙江医药",
        "广东医药",
        "湖南医药",
        "湖北医药",
      ];
      const base = this.list.length;
      for (let i = 0; i < n; i++) {
        const name = regions[(base + i) % regions.length];
        res.push({ region: name, outRate: "0%", inRate: "0%" });
      }
      return res;
    },
  },
};
</script>

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

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

.page {
  height: 100vh;
}

.card {
  margin: 24rpx;
  background: #fff;
  border-radius: 16rpx;
  font-size: 32rpx;
}

/* .table-header {
  display: flex;
  background: #eaf2ff;
  font-weight: bold;
  color: #2c69ff;
  border-top-left-radius: 16rpx;
  border-top-right-radius: 16rpx;
}
.table-body {
  margin-top: 8rpx;
}
.row {
  display: flex;
  align-items: center;
}
.row:last-child {
  border-bottom: none;
}
.cell {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 76rpx;
} */
.loading-row {
  justify-content: center;
}

.loading-wrapper {
  width: 100%;
  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);
  }
}

/* .total-row {
  font-weight: bold;
  color: #2c69ff;
} */
.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;
}

.selector-wrap {
  position: relative;
  margin-top: 16rpx;
}

.selector-input {
  width: 100%;
  height: 64rpx;
  border-radius: 32rpx;
  background: #fff;
  color: #333;
  padding: 0 72rpx 0 30rpx;
  box-sizing: border-box;
  font-size: 28rpx;
}

.selector-arrow {
  position: absolute;
  right: 24rpx;
  bottom: 25rpx;
  width: 16rpx;
  height: 16rpx;
  border: 5rpx solid #2c69ff;
  border-top: none;
  border-left: none;
  transform-origin: 50% 50%;
  transform: rotate(45deg);
  transition: transform 0.2s;
}

.selector-arrow.open {
  bottom: 18rpx;
  transform: rotate(225deg);
}

.dropdown {
  position: absolute;
  left: 0;
  right: 0;
  top: 70rpx;
  background: #fff;
  border: 1rpx solid #eef0f4;
  border-radius: 12rpx;
  box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.08);
  z-index: 10;
  max-height: none;
}

.dropdown-item {
  padding: 16rpx 24rpx;
  font-size: 28rpx;
  color: #333;
}

.dropdown-item + .dropdown-item {
  border-top: 1rpx solid #f0f2f5;
}

.customer-loading-wrap {
  width: 100%;
  height: 70rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
