<template>
  <div class="component-market">
    <!-- 顶部搜索和筛选区域 -->
    <div class="search-bar">
      <el-input v-model="searchKeyword"
                placeholder="搜索组件"
                class="search-input"
                :prefix-icon="Search" />
      <el-select v-model="selectedCategory"
                 placeholder="组件分类"
                 class="category-select">
        <el-option v-for="item in categories"
                   :key="item.value"
                   :label="item.label"
                   :value="item.value" />
      </el-select>
    </div>

    <!-- 组件列表区域 -->
    <div class="component-grid">
      <el-card v-for="item in filteredComponents"
               :key="item.id"
               class="component-card">
        <div class="component-info">
          <h3>{{ item.name }}</h3>
          <div class="card-author">
            <el-avatar :size="24" :src="item.author?.avatar || defaultAvatar"></el-avatar>
            <span>huiteng</span>
          </div>
          <p class="description">{{ item.description }}</p>
          <div class="price-row">
            <span class="price">￥{{ item.price }}</span>
            <div class="button-group">
              <el-button @click="showDetail(item)">查看详情</el-button>
              <el-button type="primary"
                         @click="handlePurchase(item)">购买</el-button>
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 详情对话框 -->
    <el-dialog v-model="detailVisible"
               :title="selectedComponent?.name"
               width="500px"
               class="component-detail-dialog">
      <div class="component-detail"
           v-if="selectedComponent">
        <div class="detail-info">
          <div class="author-info">
            <div class="author-content">
              <el-avatar :size="50"
                         :src="selectedComponent.author?.avatar || defaultAvatar"></el-avatar>
              <div class="author-details">
                <div class="author-name">开发者</div>
                <div class="author-desc">huiteng</div>
              </div>
            </div>
          </div>
          <h2>{{ selectedComponent.name }}</h2>
          <div class="detail-price">￥{{ selectedComponent.price }}</div>
          <div class="detail-category">
            <el-tag>{{ getCategoryLabel(selectedComponent.category) }}</el-tag>
          </div>
          <div class="detail-description">
            <h3>组件描述</h3>
            <p>{{ selectedComponent.description }}</p>
          </div>
          <div class="detail-features">
            <h3>主要特性</h3>
            <ul>
              <li v-for="(feature, index) in selectedComponent.features"
                  :key="index">
                {{ feature }}
              </li>
            </ul>
          </div>
          <div class="detail-actions">
            <el-button type="primary"
                       size="large"
                       @click="handlePurchase(selectedComponent)">
              立即购买
            </el-button>
            <el-button size="large"
                       @click="showDemo(selectedComponent)"
                       v-if="selectedComponent.demo">
              查看演示
            </el-button>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 购买确认对话框 -->
    <el-dialog v-model="dialogVisible"
               title="订单支付"
               width="400px"
               class="pay-dialog">
      <div class="purchase-dialog">
        <p class="purchase-title">{{ selectedComponent?.name }}</p>
        <p class="confirm-price">￥{{ selectedComponent?.price }}</p>

        <!-- 支付方式选择 -->
        <div class="payment-method"
             v-if="!qrCodeUrl">
          <p class="method-title">请选择支付方式</p>
          <div class="method-options">
            <div class="method-item"
                 :class="{'is-active': payMethod === 1}"
                 @click="payMethod = 1">
              <svg-icon icon-class="wechat"
                        class="pay-icon"></svg-icon>
              <span>微信支付</span>
            </div>
            <div class="method-item"
                 :class="{'is-active': payMethod === 0}"
                 @click="payMethod = 0">
              <svg-icon icon-class="alipay"
                        class="pay-icon"></svg-icon>
              <span>支付宝</span>
            </div>
          </div>
        </div>

        <!-- 支付二维码 -->
        <div v-if="qrCodeUrl"
             class="qr-code">
          <el-image :src="qrCodeUrl"
                    fit="contain" />
          <p class="qr-tip">请使用{{ payMethod === 1 ? '微信' : '支付宝' }}扫码支付</p>
        </div>

        <!-- 加载状态 -->
        <div v-if="loading"
             class="loading-wrap">
          <el-icon class="is-loading">
            <loading />
          </el-icon>
          <span>正在获取支付信息...</span>
        </div>
      </div>
      <template #footer
                v-if="!qrCodeUrl">
        <span class="dialog-footer">
          <el-button @click="cancelPurchase">取消</el-button>
          <el-button type="primary"
                     @click="confirmPurchase"
                     :loading="loading">
            确认支付
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { Search, Loading } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'

// 组件分类
const categories = [
  { label: '全部', value: 'all' },
  { label: '底层控件', value: 'controls' }
]

// 组件列表数据
const componentList = ref([])

// 获取组件数据
const fetchComponentData = async () => {
  try {
    const response = await axios.get('https://api.avuejs.com/get/version', {
      params: {
        key: '0901D35BFEBD2795DC15EBAADA146580'
      }
    })

    if (response.data.code === 200) {
      componentList.value = response.data.data
        .filter(item => item.category)
        .map(item => ({
          id: item.value,
          name: item.label.replace('AVUE-DATA大屏', '').replace('AVUE-DATA', ''),
          description: item.description || item.desc || '',
          price: item.money,
          category: item.category,
          demo: item.demo,
          features: item.features || [],
          author: {
            name: item.author || '匿名作者',
            avatar: item.authorAvatar,
            description: item.authorDesc || '该作者暂无介绍'
          }
        }))
    }
  } catch (error) {
    console.error('获取组件数据失败:', error)
    ElMessage.error('获取组件数据失败')
  }
}

// 在组件挂载时获取数据
onMounted(() => {
  fetchComponentData()
})

const searchKeyword = ref('')
const selectedCategory = ref('all')
const dialogVisible = ref(false)
const selectedComponent = ref(null)
const detailVisible = ref(false)
const payMethod = ref(1) // 默认微信支付
const qrCodeUrl = ref('')
const loading = ref(false)
const orderId = ref('')
const payTimer = ref(null) // 用于存储轮询定时器

// API 基础URL
const BASE_API_URL = 'https://api.avuejs.com'

// API 相关函数
const fetchPayInfo = async (params) => {
  return axios.post(`${BASE_API_URL}/payinfo`, params)
}

const fetchPayStatus = async (id) => {
  return axios.get(`${BASE_API_URL}/paydetail`, {
    params: { id }
  })
}

// 过滤后的组件列表
const filteredComponents = computed(() => {
  return componentList.value.filter(item => {
    const matchKeyword = item.name.includes(searchKeyword.value) ||
      item.description.includes(searchKeyword.value)
    const matchCategory = selectedCategory.value === 'all' ||
      item.category === selectedCategory.value
    return matchKeyword && matchCategory
  })
})

// 生成订单ID
const generateOrderId = () => {
  const timestamp = new Date().getTime()
  const random = Math.floor(Math.random() * 1000)
  return `ORDER${timestamp}${random}`
}

// 处理购买点击
const handlePurchase = (component) => {
  selectedComponent.value = component
  payMethod.value = 1 // 重置为默认支付方式
  qrCodeUrl.value = '' // 清空二维码
  orderId.value = generateOrderId() // 生成单号
  dialogVisible.value = true
}


// 查询支付状态
const checkPayStatus = async () => {
  try {
    const res = await fetchPayStatus(orderId.value)

    if (res.data && res.data.flag === true) {
      this.$alert(
        '<div style="text-align:center"><img src="https://avuejs.com/images/wechat.jpg" style="width:200px" /><p>请扫描上方二维码联系客服</p></div>', 
        '提示', 
        {
          confirmButtonText: '确定',
          dangerouslyUseHTMLString: true
        }
      );
      clearPayTimer()
      dialogVisible.value = false
    }
  } catch (error) {
    console.error('查询支付状态错误:', error)
    clearPayTimer()
  }
}

// 清除轮询定时器
const clearPayTimer = () => {
  if (payTimer.value) {
    clearInterval(payTimer.value)
    payTimer.value = null
  }
}

// 确认购买
const confirmPurchase = async () => {
  if (loading.value) return

  loading.value = true
  try {
    const res = await fetchPayInfo({
      orderid: orderId.value,
      type: payMethod.value,
      version: selectedComponent.value.id
    })
    if (res.data && res.data.data) {
      qrCodeUrl.value = res.data.data.data
      clearPayTimer()
      payTimer.value = setInterval(checkPayStatus, 1000)
    } else {
      ElMessage.error('获取支付二维码失败')
    }
  } catch (error) {
    console.error('支付接口错误:', error)
    ElMessage.error('支付接口异常')
  } finally {
    loading.value = false
  }
}

// 取消购买
const cancelPurchase = () => {
  dialogVisible.value = false
  qrCodeUrl.value = ''
  clearPayTimer() // 取消时清除定时器
}

// 显示详情
const showDetail = (component) => {
  selectedComponent.value = component
  detailVisible.value = true
}

// 获取分类标签
const getCategoryLabel = (value) => {
  const category = categories.find(item => item.value === value)
  return category ? category.label : value
}

// 查看演示
const showDemo = (component) => {
  if (component.demo) {
    window.open(component.demo, '_blank')
  } else {
    ElMessage.info('暂无演示视频')
  }
}

// 组件卸载时清除定时器
onUnmounted(() => {
  clearPayTimer()
})

const defaultAvatar = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
</script>

<style scoped>
.component-market {
  padding: 20px;
}

.search-bar {
  display: flex;
  gap: 20px;
  margin-bottom: 30px;
}

.search-input {
  width: 300px;
}

.category-select {
  width: 200px;
}

.component-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.component-card {
  transition: transform 0.3s;
}

.component-card:hover {
  transform: translateY(-5px);
}

.component-info {
  padding: 15px 0;
}

.description {
  color: var(--text-color-disabled);
  margin: 10px 0;
  height: 40px;
  overflow: hidden;
  font-size: 14px;
}

.price-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 15px;
}

.price {
  color: var(--danger-color);
  font-size: 20px;
  font-weight: bold;
}

.purchase-dialog {
  text-align: center;
  padding: 20px 0;
}

.purchase-title {
  font-size: 18px;
  color: var(--text-color-primary);
  margin-bottom: 10px;
}

.confirm-price {
  color: var(--danger-color);
  font-size: 18px;
  margin-top: 10px;
}

/* 添加详情对话框样式 */
.component-detail {
  display: flex;
  gap: 30px;
}

.detail-info {
  flex: 1;
}

.detail-info h2 {
  margin: 0 0 15px 0;
  font-size: 24px;
  color: var(--text-color-primary);
}

.detail-price {
  font-size: 28px;
  color: var(--danger-color);
  font-weight: bold;
  margin-bottom: 15px;
}

.detail-category {
  margin-bottom: 20px;
}

.detail-description {
  margin-bottom: 20px;
}

.detail-description h3,
.detail-features h3 {
  font-size: 16px;
  margin-bottom: 10px;
  color: var(--text-color-secondary);
}

.detail-features ul {
  padding-left: 20px;
  margin: 0;
}

.detail-features li {
  line-height: 1.8;
  color: var(--text-color-secondary);
}

.detail-actions {
  margin-top: 30px;
  display: flex;
  gap: 15px;
}

/* 让卡片可点击 */
.component-card {
  cursor: default;
}

/* 调整对话框样式 */
:deep(.el-dialog__body) {
  padding: 20px 30px;
}

.price-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 15px;
}

.button-group {
  display: flex;
  gap: 8px;
}

.payment-method {
  margin: 20px 0;
  text-align: left;
}

.method-title {
  font-size: 14px;
  color: var(--text-color-secondary);
  margin-bottom: 10px;
}

.method-options {
  display: flex;
  gap: 15px;
}

.method-item {
  flex: 1;
  height: 60px;
  border: 1px solid var(--border-color-light);
  border-radius: 4px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s;
}

.method-item:hover {
  border-color: var(--active-color);
}

.method-item.is-active {
  border-color: var(--active-color);
  background-color: var(--active-bg);
}

/* 微信支付样式 */
.method-item:nth-child(1) {
  --active-color: #07c160;
  --active-bg: rgba(7, 193, 96, 0.1);
}

/* 支付宝样式 */
.method-item:nth-child(2) {
  --active-color: #1677ff;
  --active-bg: rgba(22, 119, 255, 0.1);
}

.method-item .pay-icon {
  font-size: 24px;
  margin-bottom: 4px;
  color: var(--active-color);
  width: 24px;
  height: 24px;
}

.qr-code {
  width: 200px;
  margin: 20px auto;
}

.qr-code img {
  width: 100%;
  height: 100%;
}

.qr-tip {
  font-size: 14px;
  color: var(--text-color-disabled);
  margin-top: 10px;
}

.loading-wrap {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  color: var(--text-color-disabled);
  margin: 20px 0;
}

.loading-wrap .el-icon {
  font-size: 20px;
}

/* 支付对话框标题样式 */
:deep(.pay-dialog .el-dialog__title) {
  color: var(--text-color-primary);
}

:deep(.pay-dialog .el-dialog__header) {
  border-bottom: 1px solid var(--border-color-light);
}

:deep(.pay-dialog .el-dialog__headerbtn .el-dialog__close) {
  color: var(--text-color-primary);
}

/* 作者信息样式 */
.author-info {
  margin: 20px 0;
  padding: 15px;
  background: var(--bg-color-tertiary);
  border-radius: 8px;
}

.author-info h3 {
  font-size: 16px;
  color: var(--el-text-color-primary);
  margin-bottom: 15px;
}

.author-content {
  display: flex;
  align-items: center;
  gap: 15px;
}

.author-details {
  flex: 1;
}

.author-name {
  font-size: 16px;
  font-weight: 500;
  color: var(--el-text-color-primary);
  margin-bottom: 4px;
}

.author-desc {
  font-size: 14px;
  color: var(--el-text-color-secondary);
  line-height: 1.4;
}

.card-author {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 8px 0;
  color: var(--el-text-color-secondary);
  font-size: 14px;
}

.card-author .el-avatar {
  border: 1px solid var(--el-border-color-lighter);
}
</style> 