<template>
  <div class="page">
    <div class="commoditylIst">
      <el-scrollbar :always="true">
        <div class="scrollbar-flex-content">
        <div class="item" v-for="item in packageList" :key="item.typeDesc" :class="item.sellPriceRmb <= 0 ? 'dashed' : ''">
          <!--  @click="clickPayDialog(item)" -->
          <div> 
            <div class="line" :style="`background-color:${ item.sellPriceRmb > 0 ? item.color : '#eee'} ;`"></div>
            <div class="info">
              <!-- 商品信息 -->
              <div class="content">
                <div class="titleBox">
                  <!-- <p class="iconText" v-if="item.sellPriceRmb <= 0" >会员权益</p> -->
                  <div class="title">
                    {{ item.title }}
                  </div>
                </div>
                <template  v-if="item.sellPriceRmb > 0">
                <div class="money">
                  <span class="price">{{
                    item.sellPriceRmb / 100
                  }} ¥</span
                  >/ <span style="text-decoration:line-through;"> {{ $t("store.priceRmb") }}{{ item.priceRmb / 100 }}</span>
                </div>
                <div class="time">
                  {{ $t("store.glod") }}<span> {{ item.glod }}</span
                  > 
                </div>
                <div v-if="item.sellPriceRmb > 0" class="button" @click="clickPayDialog(item)" :style="`background-color: #f3af00 ;`">
                  {{ $t("store.createOrder") }}
                </div>
              </template>
              </div>
              <!-- 商品权益 -->
              <div class="authority">
                <div v-html="item.detail"></div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-scrollbar>
      <!-- 企业版 -->
      <!-- <div class="item" @click="showTalkUsDialog = true">
        <div class="mask" v-if="false">
          <el-icon><i-ep-Lock /></el-icon>
        </div>
        <div class="line" :style="`background-color:#000 ;`"></div>
        <div class="info">
          <div class="content" style="border-bottom: none">
            <div class="titleBox">
              <div class="title">
                {{ $t("shop.Ent") }}
              </div>
            </div>
            <div class="description">
              <div>
                {{ lanChange == "zh-cn" ? "所有权限" : "All Pro Benefits" }}
              </div>
              <div>
                {{
                  lanChange == "zh-cn" ? "克隆数字双元" : "Clone DigItal Double"
                }}
              </div>
              <div>
                {{
                  lanChange == "zh-cn" ? "专属定制头像" : "Customized Avatar"
                }}
              </div>
              <div>
                {{
                  lanChange == "zh-cn"
                    ? "专属定制声纹"
                    : "Customized Voiceprint"
                }}
              </div>
            </div>
            <div v-if="true" class="button" :style="`background-color:#000  ;`">
              {{ $t("shop.talkUs") }}
            </div>
            <div v-else class="button" :style="`background-color:#000  ;`">
              {{ $t("shop.talkUs") }}
            </div>
          </div>
        </div>
      </div> -->
    </div>
    <!-- 对话框 v-if="false"-->
    <el-dialog v-model="showPayDialog" v-if="showPayDialog"
      :title="$t('store.payType')" width="300px">
      <div class="payDialog">
        <el-radio-group v-model="payVendor">
          <el-radio label="4" border>
            <img src="../../assets/img/alipay.png" alt="" />{{ $t("recharge.alipay") }}
          </el-radio>
          <el-radio label="2" border>
            <img src="../../assets/img/weChat.png" alt="" />{{ $t("recharge.weChat") }}
          </el-radio>
        </el-radio-group>
      </div>
      <!-- 二维码弹出框 -->
      <el-dialog
        v-model="orderCodeDialogShow"
        width="500px"
        append-to-body
        destroy-on-close
        @closed="clearCode"
        :close-on-click-modal="false"
      >
        <div class="orderCodeDialog"  v-loading="loading"
    :element-loading-text="`${$t('store.pay')}`">
          <div class="codeImg">
            <my-Loading-Icon2
              v-if="!payCodeUrl && !iframeBody"
            ></my-Loading-Icon2>
            <!-- :callback="qrcode" -->
            <vue-qr v-if="payCodeUrl" :text="payCodeUrl" :size="280"></vue-qr>
            <iframe
              v-show="iframeBody"
              id="myIframe"
              width="210PX"
              height="205PX"
              frameborder="0"
            ></iframe>
          </div>
          <div class="tips">
            {{
              lanChange == "zh-cn"
                ? `扫描二维码进行付款`
                : `Scan the QR code for payment`
            }}
          </div>
          <!-- <div class="btnBox">
            <div @click="RefreshQR">
              {{ lanChange == "zh-cn" ? `刷新二维码` : `Refresh QR code` }}
            </div>
          </div> -->
        </div>
      </el-dialog>
      <template #footer>
      <span class="dialog-footer">
        <el-button size="small" @click="showPayDialog = false">{{ $t("store.cancel") }}</el-button>
        <el-button size="small" type="primary" @click="payConfirm">
          {{$t("store.confirm")}}
        </el-button>
      </span>
    </template>
    </el-dialog>

    <!-- 联系我们对话框 -->
    <talkUs
      :showTalkUsDialog="showTalkUsDialog"
      @updateShowTalkUsDialog="updateShowTalkUsDialog"
    ></talkUs>
  </div>
</template>

<script setup>
//#region 导入
import { getCurrentInstance, ref, onMounted } from "vue";
import { packageInfoApi } from "@/apis/myStore";
import { useI18n } from "vue-i18n";
import talkUs from "@/components/talkUs.vue";
import { useRoute, useRouter } from "vue-router";
import { createOrderApi, createPayApi, getOrderStatusApi } from "@/apis/pay";
import { orderDetailApi, findStatusApi } from '@/apis/myStore.js'
import vueQr from 'vue-qr/src/packages/vue-qr.vue';

const route = useRoute();
const router = useRouter();
const { locale } = useI18n();
const lanChange = ref(locale);

const AccessToken = localStorage.getItem("AccessToken"); // 判断有没有登录
//#endregion ------------------------------------

const packageList = ref([]);
async function getPackageList() {
  const res = await packageInfoApi();
  packageList.value = res.data;
}

const showPayDialog = ref(false); //套餐信息dialog显示隐藏
const presentItme = reactive({}); //点击的套餐项
// const presentItme = ref({}); //点击的套餐项
function clickPayDialog(item) {
  presentItme.value = item;
  createOrder(item)
  showPayDialog.value = true;
}

//#endregion ------------------------------------

//#region 点击套餐内的支付
function showOrderCode(type) {
  orderCodeDialogShow.value = true;
  myPayVendor.value = type;
  createOrderFunc();
}
const orderCodeDialogShow = ref(false);
const orderCodeUrl = ref(null);
//#endregion ------------------------------------

//#region 页面滚动
const scrollContainerRef = ref(null);
function handleWheel(event) {
  const scrollContainer = scrollContainerRef.value; // 获取滚动容器的引用
  const scrollAmount = 150; // 每次滚动的距离
  // 检查滚动方向
  if (event.deltaY > 0) {
    // 向右滚动
    scrollContainer.scrollLeft += scrollAmount;
  } else {
    // 向左滚动
    scrollContainer.scrollLeft -= scrollAmount;
  }
  event.preventDefault(); // 防止页面上下滚动
}
//#endregion ------------------------------------

//#region 联系我们弹窗
const showTalkUsDialog = ref(false);
const updateShowTalkUsDialog = (newValue) => {
  showTalkUsDialog.value = newValue;
};
//#endregion ------------------------------------

//#region 页面初始化
onMounted(async () => {
  getPackageList();
  // createOrderFunc();
});
//#endregion ------------------------------------

//#region 支付
const myPayVendor = ref(null); // 2微信  4支付宝
const payCodeUrl = ref(null); //付款二维码地址
const payCodeImg = ref(null); //付款二维码图片
// 支付失败处理
function payErrorHandle() {
  orderCodeDialogShow.value = false;
  ElMessage.error(
    lanChange.value == "zh-cn"
      ? `获取订单失败,请重试`
      : `Failed to get the order, please try again`
  );
}
// 获取订单
const myOrderNumber = ref(null); //订单号
async function createOrderFunc() {
  const data = {
    productId: 30,
  };
  try {
    const res = await createOrderApi(data);
    if (res.code == 200) {
      myOrderNumber.value = res.data;
      createPayFunc(res.data);
    } else {
      payErrorHandle();
    }
  } catch (error) {
    payErrorHandle();
  }
}
// 获取订单详情
let iframeBody = ref(null);
const iframeDom = ref(null);
const loading = ref(false)
async function createPayFunc(orderNumber) {
  const data = {
    orderNumber,
    payVendor: payVendor.value,
  };
  try {
    const res = await createPayApi(data);
    if (res.code == 200) {
      // 支付宝获取iframe内容
      if (res.data.body) {
        orderCodeDialogShow.value = true;
        setTimeout(() => {
          iframeBody.value = res.data.body;
          iframeDom.value = document.getElementById("myIframe");
          iframeDom.value.srcdoc = iframeBody.value;
        }, 1000)
      }
      // 直接获取二维码
      if (res.data.codeUrl) {
        payCodeUrl.value = res.data.codeUrl;
       // showOrderCode(payVendor.value)
        orderCodeDialogShow.value = true;
      }
      // findStatus()
      await getStatusOfOrderFunc(orderNumber);
    } else {
      payErrorHandle();
    }
  } catch (error) {
    payErrorHandle();
  }
}
// 获取订单支付状态 payStatus 查询支付状态 0:待支付，2:支付中，3：已支付
async function getStatusOfOrderFunc(orderNumber) {
  // if (
  //   route.path != "/myStore" ||
  //   orderCodeDialogShow.value == false ||
  //   orderNumber != payVendor.value
  // ) {
  //   return;
  // }
  try {
    // let payVendor = payVendor.value;
    let data = {
      orderNumber,
      payVendor: payVendor.value
    }
    const res = await findStatusApi(data);
    if (res.code == 200) {
      if (res.data.orderStatus == 1) { // 页面就不动，继续定时请求
        setTimeout(() => {
          getStatusOfOrderFunc(orderNumber);
        }, 3000);
      } else if (res.data.orderStatus == 2) { // 页面就不动, loading....的效果盖在二维码之前，继续定时请求
        loading.value = true
        setTimeout(() => {
          getStatusOfOrderFunc(orderNumber);
        }, 3000);
      } else if (res.data.orderStatus == 3) { // 提示支付成功，关闭当前页
        orderCodeDialogShow.value = false;
        showPayDialog.value = false
        ElMessage.success(
          lanChange.value == "zh-cn" ? `支付成功!` : `Payment is successful!`
        );
      } else { // 提示支付失败，关闭当前页
        ElMessage.success('支付失败');
      }
    } else {
      setTimeout(() => {
        getStatusOfOrderFunc(orderNumber);
      }, 3000);
    }
  } catch (error) {
    console.log(error, "error");
    ElMessage.error(
      lanChange.value == "zh-cn"
        ? `获取订单失败,请重试`
        : `Failed to get the order, please try again`
    );
  }
}
// 生成二维码
// function qrcode() {
//   return;
// }

// 关闭二维码弹窗
function clearCode() {
  myPayVendor.value = null; // 2微信  4支付宝
  payCodeUrl.value = null;
  iframeBody.value = null;
  showPayDialog.value = false;
}
// 刷新二维码
function RefreshQR() {
  payCodeUrl.value = null;
  iframeBody.value = null;
  // createOrderFunc();
  createPayFunc(myOrderNumber.value);
}
//#endregion ------------------------------------

//#region

//#endregion ------------------------------------
const payVendor = ref('4')
const orderNumber = ref('')
// 创建订单
function createOrder(item) {
  createOrderApi({productId: item.id}).then(res => {
    orderNumber.value = res.data
  })
}
// 创建支付
function payConfirm() {
  createPayFunc(orderNumber.value);
}
// 获取订单详情
function  getOrderDetail(item) {
  orderDetailApi(item.id).then(res => {
  })
}
//每隔一分钟运行一次保存方法
// const timer = setInterval(()=>{
//   findStatus()
// },1000)

function findStatus() {
  let data = {
    orderNumber: '',
    payVendor: ''
  }
  findStatusApi(data).then(res => {
    if (res.data !== 2) { // 如果是2就不停的调，直到返回1、3、4
      clearInterval(timer);
    }
  })
}
</script>
<style>
.el-dialog {
  border-radius: 5px !important;
}</style>
<style lang="scss" scoped>

.page {
  // min-width: calc(100vw - 210px);
  height: calc(100vh - 80px);
  width: 1690px;
  padding: 0px 20px 0 20px;
  background-color: #fff;
  border-radius: 25px 0 0;
  padding: 20px;
  user-select: none;
  overflow: hidden;
  ::-webkit-scrollbar {
    display: none;
  }
}
// 方案列表
.commoditylIst {
  display: flex;
  justify-content: flex-start;
  overflow-x: scroll;
  padding: 30px 20px 20px 10px;
  max-width: 100%;
  .scrollbar-flex-content{
    display: flex;
    padding-bottom: 30px;
  }

  .item {
    position: relative;
    width: 450px;
    // height: 680px;
    margin-left: 45px;
    background-color: #fffefd;
    flex-shrink: 0; /* 防止缩小宽度 */
    border: 1px solid #c0bfbd;
    border-radius: 20px;
    overflow: hidden;
    transition: all 0.2s;
    cursor: pointer;
    &.dashed {
      border: 1px dashed #c0bfbd;
    }
    &:hover {
      .mask {
        display: block;
      }
    }
    // 遮罩层
    .mask {
      position: absolute;
      top: 0;
      left: 0;
      display: none;
      width: 100%;
      height: 100%;
      line-height: 780px;
      font-size: 120px;
      font-weight: 900;
      text-align: center;
      background-color: rgba(0, 0, 0, 0.2);
      cursor: pointer;
    }
    .line {
      height: 20px;
      background-color: pink;
      cursor: pointer;
    }
    .info {
      padding: 20px;
      cursor: pointer;
      .content {
        // height: 220px;
        padding: 20px;
        border-bottom: 1px solid #c0bfbd;
        cursor: pointer;
        position: relative;
        .titleBox {
          display: flex;
          justify-content: space-between;
        }
        .iconText{
          font-size: 14px;
          position: absolute;
          left:-20px;
          top:0;
          transform: rotate(-45deg);
          background: rgb(243, 175, 0);
          padding: 3px 10px;
          color: #fff;
        }
        .title {
          font-size: 30px;
          font-weight: 700;
          width: 100%;
          margin-bottom: 10px;
          cursor: pointer;
          text-align: center;
          .el-icon {
            line-height: 30px;
            width: 40px;
            height: 40px;
            font-size: 40px;
            color: #000;
            text-align: center;
            vertical-align: sub;
            cursor: pointer;
          }
        }
        .money {
          margin-bottom: 10px;
          font-size: 20px;
          color: #7c7c7a;
          cursor: pointer;
          text-align: end;
          .price {
            font-size: 30px;
            color: #242625;
            cursor: pointer;
          }
        }
        .time {
          text-align: end;
          margin-bottom: 10px;
          font-size: 20px;
          color: #7c7c7a;
          cursor: pointer;
          margin-bottom: 20px;
          span {
            color: #242625;
            cursor: pointer;
            margin-right: 5px;
            padding-left: 10px;
          }
        }

        .button {
          width: 100%;
          height: 40px;
          font-size: 16px;
          border-radius: 10px;
          text-align: center;
          line-height: 40px;
          color: #fff;
          font-weight: 700;
          background-color: yellow;
          cursor: pointer;
        }
        .description {
          cursor: pointer;
          margin-top: 50px;
          margin-bottom: 30px;
          width: 100%;
          display: flex;
          flex-direction: column;
          align-items: center;
          font-size: 18px;
          color: #7c7c7a;
          > div {
            cursor: pointer;
            margin-bottom: 20px;
          }
        }
      }
      .authority {
        margin-top: 10px;
        &-item {
          display: flex;
          justify-content: space-between;
          cursor: pointer;
          font-weight: 400;
          font-size: 18px;
          padding: 5px 10px;
          color: #7c7c7a;

          span {
            cursor: pointer;
            color: #7c7c7a;
            margin-right: 30px;
          }
          i {
            font-size: 20px;
            font-style: normal;
            margin-right: 5px;
            background-image: -webkit-linear-gradient(
              left,
              #4b61dc,
              #15d1b8 25%,
              #4b61dc 50%,
              #15d1b8 75%,
              #4b61dc
            ) !important;
            -webkit-text-fill-color: transparent !important;
            -webkit-background-clip: text !important;
            background-clip: text !important;
            -webkit-background-size: 200% 100% !important;
            background-size: 200% 100% !important;
          }
        }
      }
    }
    &:hover {
      cursor: pointer;
      transform: translateY(-20px);
      box-shadow: #00000026 2px 2px 2px 2px;
    }
  }
}
// 支付弹窗
.el-radio{
  width: 100px;
  img {
    vertical-align: middle;
    margin-right: 5px;
    width: 16px;
  }
}

// 二维码弹窗
.orderCodeDialog {
  width: 100%;
  .codeImg {
    display: flex;
    margin: auto;
    // justify-content: space-evenly;
    align-items: center;
    width: 220PX;
    height: 220PX;
    border: 1px solid #ccc;
    border-radius: 15px;
    overflow: hidden;
    padding: 13px;
    img {
      width: 100%;
      height: 100%;
    }
  }
  .tips {
    padding-top: 10px;
    text-align: center;
  }
  .btnBox {
    padding: 15px 40px;
    display: flex;
    justify-content: space-evenly;
    > div {
      padding: 10px 20px;
      color: #000;
      background-color: #fff;
      border: #000 solid 1px;
      border-radius: 10px;
      transition: all 0.3s;
      cursor: pointer;
      &:hover {
        color: #fff;
        background-color: #000;
      }
    }
  }
}

// 联系我们弹窗
.TalkUsDialog {
  display: flex;
  flex-direction: column;
  align-items: center;
  &-content {
    width: 100%;
    display: flex;
    justify-content: space-between;
    > div {
      width: 30%;
      display: flex;
      flex-direction: column;
      align-items: center;
      img {
        width: 100px;
        height: 100px;
        margin-bottom: 40px;
      }
    }
    .sendEmail {
      text-decoration: underline;
      cursor: pointer;
    }
  }
  .close {
    margin-top: 50px;
    width: 100px;
    height: 50px;
    font-size: 18px;
    line-height: 50px;
    text-align: center;
    border-radius: 15px;
    border: 2px solid #ccc;
    cursor: pointer;
  }
}
</style>
