<template>
  <view class="container">
    <!-- 轮播图 -->
    <swiper class="cattle-swiper" :indicator-dots="true" :autoplay="true" :interval="3000" :duration="1000">
      <swiper-item v-for="(image, index) in cattleDetail.images" :key="index">
        <image :src="image" mode="aspectFill" class="swiper-image" @click="previewImage(index)"></image>
      </swiper-item>
    </swiper>

    <!-- 基本信息 -->
    <view class="info-section">
      <view class="cattle-header">
        <view class="cattle-title">
          <text class="breed-name">{{ cattleDetail.breed }}</text>
          <view class="cattle-status" :class="cattleDetail.status">
            {{ getStatusText(cattleDetail.status) }}
          </view>
        </view>
        <view class="cattle-price">
          <text class="price-label">价格：</text>
          <text class="price-value">¥{{ cattleDetail.price }}</text>
        </view>
      </view>

      <view class="cattle-basic-info">
        <view class="info-row">
          <view class="info-item">
            <text class="info-label">年龄</text>
            <text class="info-value">{{ cattleDetail.age }}月龄</text>
          </view>
          <view class="info-item">
            <text class="info-label">重量</text>
            <text class="info-value">{{ cattleDetail.weight }}kg</text>
          </view>
        </view>
        <view class="info-row">
          <view class="info-item">
            <text class="info-label">性别</text>
            <text class="info-value">{{ cattleDetail.gender }}</text>
          </view>
          <view class="info-item">
            <text class="info-label">健康状况</text>
            <text class="info-value">{{ cattleDetail.healthStatus }}</text>
          </view>
        </view>
        <view class="info-row">
          <view class="info-item">
            <text class="info-label">疫苗接种</text>
            <text class="info-value">{{ cattleDetail.vaccination ? '已接种' : '未接种' }}</text>
          </view>
          <view class="info-item">
            <text class="info-label">出生日期</text>
            <text class="info-value">{{ cattleDetail.birthDate }}</text>
          </view>
        </view>
      </view>

      <view class="location-info">
        <uni-icons type="location" size="16" color="#666"></uni-icons>
        <text class="location-text">{{ cattleDetail.location }}</text>
        <text class="distance-text">距离您 {{ cattleDetail.distance }}km</text>
      </view>
    </view>

    <!-- 详细描述 -->
    <view class="description-section">
      <view class="section-title">详细描述</view>
      <view class="description-content">
        <text class="description-text">{{ cattleDetail.description }}</text>
      </view>
    </view>

    <!-- 健康证明 -->
    <view class="certificate-section" v-if="cattleDetail.certificates && cattleDetail.certificates.length > 0">
      <view class="section-title">健康证明</view>
      <scroll-view class="certificate-list" scroll-x="true">
        <view 
          class="certificate-item" 
          v-for="(cert, index) in cattleDetail.certificates" 
          :key="index"
          @click="previewCertificate(index)"
        >
          <image :src="cert.image" mode="aspectFill" class="certificate-image"></image>
          <text class="certificate-name">{{ cert.name }}</text>
        </view>
      </scroll-view>
    </view>

    <!-- 卖家信息 -->
    <view class="seller-section">
      <view class="section-title">卖家信息</view>
      <view class="seller-info">
        <view class="seller-avatar">
          <image :src="cattleDetail.seller.avatar" mode="aspectFill" class="avatar-image"></image>
        </view>
        <view class="seller-details">
          <view class="seller-name">{{ cattleDetail.seller.name }}</view>
          <view class="seller-stats">
            <text class="stat-item">信用等级：{{ cattleDetail.seller.creditLevel }}</text>
            <text class="stat-item">成交次数：{{ cattleDetail.seller.dealCount }}次</text>
          </view>
          <view class="seller-location">
            <uni-icons type="location" size="12" color="#999"></uni-icons>
            <text>{{ cattleDetail.seller.location }}</text>
          </view>
        </view>
        <view class="seller-actions">
          <button class="action-btn call" @click="callSeller">
            <uni-icons type="phone" size="16" color="#fff"></uni-icons>
            <text>电话</text>
          </button>
          <button class="action-btn message" @click="messageSeller">
            <uni-icons type="chat" size="16" color="#007AFF"></uni-icons>
            <text>私信</text>
          </button>
        </view>
      </view>
    </view>

    <!-- 相似推荐 -->
    <view class="recommend-section" v-if="recommendList.length > 0">
      <view class="section-title">相似推荐</view>
      <scroll-view class="recommend-list" scroll-x="true">
        <view 
          class="recommend-item" 
          v-for="item in recommendList" 
          :key="item.id"
          @click="navigateToDetail(item.id)"
        >
          <image :src="item.image" mode="aspectFill" class="recommend-image"></image>
          <view class="recommend-info">
            <text class="recommend-breed">{{ item.breed }}</text>
            <text class="recommend-price">¥{{ item.price }}</text>
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 底部操作栏 -->
    <view class="bottom-actions">
      <view class="action-left">
        <button class="action-btn favorite" @click="toggleFavorite">
          <uni-icons 
            :type="cattleDetail.isFavorite ? 'heart-filled' : 'heart'" 
            size="20" 
            :color="cattleDetail.isFavorite ? '#ff4757' : '#666'"
          ></uni-icons>
          <text :class="{ active: cattleDetail.isFavorite }">收藏</text>
        </button>
        <button class="action-btn share" @click="shareCattle">
          <uni-icons type="redo" size="20" color="#666"></uni-icons>
          <text>分享</text>
        </button>
      </view>
      <view class="action-right">
        <button class="contact-btn" @click="contactSeller">立即联系</button>
        <button class="buy-btn" @click="showPurchasePopup = true" v-if="cattleDetail.status === 'available'">
          立即购买
        </button>
      </view>
    </view>

    <!-- 购买弹窗 -->
    <uni-popup ref="purchasePopup" type="bottom" :mask-click="false">
      <view class="purchase-popup">
        <view class="popup-header">
          <text class="popup-title">确认购买</text>
          <text class="popup-close" @click="showPurchasePopup = false">关闭</text>
        </view>
        <view class="purchase-content">
          <view class="cattle-summary">
            <image :src="cattleDetail.images[0]" mode="aspectFill" class="summary-image"></image>
            <view class="summary-info">
              <text class="summary-breed">{{ cattleDetail.breed }}</text>
              <text class="summary-details">{{ cattleDetail.age }}月龄 · {{ cattleDetail.weight }}kg · {{ cattleDetail.gender }}</text>
              <text class="summary-price">¥{{ cattleDetail.price }}</text>
            </view>
          </view>
          
          <view class="purchase-form">
            <view class="form-item">
              <text class="form-label">联系人</text>
              <input 
                type="text" 
                placeholder="请输入联系人姓名" 
                v-model="purchaseForm.contactName"
                class="form-input"
              />
            </view>
            <view class="form-item">
              <text class="form-label">联系电话</text>
              <input 
                type="tel" 
                placeholder="请输入联系电话" 
                v-model="purchaseForm.contactPhone"
                class="form-input"
              />
            </view>
            <view class="form-item">
              <text class="form-label">收货地址</text>
              <textarea 
                placeholder="请输入详细收货地址" 
                v-model="purchaseForm.address"
                class="form-textarea"
              ></textarea>
            </view>
            <view class="form-item">
              <text class="form-label">备注信息</text>
              <textarea 
                placeholder="请输入备注信息（选填）" 
                v-model="purchaseForm.remark"
                class="form-textarea"
              ></textarea>
            </view>
          </view>
        </view>
        <view class="popup-footer">
          <button class="cancel-btn" @click="showPurchasePopup = false">取消</button>
          <button class="confirm-btn" @click="confirmPurchase">确认购买</button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
export default {
  name: 'CattleDetail',
  data() {
    return {
      cattleId: '',
      showPurchasePopup: false,
      
      cattleDetail: {
        id: 1,
        breed: '西门塔尔牛',
        age: 18,
        weight: 450,
        gender: '母牛',
        price: 12000,
        location: '内蒙古呼和浩特市',
        distance: 15.6,
        healthStatus: '健康',
        vaccination: true,
        birthDate: '2022-07-15',
        status: 'available',
        description: '这是一头优质的西门塔尔母牛，体格健壮，毛色纯正，无疾病史。已完成所有疫苗接种，健康证明齐全。适合繁殖或育肥，是您养殖场的理想选择。牛只性情温顺，易于管理，产奶量高，是优秀的种牛。',
        images: [
          '/static/images/cattle1.jpg',
          '/static/images/cattle1-2.jpg',
          '/static/images/cattle1-3.jpg'
        ],
        certificates: [
          {
            name: '健康证明',
            image: '/static/images/health-cert.jpg'
          },
          {
            name: '疫苗接种证',
            image: '/static/images/vaccine-cert.jpg'
          }
        ],
        seller: {
          id: 1,
          name: '张三养殖场',
          avatar: '/static/images/seller-avatar.jpg',
          creditLevel: 'AAA',
          dealCount: 156,
          location: '内蒙古呼和浩特市',
          phone: '13800138000'
        },
        isFavorite: false,
        publishTime: '2024-01-15 10:30:00'
      },
      
      recommendList: [
        {
          id: 2,
          breed: '安格斯牛',
          price: 15000,
          image: '/static/images/cattle2.jpg'
        },
        {
          id: 3,
          breed: '夏洛莱牛',
          price: 13500,
          image: '/static/images/cattle3.jpg'
        }
      ],
      
      purchaseForm: {
        contactName: '',
        contactPhone: '',
        address: '',
        remark: ''
      }
    }
  },
  
  onLoad(options) {
    if (options.id) {
      this.cattleId = options.id;
      this.loadCattleDetail();
    }
  },
  
  onShow() {
    // 页面显示时可以刷新数据
  },
  
  watch: {
    showPurchasePopup(val) {
      if (val) {
        this.$refs.purchasePopup.open();
      } else {
        this.$refs.purchasePopup.close();
      }
    }
  },
  
  methods: {
    // 加载牛只详情
    async loadCattleDetail() {
      try {
        uni.showLoading({
          title: '加载中...'
        });
        
        // TODO: 调用API获取牛只详情
        console.log('加载牛只详情:', this.cattleId);
        
        // 模拟API调用
        await this.simulateApiCall();
        
        uni.hideLoading();
      } catch (error) {
        console.error('加载牛只详情失败:', error);
        uni.hideLoading();
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        });
      }
    },
    
    // 模拟API调用
    async simulateApiCall() {
      return new Promise(resolve => {
        setTimeout(resolve, 1000);
      });
    },
    
    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        available: '在售',
        sold: '已售',
        reserved: '预定'
      };
      return statusMap[status] || '未知';
    },
    
    // 预览图片
    previewImage(index) {
      uni.previewImage({
        urls: this.cattleDetail.images,
        current: index
      });
    },
    
    // 预览证书
    previewCertificate(index) {
      const urls = this.cattleDetail.certificates.map(cert => cert.image);
      uni.previewImage({
        urls: urls,
        current: index
      });
    },
    
    // 拨打电话
    callSeller() {
      uni.makePhoneCall({
        phoneNumber: this.cattleDetail.seller.phone
      });
    },
    
    // 发送私信
    messageSeller() {
      // TODO: 跳转到聊天页面
      uni.showToast({
        title: '私信功能开发中',
        icon: 'none'
      });
    },
    
    // 联系卖家
    contactSeller() {
      uni.showActionSheet({
        itemList: ['拨打电话', '发送私信'],
        success: (res) => {
          if (res.tapIndex === 0) {
            this.callSeller();
          } else if (res.tapIndex === 1) {
            this.messageSeller();
          }
        }
      });
    },
    
    // 切换收藏状态
    async toggleFavorite() {
      try {
        // TODO: 调用API切换收藏状态
        this.cattleDetail.isFavorite = !this.cattleDetail.isFavorite;
        
        uni.showToast({
          title: this.cattleDetail.isFavorite ? '收藏成功' : '取消收藏',
          icon: 'success'
        });
      } catch (error) {
        console.error('切换收藏状态失败:', error);
        uni.showToast({
          title: '操作失败',
          icon: 'none'
        });
      }
    },
    
    // 分享牛只
    shareCattle() {
      uni.share({
        provider: 'weixin',
        scene: 'WXSceneSession',
        type: 0,
        href: `pages/detail/detail?id=${this.cattleId}`,
        title: `${this.cattleDetail.breed} - ¥${this.cattleDetail.price}`,
        summary: this.cattleDetail.description,
        imageUrl: this.cattleDetail.images[0],
        success: () => {
          uni.showToast({
            title: '分享成功',
            icon: 'success'
          });
        },
        fail: (error) => {
          console.error('分享失败:', error);
          uni.showToast({
            title: '分享失败',
            icon: 'none'
          });
        }
      });
    },
    
    // 导航到详情页
    navigateToDetail(cattleId) {
      uni.navigateTo({
        url: `/pages/detail/detail?id=${cattleId}`
      });
    },
    
    // 确认购买
    async confirmPurchase() {
      // 表单验证
      if (!this.purchaseForm.contactName.trim()) {
        uni.showToast({
          title: '请输入联系人姓名',
          icon: 'none'
        });
        return;
      }
      
      if (!this.purchaseForm.contactPhone.trim()) {
        uni.showToast({
          title: '请输入联系电话',
          icon: 'none'
        });
        return;
      }
      
      if (!this.purchaseForm.address.trim()) {
        uni.showToast({
          title: '请输入收货地址',
          icon: 'none'
        });
        return;
      }
      
      // 验证手机号格式
      const phoneRegex = /^1[3-9]\d{9}$/;
      if (!phoneRegex.test(this.purchaseForm.contactPhone)) {
        uni.showToast({
          title: '请输入正确的手机号',
          icon: 'none'
        });
        return;
      }
      
      try {
        uni.showLoading({
          title: '提交中...'
        });
        
        // TODO: 调用API提交购买订单
        const orderData = {
          cattleId: this.cattleId,
          ...this.purchaseForm
        };
        
        console.log('提交购买订单:', orderData);
        
        // 模拟API调用
        await this.simulateApiCall();
        
        uni.hideLoading();
        this.showPurchasePopup = false;
        
        uni.showModal({
          title: '购买成功',
          content: '您的购买意向已提交，卖家将尽快与您联系',
          showCancel: false,
          success: () => {
            // 可以跳转到订单页面
            uni.navigateTo({
              url: '/pages/order/order'
            });
          }
        });
        
      } catch (error) {
        console.error('提交购买订单失败:', error);
        uni.hideLoading();
        uni.showToast({
          title: '提交失败',
          icon: 'none'
        });
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 120rpx;
}

/* 轮播图 */
.cattle-swiper {
  width: 100%;
  height: 500rpx;
  
  .swiper-image {
    width: 100%;
    height: 100%;
  }
}

/* 信息区域 */
.info-section {
  background-color: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
  
  .cattle-header {
    margin-bottom: 30rpx;
    
    .cattle-title {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20rpx;
      
      .breed-name {
        font-size: 36rpx;
        font-weight: bold;
        color: #333;
      }
      
      .cattle-status {
        padding: 8rpx 20rpx;
        border-radius: 25rpx;
        font-size: 24rpx;
        color: #fff;
        
        &.available {
          background-color: #52c41a;
        }
        
        &.sold {
          background-color: #ff4d4f;
        }
        
        &.reserved {
          background-color: #faad14;
        }
      }
    }
    
    .cattle-price {
      .price-label {
        font-size: 28rpx;
        color: #666;
      }
      
      .price-value {
        font-size: 40rpx;
        font-weight: bold;
        color: #ff4757;
      }
    }
  }
  
  .cattle-basic-info {
    margin-bottom: 30rpx;
    
    .info-row {
      display: flex;
      margin-bottom: 20rpx;
      
      .info-item {
        flex: 1;
        display: flex;
        flex-direction: column;
        
        .info-label {
          font-size: 24rpx;
          color: #999;
          margin-bottom: 8rpx;
        }
        
        .info-value {
          font-size: 28rpx;
          color: #333;
          font-weight: 500;
        }
      }
    }
  }
  
  .location-info {
    display: flex;
    align-items: center;
    
    .location-text {
      font-size: 26rpx;
      color: #666;
      margin-left: 8rpx;
    }
    
    .distance-text {
      font-size: 24rpx;
      color: #999;
      margin-left: 20rpx;
    }
  }
}

/* 通用区域样式 */
.description-section,
.certificate-section,
.seller-section,
.recommend-section {
  background-color: #fff;
  margin-bottom: 20rpx;
  
  .section-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    padding: 30rpx 30rpx 20rpx;
    border-bottom: 1rpx solid #f0f0f0;
  }
}

/* 详细描述 */
.description-section {
  .description-content {
    padding: 30rpx;
    
    .description-text {
      font-size: 28rpx;
      color: #666;
      line-height: 1.6;
    }
  }
}

/* 健康证明 */
.certificate-section {
  .certificate-list {
    padding: 30rpx;
    white-space: nowrap;
    
    .certificate-item {
      display: inline-block;
      margin-right: 20rpx;
      text-align: center;
      
      .certificate-image {
        width: 120rpx;
        height: 120rpx;
        border-radius: 10rpx;
        margin-bottom: 10rpx;
      }
      
      .certificate-name {
        font-size: 24rpx;
        color: #666;
        display: block;
      }
    }
  }
}

/* 卖家信息 */
.seller-section {
  .seller-info {
    display: flex;
    align-items: center;
    padding: 30rpx;
    
    .seller-avatar {
      margin-right: 20rpx;
      
      .avatar-image {
        width: 80rpx;
        height: 80rpx;
        border-radius: 50%;
      }
    }
    
    .seller-details {
      flex: 1;
      
      .seller-name {
        font-size: 30rpx;
        font-weight: bold;
        color: #333;
        margin-bottom: 10rpx;
      }
      
      .seller-stats {
        display: flex;
        gap: 20rpx;
        margin-bottom: 10rpx;
        
        .stat-item {
          font-size: 24rpx;
          color: #666;
        }
      }
      
      .seller-location {
        display: flex;
        align-items: center;
        
        text {
          font-size: 24rpx;
          color: #999;
          margin-left: 8rpx;
        }
      }
    }
    
    .seller-actions {
      display: flex;
      flex-direction: column;
      gap: 15rpx;
      
      .action-btn {
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 15rpx 25rpx;
        border-radius: 30rpx;
        font-size: 24rpx;
        border: none;
        
        text {
          margin-left: 8rpx;
        }
        
        &.call {
          background-color: #52c41a;
          color: #fff;
        }
        
        &.message {
          background-color: #f0f9ff;
          color: #007AFF;
        }
      }
    }
  }
}

/* 相似推荐 */
.recommend-section {
  .recommend-list {
    padding: 30rpx;
    white-space: nowrap;
    
    .recommend-item {
      display: inline-block;
      width: 200rpx;
      margin-right: 20rpx;
      
      .recommend-image {
        width: 100%;
        height: 150rpx;
        border-radius: 10rpx;
        margin-bottom: 10rpx;
      }
      
      .recommend-info {
        .recommend-breed {
          font-size: 26rpx;
          color: #333;
          display: block;
          margin-bottom: 5rpx;
        }
        
        .recommend-price {
          font-size: 24rpx;
          color: #ff4757;
          font-weight: bold;
        }
      }
    }
  }
}

/* 底部操作栏 */
.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 20rpx 30rpx;
  border-top: 1rpx solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  .action-left {
    display: flex;
    gap: 30rpx;
    
    .action-btn {
      display: flex;
      flex-direction: column;
      align-items: center;
      background: none;
      border: none;
      padding: 0;
      
      text {
        font-size: 22rpx;
        color: #666;
        margin-top: 5rpx;
        
        &.active {
          color: #ff4757;
        }
      }
    }
  }
  
  .action-right {
    display: flex;
    gap: 20rpx;
    
    .contact-btn,
    .buy-btn {
      padding: 20rpx 40rpx;
      border-radius: 50rpx;
      font-size: 28rpx;
      border: none;
    }
    
    .contact-btn {
      background-color: #f0f9ff;
      color: #007AFF;
    }
    
    .buy-btn {
      background-color: #ff4757;
      color: #fff;
    }
  }
}

/* 购买弹窗 */
.purchase-popup {
  background-color: #fff;
  border-radius: 40rpx 40rpx 0 0;
  max-height: 80vh;
  
  .popup-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 40rpx;
    border-bottom: 1rpx solid #eee;
    
    .popup-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
    
    .popup-close {
      font-size: 28rpx;
      color: #007AFF;
    }
  }
  
  .purchase-content {
    padding: 40rpx;
    max-height: 50vh;
    overflow-y: auto;
    
    .cattle-summary {
      display: flex;
      padding: 30rpx;
      background-color: #f9f9f9;
      border-radius: 20rpx;
      margin-bottom: 40rpx;
      
      .summary-image {
        width: 120rpx;
        height: 120rpx;
        border-radius: 10rpx;
        margin-right: 20rpx;
      }
      
      .summary-info {
        flex: 1;
        
        .summary-breed {
          font-size: 28rpx;
          font-weight: bold;
          color: #333;
          margin-bottom: 10rpx;
        }
        
        .summary-details {
          font-size: 24rpx;
          color: #666;
          margin-bottom: 10rpx;
        }
        
        .summary-price {
          font-size: 30rpx;
          font-weight: bold;
          color: #ff4757;
        }
      }
    }
    
    .purchase-form {
      .form-item {
        margin-bottom: 30rpx;
        
        .form-label {
          font-size: 28rpx;
          color: #333;
          margin-bottom: 15rpx;
          display: block;
        }
        
        .form-input,
        .form-textarea {
          width: 100%;
          padding: 20rpx;
          border: 1rpx solid #ddd;
          border-radius: 10rpx;
          font-size: 28rpx;
          box-sizing: border-box;
        }
        
        .form-textarea {
          height: 120rpx;
          resize: none;
        }
      }
    }
  }
  
  .popup-footer {
    display: flex;
    gap: 20rpx;
    padding: 40rpx;
    border-top: 1rpx solid #eee;
    
    .cancel-btn,
    .confirm-btn {
      flex: 1;
      padding: 25rpx;
      border-radius: 50rpx;
      font-size: 28rpx;
      border: none;
    }
    
    .cancel-btn {
      background-color: #f5f5f5;
      color: #666;
    }
    
    .confirm-btn {
      background-color: #ff4757;
      color: #fff;
    }
  }
}
</style>