<template>
  <div class="app-container computing-resource">

    <div class="top-banner-list flex-justify-center">
      <div class="banner-item flex-align-center">
        <img src="@/assets/images/superior-performance.png" alt="">
        <div>
          <h3>性能优越</h3>
          <p>
            提供多种产品配置
            <br>
            满足个性化需求</p>
        </div>
      </div>

      <div class="banner-item flex-align-center">
        <img src="@/assets/images/intelligent-computing.png" alt="">
        <div>
          <h3>智能计算</h3>
          <p>
            提供多种产品配置
            <br>
            满足个性化需求</p>
        </div>
      </div>

      <div class="banner-item flex-align-center">
        <img src="@/assets/images/innovative-design.png" alt="">
        <div>
          <h3>创新设计</h3>
          <p>
            提供多种产品配置
            <br>
            满足个性化需求</p>
        </div>
      </div>
    </div>

    <div class="info-content">
      <div class="switch-display" @click="showVersion = (showVersion === 1 ? 2 : 1)">
        <svg-icon v-show="showVersion === 2" color="#2E77E3" icon-class="list-1"/>
        <svg-icon v-show="showVersion === 1" color="#2E77E3" icon-class="table"/>
      </div>
      <el-tabs v-model="tabActive" @tab-change="tabChange">
        <el-tab-pane
            v-for="productType in productTypes"
            :key="productType.id"
            :label="productType.name"
            :name="productType.id">
          <div v-if="showVersion === 1" class="version-1">
            <el-table v-if="tableData.length !== 0" :data="tableData" :max-height="490" style="width: 100%">
              <el-table-column prop="name" label="型号" width="190px" sortable/>
              <el-table-column prop="cpu" label="CPU" sortable/>
              <el-table-column prop="gpu" label="GPU" sortable/>
              <el-table-column prop="ram" label="内存" sortable/>
              <el-table-column prop="storage" label="存储" sortable/>
              <el-table-column prop="location" label="所在地" sortable/>
              <!-- 新增的价格列（醒目字体） -->
              <el-table-column label="价格" width="200px">
                <template #default="{ row }">
                  <span style="font-weight: 600; font-size: 16px; color: #FF9811;">
                    ￥{{ row.price ? (row.price / 100).toFixed(2) : '-' }}
                  </span>
                                <span style="margin-left: 4px; font-size: 14px; color: #606266;">
                    /{{ row.feeInfo }}
                  </span>
                </template>
              </el-table-column>

              <el-table-column label="操作" width="204px">
                <template #default="{row}">
                  <!--                  <el-button class="action-button" @click="selectedProduct(1,row.id)">加入购物车</el-button>-->
                  <el-button type="primary" class="action-button" @click="selectedProduct(2,row.id)">立即购买
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-empty v-if="tableData.length === 0" description="暂无资源"/>
          </div>
          <!--卡片形式-->
          <div v-if="showVersion === 2" class="version-2">
            <el-row :gutter="24" v-if="tableData.length !== 0">
              <el-col v-for="(item,index) in tableData" :key="index" :span="6">
                <div class="product-card">
                  <div class="top-info">
                    <div class="title">{{ item.name }}</div>
                    <!--                    <div class="title">{{ item.term }}</div>-->
                    <div class="tag">
                      <!--<el-tag type="warning" effect="dark">性价比</el-tag>-->
                      <!--<el-tag type="info" effect="plain">专家推荐</el-tag>-->
                    </div>
                    <div class="desc">{{ item.remark }}</div>
                  </div>
                  <div class="bottom-info">
                    <el-row>
                      <el-col>
                        <div class="parameter-item">
                          <div class="label">CPU</div>
                          <div class="value">{{ item.cpu || '-' }}</div>
                        </div>
                      </el-col>
                      <el-col>
                        <div class="parameter-item">
                          <div class="label">GPU</div>
                          <div class="value">{{ item.gpu || '-' }}</div>
                        </div>
                      </el-col>
                      <el-col>
                        <div class="parameter-item">
                          <div class="label">内存</div>
                          <div class="value">{{ item.ram || '-' }}</div>
                        </div>
                      </el-col>
                      <el-col>
                        <div class="parameter-item">
                          <div class="label">存储</div>
                          <div class="value">{{ item.storage || '-' }}</div>
                        </div>
                      </el-col>
                      <el-col>
                        <div class="parameter-item">
                          <div class="label">所在地</div>
                          <div class="value">{{ item.location || '-' }}</div>
                        </div>
                      </el-col>

                    </el-row>
                    <el-divider></el-divider>
                    <div class="flex-justify-end price">
                      ￥{{ item.price ? (item.price / 100).toFixed(2) : '-' }}/{{ item.feeInfo }}
                    </div>
                    <!--<div class="flex-justify-end month-expenses">约￥15/月</div>-->
                    <el-divider></el-divider>
                    <div class="footer-action flex">
                      <!--                      <el-button class="action-button" @click="selectedProduct(1,item.id)">加入购物车</el-button>-->
                      <el-button type="primary" class="action-button" @click="selectedProduct(2,item.id)">立即购买
                      </el-button>
                    </div>
                  </div>

                </div>
              </el-col>
            </el-row>
            <pagination
                v-show="total > 0"
                :total="total"
                v-model:page="pageNo"
                v-model:limit="pageSize"
                @pagination="getList"/>
            <el-empty v-if="tableData.length === 0" description="暂无资源"/>
          </div>

        </el-tab-pane>
      </el-tabs>
    </div>

    <el-drawer v-model="showDrawer" class="drawer" direction="rtl" :size="694" title="订单详情">
      <template #default>
        <div class="info-block">
          <div class="info-item flex-align-center flex-space-between">
            <div class="label">类别</div>
            <div class="value">{{ productDetail.name }}</div>
          </div>

          <div class="info-item  flex-align-center flex-space-between">
            <div class="label">型号</div>
            <div class="value">{{ productDetail.name }}</div>
          </div>

        </div>

        <div class="info-block">
          <div class="info-item flex-align-center flex-space-between">
            <div class="label">CPU</div>
            <div class="value">{{ productDetail.cpu || '-' }}</div>
          </div>
          <div class="info-item flex-align-center flex-space-between">
            <div class="label">GPU</div>
            <div class="value">{{ productDetail.gpu || '-' }}</div>
          </div>
          <div class="info-item flex-align-center flex-space-between">
            <div class="label">内存</div>
            <div class="value">{{ productDetail.ram || '-' }}</div>
          </div>
          <div class="info-item flex-align-center flex-space-between">
            <div class="label">存储</div>
            <div class="value">{{ productDetail.storage || '-' }}</div>
          </div>
          <!-- 服务器IP已隐藏 -->
          <!-- <div class="info-item flex-align-center flex-space-between">
            <div class="label">服务器IP</div>
            <div class="value">{{ productDetail.ip || '-' }}</div>
          </div> -->
          <div class="info-item flex-align-center flex-space-between">
            <div class="label">服务器所在地</div>
            <div class="value">{{ productDetail.location || '-' }}</div>
          </div>
        </div>

        <div class="info-block">

          <div class="info-item flex-align-center flex-space-between">
            <div class="label">使用数量（个）</div>
            <div class="value">
              <el-input-number v-model="form.num" :min="0" @change="orderComputerPrice" style="width: 110px" disabled/>
            </div>
          </div>
        </div>
      </template>
      <template #footer>
        <div class="checkbox-info">
          <el-checkbox v-model="checkbox" :value="true" size="large">
            <template #default>
              我已阅读和理解上述
            </template>
          </el-checkbox>
          <span class="link" @click="handleCheckProtocol">《购买协议》</span>
        </div>
        <el-divider style="margin: 0 !important;"/>
        <div class="drawer-footer flex-space-between flex-align-center">
          <div>应付配置费用</div>

          <div class="flex-align-center">
            <div class="mr20">
              <div class="price">￥{{ orderPrice / 100 }}</div>
            </div>
            <el-button type="primary" @click="create" :disabled="!checkbox">
              {{ selectedType === 1 ? '加入购物车' : '立即购买' }}
            </el-button>
          </div>
        </div>
      </template>
    </el-drawer>

    <!--    <div class="shopping-trolley" @click="$router.push('/computingResource/shoppingCart')">-->
    <!--      <el-icon size="24px">-->
    <!--        <ShoppingTrolley/>-->
    <!--      </el-icon>-->
    <!--      <div>购</div>-->
    <!--      <div>物</div>-->
    <!--      <div>车</div>-->
    <!--    </div>-->
    <el-dialog
        :title="qrCode.title"
        v-model="qrCode.visible"
        width="385px"
        append-to-body
        :align-center="true"
        :close-on-click-modal="false"
        @closed="clearQueryInterval"
    >
      <img :src="qrCode.url" alt=""/>
    </el-dialog>

    <el-dialog
        title="购买协议"
        v-model="protocol"
        width="800px"
        append-to-body
        :align-center="true"
        :close-on-click-modal="false"
        @closed="clearProtocol"
    >
      <div class="pdf-box">
        <!--        <div id="pdf-container" style="width: 100%; height: 100%;"></div>-->
        <iframe
            v-if="pdfUrl"
            :src="pdfUrl"
            style="width:100%; height:80vh;"
        ></iframe>
      </div>
    </el-dialog>

    </div>
</template>

<script name="ResourceList" setup>
import {ref, watch, nextTick} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import SvgIcon from '@/components/SvgIcon/index.vue'
import {
  getRListByCategory,
  getRDetail,
  categoryMenuNew,
  createOrderSubmit,
  createOrderSubmitWpgj,
  createPay
} from '@/api/computingResource.js'
import {useRoute, useRouter} from 'vue-router'
import QRCode from 'qrcode'
import request from '@/utils/request'
import {PayOrderStatusEnum} from "@/utils/constants.js";
import PDFObject from 'pdfobject';
import axios from "axios";

const route = useRoute()
const router = useRouter()

const showVersion = ref(2)
const tabActive = ref()
const total = ref(0)
const pageNo = ref(1)
const pageSize = ref(10)

const productTypes = ref([])
const tableData = ref([])
const interval = ref(undefined)
const checkbox = ref(false)
const protocol = ref(false)
const pdfBlobUrl = ref('');
const pdfUrl = ref(import.meta.env.VITE_APP_BASE_API+'/infra/file/preview?url=https://luhu-ltx.oss-cn-shenzhen.aliyuncs.com/20250918/buy_1758208746972.pdf')

const qrCode = ref({
  url: '',
  title: '请使用微信或支付宝扫码支付',
  visible: false
})


function getTypeData() {
  categoryMenuNew().then(res => {
    productTypes.value = res.data
    if (route.query.type) {
      tabActive.value = Number(route.query.type)
    } else {
      tabActive.value = Number(res.data[0].id)
    }
    getList()
  })
}

getTypeData()

watch(() => route.query.type, (value, oldValue) => {
  if (value) {
    tabActive.value = Number(value)
  }
})

async function handleCheckProtocol() {
  console.log('点击')
  protocol.value = true
  // nextTick(() => {
  //   PDFObject.embed("https://luhu-ltx.oss-cn-shenzhen.aliyuncs.com/20250828/文字文稿1_1756349853834.pdf", "#pdf-container", {
  //     height: "100%",
  //     pdfOpenParams: {
  //       view: "FitH",  // 页面适配
  //       pagemode: "none" // 隐藏侧边栏
  //     }
  //   });
  // })
  // try {
  //   // 这里用服务器给你的 PDF 地址
  //   const res = await axios.get(pdfUrl, {
  //     responseType: "blob",
  //   });
  //   console.log(res, 'res')
  //   if (res.headers["content-type"].includes("pdf")) {
  //     pdfBlobUrl.value = URL.createObjectURL(
  //         new Blob([res.data], {type: "application/pdf"})
  //     );
  //   } else {
  //     console.error("返回的不是 PDF 文件");
  //   }
  //   // pdfBlobUrl.value = URL.createObjectURL(
  //   //     new Blob([res.data], {type: "application/pdf"})
  //   // );
  // } catch (e) {
  //   console.error("加载PDF失败", e);
  // }
}

function tabChange() {
  pageNo.value = 1
  getList()
}

function getList() {
  getRListByCategory({categoryId: tabActive.value, pageNo: pageNo.value, pageSize: pageSize.value}).then(res => {
    total.value = res.data.total
    tableData.value = res.data.list
  })
}

const showDrawer = ref(false)
const form = ref({
  num: 1
})

const selectedType = ref()
const selectedId = ref()
const productDetail = ref({})

function selectedProduct(type, id) {
  selectedType.value = type
  selectedId.value = id
  getRDetail({id}).then(res => {
    productDetail.value = res.data
    orderPrice.value = res.data.price;
    showDrawer.value = true
  })
}

const orderPrice = ref(0)

function orderComputerPrice() {
  orderComputer(initSubmitData()).then(res => {
    orderPrice.value = res.data.totalPulicPrice
  })
}

function getCreateData() {
  return {
    skuId: selectedId.value,
  }
}

function create() {
  // 用户点击"确认"时执行
  const createData = getCreateData();

  // 创建订单（使用旺铺聚合支付）
  createOrderSubmitWpgj(createData).then(res => {
    console.log('WPGJ支付响应数据:', res.data);
    // 直接弹出确认对话框（WPGJ接口调用成功就显示）
    ElMessageBox.confirm(
        '确定购买吗？',  // 对话框提示文字
        '购买确认',       // 对话框标题
        {
          confirmButtonText: '确认',  // 确认按钮文字
          cancelButtonText: '取消',   // 取消按钮文字
          type: 'warning'             // 对话框类型（警告样式）
        }
    )
        .then(() => {
          // WPGJ聚合支付处理 - 后端现在直接返回AppPayOrderSubmitRespVO
          if (res.data.displayContent) {
            // 使用displayContent字段生成二维码，使用WPGJ订单ID进行轮询
            getCode(res.data.displayContent, res.data.id);
          } else {
            ElMessage.error('获取支付信息失败');
          }
          showDrawer.value = false;
        })
        .catch(() => {
          ElMessageBox.confirm(
              '订单已创建，请前往控制台-我的订单查看',
              '提示',
              {
                confirmButtonText: '确认',
                showCancelButton: false,
                type: 'success'
              }
          ).then(() => {
            showDrawer.value = false;
          })
        });
  }).catch(err => {
    console.error('创建订单失败:', err);
    ElMessage.error('创建订单失败，请重试');
  });

  // 原有支付方式代码（已注释）
  /*
  createOrderSubmit(createData).then(res => {
    if (res.data.payOrderId) {
      // 弹出确认对话框
      ElMessageBox.confirm(
          '确定购买吗？',  // 对话框提示文字
          '购买确认',       // 对话框标题
          {
            confirmButtonText: '确认',  // 确认按钮文字
            cancelButtonText: '取消',   // 取消按钮文字
            type: 'warning'             // 对话框类型（警告样式）
          }
      )
          .then(() => {
            createPay({id: res.data.payOrderId, channelCode: 'wx_native'}).then(i => {
              if (i.code === 0) {
                getCode(i.data.displayContent, res.data.payOrderId)
              }
            })
            // showDrawer.value = false;
          })
          .catch(() => {
            ElMessageBox.confirm(
                '订单已创建，请前往控制台-我的订单查看',
                '提示',
                {
                  confirmButtonText: '确认',
                  showCancelButton: false,
                  type: 'success'
                }
            ).then(() => {
              showDrawer.value = false;
            })
          });
    }
  }).catch(err => {
    // 接口调用失败的处理（如提示错误）
  });
  */
}

function getCode(value, payOrderId) {
  QRCode.toDataURL(value, {errorCorrectionLevel: 'L', margin: 2, width: 350}, (err, url) => {
        if (err) throw err
        qrCode.value = {
          url: url,
          title: '请使用微信、支付宝或云闪付“扫一扫”扫码支付',
          visible: true
        }
      }
  )
  createQueryInterval(payOrderId)
}

/** 轮询查询任务 - WPGJ支付 */
const createQueryInterval = (id) => {
  if (interval.value) {
    return
  }
  interval.value = setInterval(async () => {
    const res = await getWpgjOrder(id)
    console.log(res, 'WPGJ轮询结果')
    // 已支付
    if (res.data.orderStatus === '1') {
      clearQueryInterval()
      // ElMessage.success('支付成功！')
      ElMessageBox.confirm(
          '支付成功',
          '请前往控制台-我的订单查看',
          {
            confirmButtonText: '确认',
            showCancelButton: false,
            type: 'success'
          }
      ).then(() => {
      })
    }
    // 已取消或失败
    if (res.data.orderStatus === '2') {
      clearQueryInterval()
      ElMessage.error('支付已关闭！')
    }
  }, 1000 * 2)
}

/** 轮询查询任务 - 老代码（已注释） */
/*
const createQueryInterval = (id) => {
  if (interval.value) {
    return
  }
  interval.value = setInterval(async () => {
    const res = await getOrder(id)
    console.log(res, 'res')
    // 已支付
    if (res.data.status === PayOrderStatusEnum.SUCCESS.status) {
      clearQueryInterval()
      // ElMessage.success('支付成功！')
      ElMessageBox.confirm(
          '支付成功',
          '请前往控制台-我的订单查看',
          {
            confirmButtonText: '确认',
            showCancelButton: false,
            type: 'success'
          }
      ).then(() => {
      })
    }
    // 已取消
    if (res.data.status === PayOrderStatusEnum.CLOSED.status) {
      clearQueryInterval()
      ElMessage.error('支付已关闭！')
    }
  }, 1000 * 2)
}
*/

// 查询详情支付订单 - 老代码（已注释）
/*
const getOrder = async (id, sync) => {
  return await request({
    url: '/pay/order/get',
    method: 'get',
    params: {
      id,
      sync
    }
  })
}
*/

// WPGJ旺铺聚合支付订单查询
const getWpgjOrder = async (id) => {
  return await request({
    url: '/pay/order/wpgj-get',
    method: 'get',
    params: {
      id
    }
  })
}

/** 清空查询任务 */
const clearQueryInterval = () => {
  // 清空各种弹窗
  qrCode.value = {
    title: '',
    url: '请使用微信“扫一扫”扫码支付',
    visible: false
  }
  showDrawer.value = false
  // 清空任务
  clearInterval(interval.value)
  interval.value = undefined
}

const clearProtocol = () => {
  protocol.value = true
}
</script>

<style scoped lang="scss">
.app-container {
  padding-top: 20px;
  padding-left: 0;
  padding-right: 0;
}

.top-banner-list {
  margin-top: 84px;

  .banner-item {
    width: 360px;
    height: 144px;
    background: linear-gradient(180deg, #DEEBFF 0%, rgba(222, 235, 255, 0) 100%), #FFFFFF;
    box-shadow: 0 9px 28px 8px rgba(46, 119, 227, 0.02), 0 6px 16px 0 rgba(46, 119, 227, 0.04), 0 3px 6px -4px rgba(46, 119, 227, 0.06);
    border-radius: 15px;
    border: 2px solid #FFFFFF;

    &:nth-child(2) {
      margin: 0 24px;
    }

    img {
      margin-right: 24px;
      width: 96px;
      height: 96px;
      object-fit: contain;
    }

    h3 {
      margin: 0 0 6px;
      font-weight: bold;
      font-size: 16px;
      color: #303233;
    }

    p {
      margin: 0;
      font-weight: 400;
      font-size: 14px;
      color: #626566;
      line-height: 22px;
    }
  }
}

.info-content {
  width: 1280px;
  margin: 40px auto 0 auto;
  position: relative;

  .switch-display {
    position: absolute;
    cursor: pointer;
    right: 0;
    top: 12px;
    z-index: 99;
    font-size: 24px;
  }

  .el-tabs {
    --el-border-color-light: #2E77E3;
    --el-tabs-header-height: 48px;

    :deep(.el-tabs__content) {
      overflow: visible
    }

    :deep(.el-tabs__active-bar) {
      display: none;
    }

    :deep(.el-tabs__item) {
      --el-font-size-base: 16px;
      padding-left: 24px !important;
      padding-right: 24px !important;

      &.is-active {
        color: #ffffff;
        background-color: #2E77E3;
      }
    }
  }

  .version-2 {
    height: 1000px;
    margin: 0 -12px;
    overflow-x: auto;

    .el-row {
      margin: 0 !important;
    }
  }
}

.el-table {
  font-size: 14px;

  :deep(.el-table__header-wrapper th) {
    font-size: 14px;
  }

  .action-button {
    padding-left: 8px;
    padding-right: 8px;
    height: 24px;
  }
}

.product-card {
  margin-bottom: 24px;
  border: 1px solid rgba(0, 0, 0, 0.08);
  //box-shadow: 0 0 10px 4px rgba(0, 0, 0, 0.08);
  box-shadow: 0 5px 10px 2px rgba(0, 0, 0, 0.08);
  border-radius: 15px;

  &:hover {
    border: 1px solid #2E77E3;
    box-sizing: border-box;
  }

  .top-info {
    padding: 18px 20px 12px 20px;
    border-radius: 15px 15px 0 0;
    background: linear-gradient(153deg, rgba(255, 175, 175, 0) 0%, #FDE7E7 100%), linear-gradient(145deg, #EDFCFF 0%, rgba(97, 227, 255, 0) 100%), #F0F6FF;

    .title {
      font-weight: bold;
      font-size: 20px;
      color: #303233;
      margin-bottom: 6px;
    }

    .tag {
      margin-bottom: 8px;

      .el-tag {
        margin-right: 5px;
      }
    }

    .desc {
      font-weight: 400;
      font-size: 14px;
      color: #949899;
    }
  }

  .bottom-info {
    padding: 12px 24px 20px 24px;

    .el-divider {
      margin: 12px 0;
    }
  }

  .el-col {
    &:nth-child(even) {
      display: flex;
      justify-content: space-between;
    }
  }

  .parameter-item:first-child {
    margin-bottom: 15px;
  }

  .label {
    font-weight: 500;
    font-size: 14px;
    color: #626566;
    margin-bottom: 2px;
  }

  .value {
    font-weight: bold;
    font-size: 16px;
    color: #303233;
  }

  .price {
    font-weight: bold;
    font-size: 24px;
    color: #FF9811;
  }

  .month-expenses {
    font-weight: 400;
    font-size: 14px;
    color: #949899;
  }

  .footer-action {
    .el-button {
      flex: 1
    }
  }
}

.shopping-trolley {
  cursor: pointer;
  color: #FFFFFF;
  position: absolute;
  right: 20px;
  bottom: 270px;
  padding: 16px 8px;
  background-color: #2E77E3;
  font-size: 16px;
  text-align: center;
}

:deep(.drawer) {
  .el-drawer__header {
    margin: 0;
    padding-bottom: 20px;
  }

  .el-drawer__title {
    font-weight: bold;
    font-size: 32px;
    color: #303233;
  }

  .el-drawer__body {
    padding-top: 12px;
    background-color: #F7F8F9;
  }
}

.info-block {
  background-color: #ffffff;
  padding: 4px 0;
  margin-bottom: 14px;
}

.info-item {
  padding: 12px 48px;

  .label {
    font-weight: 400;
    font-size: 14px;
    color: #626566;
  }

  .value {
    font-weight: bold;
    font-size: 14px;
    color: #303233;
  }
}

.drawer-footer {
  padding: 20px 48px 10px 48px;

  .price {
    font-weight: bold;
    font-size: 24px;
    color: #FF9811;

    & + div {
      font-weight: 400;
      font-size: 14px;
      color: #949899;
      text-align: right;
    }
  }

  .el-button {
    width: 180px;
    height: 46px;
    font-size: 20px;
    border-radius: 2px 2px 2px 2px;
  }
}

.checkbox-info {
  display: flex;
  align-items: center;
  background: #ffffff;
  padding-left: 48px;
  padding-bottom: 10px;

  .link {
    color: #409eff;
    cursor: pointer;
  }
}

#pdf-container {
  width: 100%; /* 设置容器宽度 */
  height: 600px; /* 设置容器高度 */
  border: 1px solid #ccc; /* 可选：添加边框 */
}

.pdf-box {
  height: 600px;
  //overflow: hidden;
  overflow-y: auto;
}
</style>
