<template>
  <div class="home">
    <nav-bar title="物价查询" />
    
    <!-- 分类切换 - 优化样式 -->
    <div class="category-tabs">
      <div 
        class="category-item" 
        :class="{ active: params.CLASSIFY === '1', loading: loading }"
        @click="params.CLASSIFY = '1'; handleCategoryChange()"
        :disabled="loading"
      >
        药品
      </div>
      <div 
        class="category-item" 
        :class="{ active: params.CLASSIFY === '2', loading: loading }"
        @click="params.CLASSIFY = '2'; handleCategoryChange()"
        :disabled="loading"
      >
        诊疗项目
      </div>
    </div>
    
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-box">
        <i class="icon-search" />
        <input 
          type="text" 
          v-model="params.ITEMINPUTCODE" 
          placeholder="请输入名称拼音或首字母查询"
          @keyup.enter="handleSearch"
          @blur="handleSearch" 
          :disabled="loading"
        />
        <van-loading 
          color="#36bffa" 
          size="20" 
          v-if="loading && params.ITEMINPUTCODE" 
          class="search-loading"
        />
      </div>
    </div>
    
    <!-- 结果列表 - 添加单位列 -->
    <div class="result-container">
      <!-- 加载遮罩层 - 用于分类切换和搜索时的过渡效果 -->
      <div 
        class="loading-overlay" 
        v-if="loading && dataList.length > 0"
      >
        <van-loading color="#36bffa" size="40" />
      </div>
      
      <!-- 初始加载状态 -->
      <div class="initial-loading" v-if="loading && dataList.length === 0">
        <van-loading color="#36bffa" size="50" />
        <p class="loading-text">正在加载数据...</p>
      </div>
      
      <!-- 空状态 -->
      <div class="empty-state" v-if="!loading && total === 0">
        <van-empty description="暂无查询结果" />
      </div>
      
      <!-- 列表内容 -->
      <div class="result-card" v-if="dataList.length > 0 || loading">
        <div class="list-wrapper" :style="pullStyle">
          <ul 
            class="result-list" 
            @scroll="handleScroll"
            @touchstart="handleTouchStart"
            @touchmove="handleTouchMove"
            @touchend="handleTouchEnd"
            :class="{ 'list-fade': loading && dataList.length > 0 }"
          >
            <li class="list-header">
              <div class="col name">名称</div>
              <div class="col spec">规格</div>
              <div class="col unit">单位</div>
              <div class="col price">价格(元)</div>
              <div class="col type">类型</div>
            </li>
            
            <li class="list-item" v-for="(item, index) in dataList" :key="index">
              <div class="col name">
                <div class="item-name">{{ item.ITEMNAME }}</div>
                <div class="item-code">{{ item.ITEMCODE }}</div>
              </div>
              <div class="col spec">{{ item.ITEMSPEC || '-' }}</div>
              <div class="col unit">{{ item.ITEMUNIT || '-' }}</div>
              <div class="col price">{{ item.ITEMPRICE }}</div>
              <div class="col type">{{ item.ITEMTYPE }}</div>
            </li>
          </ul>
          
          <!-- 底部加载提示区域 -->
          <div class="pull-indicator" :class="{ active: pullDistance > 0 || loadingMore }">
            <div v-if="!loadingMore && !isLastPage">
              <i class="icon-arrow-up" :class="{ rotate: pullDistance >= pullThreshold }"></i>
              <span v-if="pullDistance < pullThreshold">上拉加载更多</span>
              <span v-else>松开加载下一页</span>
            </div>
            <div v-if="!loadingMore && isLastPage" class="no-more">
              已显示全部内容
            </div>
            <van-loading color="#36bffa" size="20" v-if="loadingMore" />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { apiGetDrugPrice } from "@/request/api.js";
import { Loading, Empty } from "vant";

export default {
  components: {
    [Loading.name]: Loading,
    [Empty.name]: Empty
  },
  data() {
    return {
      params: {
        CLASSIFY: '1',  // 默认选中药品
        ITEMINPUTCODE: '',
        page: 1,
        size: 20,
      },
      dataList: [],
      total: 0,
      totalPages: 0,
      loading: false,
      loadingMore: false,
      isLastPage: false,
      
      // 触摸相关变量
      isTouching: false,
      startY: 0,
      startX: 0,
      pullDistance: 0,
      pullThreshold: 50,
      maxPullDistance: 150,
      isAtBottom: false,
      isDraggingVertically: null,
    };
  },

  computed: {
    // 上拉拖动的样式
    pullStyle() {
      let effectiveDistance = this.pullDistance;
      if (this.pullDistance > this.pullThreshold) {
        effectiveDistance = this.pullThreshold + (this.pullDistance - this.pullThreshold) * 0.5;
      }
      
      if (effectiveDistance > 0 && (this.isAtBottom || this.pullDistance > 0) && !this.loadingMore) {
        return {
          transform: `translateY(-${effectiveDistance}px)`,
          transition: this.isTouching ? 'none' : 'transform 0.3s cubic-bezier(0.18, 0.89, 0.32, 1.28)',
          boxShadow: this.pullDistance > 0 ? '0 -4px 12px rgba(0, 0, 0, 0.05)' : 'none'
        };
      }
      return {
        transform: 'translateY(0)',
        transition: 'transform 0.3s cubic-bezier(0.18, 0.89, 0.32, 1.28)',
        boxShadow: 'none'
      };
    }
  },

  mounted() {
    this.$nextTick(() => {
      this.calculateResultContainerHeight();
      this.queryData();
    });
  },

  methods: {
    calculateResultContainerHeight() {
      const navBarHeight = document.querySelector('nav-bar')?.offsetHeight || 0;
      const categoryHeight = document.querySelector('.category-tabs')?.offsetHeight || 0;
      const searchContainerHeight = document.querySelector('.search-container')?.offsetHeight || 0;
      
      const totalTopHeight = navBarHeight + categoryHeight + searchContainerHeight;
      
      const resultContainer = document.querySelector('.result-container');
      if (resultContainer) {
        resultContainer.style.height = `calc(100vh - ${totalTopHeight}px)`;
      }
    },
    
    // 分类切换时触发
    handleCategoryChange() {
      this.params.page = 1;
      this.isLastPage = false;
      this.queryData();  // 切换分类后自动查询
    },
    
    // 查询数据
queryData(isLoadMore = false) {
  if (isLoadMore) {
    this.loadingMore = true;
  } else {
    this.loading = true;  // 开始加载，显示加载效果
  }
  
  apiGetDrugPrice(this.params)
    .then(res => {
      this.loading = false;   // 加载完成，隐藏加载效果
      this.loadingMore = false;
      this.pullDistance = 0;
      
      // 数据过滤逻辑
      let filteredData = res.data.data || [];
      const inputCode = this.params.ITEMINPUTCODE?.trim();
      
      if (inputCode) {
        // 提取输入中的汉字（用于混合类型处理）
        const chineseChars = inputCode.match(/[\u4e00-\u9fa5]/g)?.join('') || '';
        // 判断是否纯字母
        const isPureLetter = /^[A-Za-z]+$/.test(inputCode);
        // 判断是否汉字+字母混合（既有汉字也有字母）
        const isChineseWithLetter = chineseChars && inputCode.replace(/[\u4e00-\u9fa5]/g, '').match(/[A-Za-z]/);
        
        filteredData = filteredData.filter(item => {
          const itemName = String(item.ITEMNAME || '').toLowerCase();
          const itemInputCode = String(item.ITEMINPUTCODE || '').toLowerCase();
          const target = inputCode.toLowerCase();
          
          // 1. 纯字母：模糊匹配ITEMINPUTCODE
          if (isPureLetter) {
            return itemInputCode.includes(target);
          }
          
          // 2. 汉字+字母混合：只取汉字部分模糊匹配ITEMNAME
          if (isChineseWithLetter && chineseChars) {
            return itemName.includes(chineseChars.toLowerCase());
          }
          
          // 3. 纯汉字：模糊匹配ITEMNAME（保持原有逻辑）
          if (chineseChars && !isChineseWithLetter) {
            return itemName.includes(target);
          }
          
          // 其他情况返回所有数据
          return true;
        });
      }

      // 添加名称替换逻辑
      filteredData = filteredData.map(item => {
        // 替换包含"右短崛∥锲?乙"的名称为"杏叶提取物片-乙"
        if (item.ITEMNAME && item.ITEMNAME.includes("右短崛∥锲?乙")) {
          return {
            ...item,
            ITEMNAME: "杏叶提取物片-乙"
          };
        }
        return item;
      });
      
      if (res.code === 200 && res.data.returncode === "1") {
        // 为新数据添加淡入动画
        if (!isLoadMore) {
          this.dataList = [];
          // 使用setTimeout确保DOM更新后再添加数据，触发动画
          setTimeout(() => {
            this.dataList = filteredData;
          }, 50);
        } else {
          this.dataList = [...this.dataList, ...filteredData];
        }
        
        this.total = res.data.total || 0;
        this.totalPages = res.data.totalPages || 0;
        this.isLastPage = this.params.page >= this.totalPages;
      } else {
        if (!isLoadMore) {
          this.dataList = [];
          this.total = 0;
        }
        this.$toast(res.data.errormsg || "查询失败");
      }
    })
    .catch(err => {
      this.loading = false;    // 加载失败，隐藏加载效果
      this.loadingMore = false;
      this.pullDistance = 0;
      
      if (!isLoadMore) {
        this.dataList = [];
        this.total = 0;
      }
      
      this.$toast("网络错误，请稍后重试");
      console.error(err);
    });
},

    // 搜索处理
    handleSearch() {
      // 防止频繁搜索
      if (this.searchTimer) {
        clearTimeout(this.searchTimer);
      }
      
      this.searchTimer = setTimeout(() => {
        this.params.page = 1;
        this.isLastPage = false;
        this.queryData();
      }, 300);  // 300ms防抖
    },

    // 滚动处理
    handleScroll(e) {
      const { scrollTop, scrollHeight, clientHeight } = e.target;
      this.isAtBottom = (scrollTop + clientHeight) >= (scrollHeight - 30);
    },

    // 触摸开始
    handleTouchStart(e) {
      if (!this.loading && !this.loadingMore) {
        this.isTouching = true;
        this.startY = e.touches[0].clientY;
        this.startX = e.touches[0].clientX;
        this.startPullDistance = this.pullDistance;
        this.isDraggingVertically = null;
      }
    },

    // 触摸移动
    handleTouchMove(e) {
      if (this.isTouching && !this.loading && !this.loadingMore) {
        const currentY = e.touches[0].clientY;
        const currentX = e.touches[0].clientX;
        const deltaY = this.startY - currentY;
        const deltaX = Math.abs(currentX - this.startX);
        const newDistance = this.startPullDistance + deltaY;
        
        if (this.isDraggingVertically === null) {
          if (Math.abs(deltaY) > 10 || deltaX > 10) {
            this.isDraggingVertically = Math.abs(deltaY) > deltaX;
          }
        }
        
        if (this.isDraggingVertically && this.isAtBottom && newDistance > 0) {
          this.pullDistance = Math.min(newDistance, this.maxPullDistance);
          e.preventDefault();
        } else if (!this.isDraggingVertically && this.isDraggingVertically !== null) {
          this.pullDistance = 0;
        }
      }
    },

    // 触摸结束
    handleTouchEnd() {
      if (this.isTouching) {
        this.isTouching = false;
        this.isDraggingVertically = null;
        
        if (this.isAtBottom && this.pullDistance >= this.pullThreshold && !this.loadingMore && !this.isLastPage) {
          setTimeout(() => {
            this.params.page++;
            this.queryData(true);
          }, 150);
        } else {
          this.pullDistance = 0;
        }
      }
    }
  },
};
</script>

<style scoped lang="scss">
// 基础变量
$primary-color: #36bffa;
$primary-dark: #2594d8;
$text-primary: #1d2129;
$text-secondary: #4e5969;
$text-tertiary: #86909c;
$border-color: #e5e6eb;
$light-bg: #f2f3f5;
$card-shadow: 0 2px 14px rgba(0, 0, 0, 0.06);
$transition-base: all 0.25s ease;

.home {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  height: 100vh;
}

// 分类切换样式 - 优化版
.category-tabs {
  padding: 0.1rem 0.2667rem;
  background-color: #fff;
  border-bottom: 1px solid $border-color;
  display: flex;
  justify-content: center;
  
  .category-item {
    padding: 0.2rem 0.6rem;
    margin: 0.1rem 0.15rem;
    border-radius: 2rem;
    font-size: 0.38rem;
    color: $text-secondary;
    cursor: pointer;
    transition: all 0.3s ease;
    position: relative;
    overflow: hidden;
    user-select: none;
    
    &::after {
      content: '';
      position: absolute;
      bottom: 0;
      left: 0;
      width: 0;
      height: 2px;
      background-color: $primary-color;
      transition: width 0.3s ease;
    }
    
    &:hover {
      color: $primary-color;
    }
    
    &.active {
      color: $primary-color;
      font-weight: 500;
      
      &::after {
        width: 100%;
      }
    }
    
    // 加载状态样式
    &.loading {
      opacity: 0.7;
      cursor: not-allowed;
    }
  }
}

// 搜索区域样式
.search-container {
  padding: 0.2667rem;
  background-color: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);

  .search-box {
    display: flex;
    align-items: center;
    background-color: $light-bg;
    border-radius: 0.2rem;
    padding: 0 0.3rem;
    height: 0.9rem;
    transition: $transition-base;
    width: 100%;

    &:focus-within {
      box-shadow: 0 0 0 2px rgba(54, 191, 250, 0.2);
    }

    .icon-search {
      color: $text-tertiary;
      margin-right: 0.2rem;
      width: 0.4rem;
      height: 0.4rem;
      background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='2'%3E%3Ccircle cx='11' cy='11' r='8'/%3E%3Cpath d='m21 21-4.3-4.3'/%3E%3C/svg%3E") no-repeat center;
    }

    input {
      flex: 1;
      border: none;
      background: transparent;
      outline: none;
      font-size: 0.38rem;
      color: $text-primary;
      height: 100%;
      letter-spacing: 0.005rem;

      &::placeholder {
        color: $text-tertiary;
        font-size: 0.35rem;
      }
      
      &:disabled {
        opacity: 0.7;
        cursor: not-allowed;
      }
    }
    
    .search-loading {
      margin-left: 0.2rem;
    }
  }
}

// 加载遮罩层 - 用于数据更新时的过渡效果
.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.7);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 100;
  transition: opacity 0.3s ease;
}

// 初始加载状态
.initial-loading {
  padding: 1.3333rem 0;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  
  .loading-text {
    margin-top: 0.2rem;
    color: $text-tertiary;
    font-size: 0.32rem;
    animation: fadeIn 0.6s ease-in-out;
  }
}

// 结果区域
.result-container {
  flex: 1;
  width: 100%;
  padding: 0.2667rem;
  box-sizing: border-box;
  overflow: hidden;
  position: relative;
}

.result-card {
  height: 100%;
  min-height: 0;
  background-color: #fff;
  border-radius: 0.2667rem;
  box-shadow: $card-shadow;
  overflow: hidden;
  position: relative;
}

.empty-state {
  padding: 1.3333rem 0;
  display: flex;
  justify-content: center;
}

// 列表外层容器
.list-wrapper {
  width: 100%;
  transition: transform 0.3s cubic-bezier(0.18, 0.89, 0.32, 1.28), 
              box-shadow 0.3s ease;
  height: 100%;
}

.result-list {
  width: 100%;
  margin: 0;
  padding: 0;
  list-style: none;
  overflow-y: auto;
  overflow-x: hidden;
  scroll-behavior: smooth;
  height: 100%;
  scrollbar-width: none;
  -ms-overflow-style: none;
  transition: opacity 0.3s ease;
  
  &::-webkit-scrollbar {
    display: none;
  }
  
  // 列表加载时的淡入效果
  &.list-fade {
    opacity: 0.5;
  }
}

// 上拉提示指示器
.pull-indicator {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  height: 0;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
  color: $text-tertiary;
  font-size: 0.28rem;
  transition: height 0.2s ease-out, padding 0.2s ease-out, opacity 0.2s ease;
  padding: 0;
  background-color: #fff;
  border-top: 1px solid $border-color;
  opacity: 0;
  
  &.active {
    height: 1rem;
    padding: 0.2rem 0;
    opacity: 1;
  }
  
  .icon-arrow-up {
    display: inline-block;
    width: 0.3rem;
    height: 0.3rem;
    margin-right: 0.1rem;
    background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='2'%3E%3Cpath d='m5 15 7-7 7 7'/%3E%3C/svg%3E") no-repeat center;
    transition: transform 0.2s ease;
    transform-origin: center;
  }
  
  .icon-arrow-up.rotate {
    transform: rotate(180deg);
  }
  
  .no-more {
    color: $text-tertiary;
    font-size: 0.28rem;
  }
}

.list-header {
  display: flex;
  padding: 0.2667rem 0.3333rem;
  background-color: $light-bg;
  font-weight: 600;
  font-size: 0.32rem;
  color: $text-secondary;
  border-bottom: 1px solid $border-color;
  position: sticky;
  top: 0;
  z-index: 10;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.02);
}

.list-item {
  display: flex;
  padding: 0.3rem 0.3333rem;
  border-bottom: 1px solid $border-color;
  font-size: 0.32rem;
  transition: background-color 0.2s ease, transform 0.15s ease, opacity 0.3s ease;
  align-items: center;
  transform: translateX(0);
  will-change: transform, background-color;
  animation: fadeIn 0.3s ease-out;

  &:last-child {
    border-bottom: none;
  }

  &:hover {
    background-color: rgba(54, 191, 250, 0.03);
  }
}

.col {
  flex-shrink: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  line-height: 1.5;
  white-space: normal;
  word-break: break-word;
  padding: 0 0.1rem;
}

.name {
  width: 35%;
}

.spec {
  width: 20%;
}

.unit {
  width: 10%;
}

.price {
  width: 15%;
  color: #f53f3f;
  font-weight: 600;
  font-size: 0.35rem;
}

.type {
  width: 20%;
}

.item-name {
  color: $text-primary;
  margin-bottom: 0.1rem;
  font-weight: 500;
  font-size: 0.35rem;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.item-code {
  font-size: 0.2667rem;
  color: $text-tertiary;
}

// 适配小屏幕
@media (max-width: 768px) {
  .result-list {
    .col {
      font-size: 0.3rem;
    }
    
    .name {
      width: 32%;
    }
    
    .spec {
      width: 20%;
    }
    
    .unit {
      width: 10%;
    }
    
    .price {
      width: 16%;
    }
    
    .type {
      width: 22%;
    }
  }
}

// 动画效果
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>
