<template>
  <Water></Water>
  <view
    class="detail-page"
    :style="{ height: pageHeight }"
    v-if="!!data && !loading"
  >
    <view
      class="detail-card detail-bg"
      :style="{ backgroundImage: 'url(' + bg + ')' }"
    >
      <view class="detail-drug-title">{{ data.physicName }}</view>
      <view class="detail-row detail-traceability">
        <view class="detail-label">追溯码：</view>
        <view class="detail-value detail-wrap">{{
          formatTraceCode(traceCode)
        }}</view>
        <view class="detail-copy-btn" @click="copy(traceCode)">
          <image
            src="../../../static/images/copy.png"
            mode="scaleToFill"
            :style="{ width: '30rpx', height: '30rpx' }"
          />
        </view>
      </view>

      <view class="detail-row">
        <view class="detail-label">生产企业：</view>
        <view
          class="detail-value detail-wrap detail-company-value"
          :class="{ 'detail-clamp': !companyExpanded }"
          :style="{ marginBottom: needCompanyToggle ? '40rpx' : undefined }"
          id="companyValue"
        >
          <text>{{ data.produceEntName }}</text>
        </view>
        <text
          v-if="needCompanyToggle"
          class="detail-expand-tag"
          @click="toggleCompanyExpand"
          >{{ companyExpanded ? "收起" : "展开" }}</text
        >
      </view>
      <view class="detail-row">
        <view class="detail-label">批准文号：</view>
        <view class="detail-value">{{ data.approveNo }}</view>
      </view>
      <view class="detail-row">
        <view class="detail-label">生产日期：</view>
        <view class="detail-value">{{ data.produceDate }}</view>
      </view>
      <view class="detail-row" v-show="cardExpanded">
        <view class="detail-label">产品批号：</view>
        <view class="detail-value">{{ data.produceBatchNo }}</view>
      </view>
      <view class="detail-row" v-show="cardExpanded">
        <view class="detail-label">
          剂<text :style="{ opacity: 0 }">剂型</text>型：</view
        >
        <view class="detail-value">{{ data.prepnDesc }}</view>
      </view>
      <view class="detail-row" v-show="cardExpanded">
        <view class="detail-label">包装规格：</view>
        <view class="detail-value">{{ data.prepnSpec }}</view>
      </view>
      <view class="detail-row" v-show="cardExpanded">
        <view class="detail-label">有效期至：</view>
        <view class="detail-value">{{ data.validEndDate }}</view>
      </view>
      <view class="detail-card-toggle" @click="toggleCardExpand">
        <uni-icons
          :type="cardExpanded ? 'up' : 'down'"
          size="18"
          color="#9aa4b2"
        ></uni-icons>
      </view>
    </view>

    <view
      class="detail-timeline detail-bg"
      :style="{ backgroundImage: 'url(' + bg + ')' }"
    >
      <view class="detail-section-header">
        <view class="detail-section-title">扫码跟踪</view>
        <!-- <view class="detail-section-actions">
          <view
            class="detail-section-action"
            @tap="toggleTimelineView"
          >
            <uni-icons
              :type="timelineView === 'text' ? 'image' : 'list'"
              size="20"
              color="#59a8f2"
            ></uni-icons>
            <text>{{
              timelineView === "text" ? "查看图形" : "查看文字"
            }}</text>
          </view>
          <view class="detail-section-action" @tap="onSetDefaultView">
            <uni-icons type="gear" size="20" color="#59a8f2"></uni-icons>
            <text>设置默认</text>
          </view>
        </view> -->
      </view>
      <view class="detail-graph-placeholder" v-if="timelineView === 'graph'">
        图形视图占位区域
      </view>
      <view class="detail-timeline-toolbar" v-if="timelineView === 'text'">
        <view class="detail-toolbar-btn" @tap.stop="setAllTimelineDetail(true)"
          >全部展示详情</view
        >
        <view class="detail-toolbar-btn" @tap.stop="setAllTimelineDetail(false)"
          >全部展示概要</view
        >
      </view>
      <view
        v-if="timelineView === 'text'"
        class="detail-timeline-item"
        :class="{ 'detail-timeline-item-first': i === 0 }"
        v-for="(value, i) in data.billDetailList"
        :key="i"
      >
        <view class="detail-left">
          <view class="detail-dot" :class="{ 'detail-fill': false }"></view>
          <view
            class="detail-line"
            v-if="i < (data.billDetailList || []).length - 1"
          ></view>
        </view>
        <view class="detail-right">
          <view class="detail-title-row">
            <view class="detail-title" :class="{ 'detail-bold': true }">
              {{ value.billTypeName || "--" }} {{ value.billCode || "" }}
            </view>
            <view class="detail-item-toggle" @tap.stop="toggleTimelineItem(i)">
              {{ value._showDetail ? "概要" : "详情" }}
              <uni-icons
                :type="value._showDetail ? 'up' : 'down'"
                size="14"
                color="#888"
              ></uni-icons>
            </view>
          </view>
          <view class="detail-info-row">
            <text class="detail-info-label">发货企业：</text>
            <text class="detail-info-value">{{ value.fromEntName || "--" }}</text>
          </view>
          <view class="detail-tag-row" v-if="value._showDetail">
            <text class="detail-tag" v-if="value.fromEntTypeName">{{
              value.fromEntTypeName
            }}</text>
            <text class="detail-tag detail-tag-region" v-if="getRegionByPrefix(value, 'from')">{{
              getRegionByPrefix(value, "from")
            }}</text>
          </view>
          <view class="detail-info-row">
            <text class="detail-info-label">收货企业：</text>
            <text class="detail-info-value">{{ value.toEntName || "--" }}</text>
          </view>
          <view class="detail-tag-row" v-if="value._showDetail">
            <text class="detail-tag" v-if="value.toEntTypeName">{{
              value.toEntTypeName
            }}</text>
            <text class="detail-tag detail-tag-region" v-if="getRegionByPrefix(value, 'to')">{{
              getRegionByPrefix(value, "to")
            }}</text>
          </view>
          <view class="detail-info-row">
            <text class="detail-info-label">入出库时间：</text>
            <text class="detail-info-value">{{ value.billTime || "--" }}</text>
          </view>
          <view class="detail-info-row">
            <text class="detail-info-label">上传企业：</text>
            <text class="detail-info-value">{{
              value.uploadEntName || "--"
            }}</text>
          </view>
          <view class="detail-tag-row" v-if="value._showDetail">
            <text class="detail-tag" v-if="value.uploadEntTypeName">{{
              value.uploadEntTypeName
            }}</text>
            <text class="detail-tag detail-tag-region" v-if="getRegionByPrefix(value, 'upload')">{{
              getRegionByPrefix(value, "upload")
            }}</text>
          </view>
          <view class="detail-info-row">
            <text class="detail-info-label">上传时间：</text>
            <text class="detail-info-value">{{ value.uploadTime || "--" }}</text>
          </view>
        </view>
      </view>
    </view>
  </view>
  <view
    class="detail-page-empty"
    :style="{ height: pageHeight }"
    v-if="!data && !loading"
  >
    <image
      src="../../../static/images/empty.png"
      mode="scaleToFill"
      :style="{ width: '264rpx', height: '200rpx' }"
    />
    <text
      :style="{
        fontSize: '24rpx',
        color: '#99a1ad',
        marginTop: '60rpx',
        textAlign: 'center',
      }"
      >所查询药品所在生产企业尚未纳入扫码范围，后续将进一步扩大，敬请期待</text
    >
  </view>
  <view
    class="detail-page-empty"
    :style="{ height: pageHeight }"
    v-if="loading"
  >
    <image
      src="../../../static/images/loading.png"
      mode="scaleToFill"
      :style="{ width: '50rpx', height: '50rpx' }"
      class="detail-loading"
    />
  </view>
</template>

<script>
import bg from "../../../static/images/bg.png";
import { formatDate } from "../../../utils/utils.js";
import request from "../../../request/index.js";
import Water from "@/components/water/water.vue";
export default {
  components: {
    Water,
  },
  data() {
    return {
      data: null,
      loading: true,
      statusBarHeight: 20,
      traceCode: "",
      pageHeight: 0,
      bg,
      companyExpanded: true,
      needCompanyToggle: false,
      cardExpanded: false,
      allTimelineDetail: true,
      timelineView: "text",
      defaultTimelineViewKey: "traceabilityCodeQuery.detail.timelineDefaultView",
    };
  },
  onLoad(options) {
    const info = uni.getSystemInfoSync();
    this.statusBarHeight = info.statusBarHeight || 20;
    this.pageHeight = (info.windowHeight && info.windowHeight + "px") || "100%";
    if (options.traceCode) {
      this.traceCode = options.traceCode;
    }
    const defaultView = uni.getStorageSync(this.defaultTimelineViewKey);
    if (defaultView === "graph" || defaultView === "text") {
      this.timelineView = defaultView;
    }
    // this.getData(options.traceCode);
    this.getData2(options.traceCode);
  },
  onReady() {
    this.$nextTick(() => {
      const info = uni.getSystemInfoSync();
      const lineHeightPx = (info.windowWidth / 750) * 40;
      this.companyExpanded = true; // 展开测量高度
      uni
        .createSelectorQuery()
        .in(this)
        .select("#companyValue")
        .boundingClientRect((rect) => {
          if (!rect || !lineHeightPx) return;
          const lines = Math.round(rect.height / lineHeightPx);
          this.needCompanyToggle = lines > 2;
          this.companyExpanded = !this.needCompanyToggle;
        })
        .exec();
    });
  },
  methods: {
    formatDate(date) {
      return formatDate({ date }, "YYYY-MM-DD");
    },
    getRegion(value = {}) {
      const { provinceDesc, cityDesc, areaDesc } = value;
      return (
        [provinceDesc, cityDesc, areaDesc].filter(Boolean).join("，") || ""
      );
    },
    getRegionByPrefix(value = {}, prefix = "from") {
      const province = value[`${prefix}ProvinceDesc`];
      const city = value[`${prefix}CityDesc`];
      const area = value[`${prefix}AreaDesc`];
      return [province, city, area].filter(Boolean).join("-") || "";
    },
    toggleTimelineItem(index) {
      if (!this.data || !Array.isArray(this.data.billDetailList)) return;
      const item = this.data.billDetailList[index];
      if (!item) return;
      this.$set(item, "_showDetail", !item._showDetail);
    },
    setAllTimelineDetail(showDetail) {
      this.allTimelineDetail = !!showDetail;
      if (!this.data || !Array.isArray(this.data.billDetailList)) return;
      this.data.billDetailList.forEach((item) => {
        if (item) this.$set(item, "_showDetail", !!showDetail);
      });
    },
    toggleTimelineView() {
      this.timelineView = this.timelineView === "text" ? "graph" : "text";
    },
    onSetDefaultView() {
      uni.setStorageSync(this.defaultTimelineViewKey, this.timelineView);
      uni.showToast({
        title: "已设为默认",
        icon: "none",
      });
    },
    getData2(traceCode) {
      request("/bills/scanCode2", {
        tracCode: traceCode,
        path: "/traceabilityCodeQuery/pages/detail/index.vue",
      }).then((res) => {
        if (res.code == 200) {
          const _data = res.data;
          this.data = _data || null;
          if (this.data && Array.isArray(this.data.billDetailList)) {
            this.data.billDetailList = this.data.billDetailList.map((item) => ({
              ...item,
              _showDetail: !!this.allTimelineDetail,
            }));
          }
          if (
            typeof _data === "object" &&
            Object.values(_data).filter((i) => !!i).length == 0
          ) {
            this.data = null;
          }
          this.loading = false;
        } else {
          uni.showToast({ title: "查询失败", icon: "none" });
        }
      });
    },
    getData(traceCode) {
      request("/bills/scanCode", {
        tracCode: traceCode,
        path: "/traceabilityCodeQuery/pages/detail/index.vue",
      }).then((res) => {
        if (res.code == 200) {
          const _data = res.data;
          this.data = _data || null;
          if (
            typeof _data === "object" &&
            Object.values(_data).filter((i) => !!i).length == 0
          ) {
            this.data = null;
          }
          this.loading = false;
        } else {
          uni.showToast({ title: "查询失败", icon: "none" });
        }
      });
    },
    copy(text) {
      const data = String(text || this.traceCode);
      uni.setClipboardData({
        data,
        success: () => {
          console.log(
            "packages/traceabilityCodeQuery/pages/detail/index.vue" +
              "storage" +
              "clipboardData",
          );
          uni.showToast({
            title: "已复制追溯码",
            icon: "none",
            duration: 2000,
          });
        },
      });
    },
    toggleCompanyExpand() {
      if (!this.needCompanyToggle) return;
      this.companyExpanded = !this.companyExpanded;
    },
    toggleCardExpand() {
      this.cardExpanded = !this.cardExpanded;
    },
    formatTraceCode(traceCode) {
      return String(traceCode || "")
        .replace(/(.{5})/g, "$1 ")
        .trim();
    },
  },
};
</script>

<style>
.detail-bg {
  background-position: center top;
  background-size: 100% auto;
}

.detail-page {
  box-sizing: border-box;
  background: rgb(226 226 226);
  padding-bottom: 50rpx;
  overflow: auto;
}

.detail-page-empty {
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 0 136rpx 280rpx;
}

.detail-card {
  padding: 40rpx;
}

.detail-drug-title {
  font-size: 45rpx;
  font-weight: 800;
  color: #000;
  margin-bottom: 16rpx;
}

.detail-row {
  position: relative;
  display: flex;
  margin-top: 12rpx;
  align-items: baseline;
}

.detail-label {
  flex-shrink: 0;
  display: inline-block;
  vertical-align: baseline;
  width: 150rpx;
  font-size: 28rpx;
}

.detail-value {
  display: inline-block;
  vertical-align: baseline;
  font-size: 28rpx;
}

.detail-company-value {
  line-height: 40rpx;
}

.detail-company-value.detail-clamp {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}

.detail-expand-tag {
  position: absolute;
  left: 150rpx;
  bottom: 0;
  color: #2c69ff;
  font-size: 28rpx;
}

.detail-value.detail-wrap {
  word-break: break-all;
  white-space: normal;
}

.detail-copy-btn {
  margin-left: 16rpx;
  display: flex;
  align-items: center;
  color: #2c69ff;
}

.detail-copy-text {
  margin-left: 6rpx;
  font-size: 26rpx;
}

.detail-traceability {
  font-size: 24rpx;
  margin: -10rpx 0 45rpx;
}

.detail-card-toggle {
  display: flex;
  justify-content: center;
  align-items: center;
  padding-top: 18rpx;
}

.detail-traceability .detail-label {
  width: auto;
}

.detail-section-header {
  padding: 30rpx 24rpx 20rpx 46rpx;
  border-bottom: 1rpx solid #55555526;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.detail-section-title {
  font-size: 35rpx;
  font-weight: 900;
}

.detail-section-actions {
  display: flex;
  align-items: center;
  gap: 12rpx;
}

.detail-section-action {
  font-size: 26rpx;
  color: #59a8f2;
  padding: 4rpx 6rpx;
  display: flex;
  align-items: center;
  gap: 6rpx;
}

.detail-section-action.active {
  color: #2c69ff;
  font-weight: 600;
}

.detail-timeline {
  margin-top: 20rpx;
  padding-bottom: 50rpx;
}

.detail-graph-placeholder {
  margin: 16rpx 20rpx 0;
  background: #fff;
  border-radius: 14rpx;
  font-size: 24rpx;
  text-align: center;
  color: #97a0ae;
  padding: 120rpx 20rpx;
}

.detail-timeline-toolbar {
  display: flex;
  gap: 16rpx;
  padding: 20rpx 32rpx 10rpx;
}

.detail-toolbar-btn {
  padding: 8rpx 18rpx;
  border: 1rpx solid #d8dbe0;
  border-radius: 999rpx;
  color: #666;
  font-size: 24rpx;
  background: #fff;
}

.detail-timeline-item {
  position: relative;
  display: flex;
  margin-left: 36rpx;
}

.detail-timeline-item-first {
  margin-top: 20rpx;
}

.detail-left {
  position: absolute;
  top: 34rpx;
  left: 0;
  height: 100%;
  display: flex;
  align-items: center;
  flex-direction: column;
}

.detail-dot {
  width: 16rpx;
  height: 16rpx;
  border-radius: 50%;
  border: 2rpx solid #2c69ff;
}

.detail-dot.detail-fill {
  background: #2c69ff;
  border-color: #2c69ff;
}

.detail-line {
  width: 2rpx;
  flex: 1;
  background: #8face68f;
  margin-right: 2rpx;
}

.detail-right {
  flex: 1;
  padding: 20rpx 0;
  margin-left: 45rpx;
  border-bottom: 1rpx solid #55555526;
}

.detail-title-row {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 16rpx;
}

.detail-title {
  font-size: 32rpx;
  color: #333;
}

.detail-title.detail-bold {
  font-weight: 800;
}

.detail-item-toggle {
  flex-shrink: 0;
  padding: 6rpx 12rpx;
  border: 1rpx solid #d8dbe0;
  border-radius: 999rpx;
  font-size: 22rpx;
  color: #666;
  display: flex;
  align-items: center;
  gap: 6rpx;
}

.detail-info-row {
  display: flex;
  margin-top: 10rpx;
  font-size: 28rpx;
  color: #444;
}

.detail-info-label {
  color: #666;
  flex-shrink: 0;
}

.detail-info-value {
  color: #333;
  word-break: break-all;
}

.detail-tag-row {
  display: flex;
  flex-wrap: wrap;
  gap: 10rpx;
  margin-top: 8rpx;
  padding-left: 130rpx;
}

.detail-tag {
  background: #fff7df;
  color: #ecb640;
  border-radius: 8rpx;
  padding: 5rpx 14rpx;
  font-size: 22rpx;
  border: 1rpx solid #f3d9a1;
}

.detail-tag-region {
  background: #f5f5f5;
  color: #999;
  border: 1rpx solid #d8dbe0;
}

.detail-text-red {
  color: red;
}

.detail-loading {
  animation: spin 1s linear infinite;
}

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

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