<template>
  <div class="list-box">
    <div class="titleBox">
      <div class="titleBox_l">My order</div>
      <div class="titleBox_r">
        <div class="titleBox_r_l">
          <n-input v-model:value="keyword" type="text" class="custom-placeholder" clearable placeholder="Please enter your order number for inquiry" />
        </div>
        <div class="titleBox_r_r">
          Search
        </div>
      </div>
    </div>
    <div class="list">
      <div class="item" v-for="item in pageData.list" :key="item.id">
        <div class="item_title">Order Number：{{ item.orderNumber }}</div>
        <div class="item_content">
          <img :src="BaseUrl + '/report/' + item.researchReportFileName" alt="">
          <div>
            <div class="item_content_title">
              <img :src="BaseUrl + '/report/' + item.researchReportFileName" alt="">
              <div>
                {{ item.researchBriefReportTitle ||item.researchReportTitle}}
              </div>
            </div>
            <div class="item_content_time">Order placement time：<span> {{item.createDate}}</span></div>
            <div class="item_content_method">Payment method：<span>{{item.payResearchType}} </span></div>
            <div class="item_content_amount">Payment amount：<span>${{item.payPrice}}</span></div>
          </div>
        </div>
        <div class="btnBox">
          <div class="blue">PDF download</div>
          <div class="green">PPT Download</div>
        </div>
      </div>
    </div>
    <div class="pageBox" v-if="pageData?.list.length>0">
      <n-pagination show-quick-jumper :page-count="pageData?.count" :on-update:page="changePage" :page-slot="6">
        <template #prev>
          <div class="pageBox_btn">Previous</div>
        </template>
        <template #next>
          <div class="pageBox_btn">Next</div>
        </template>
        <template #goto>
          <div class="pageBox_inp">Go To</div>
        </template>
      </n-pagination>
    </div>
    <div class="box-empty" v-if="pageData?.count === 0">
      <n-empty description="Data Missed">
        <template #extra>
          <!-- <n-button @click="handleDemand({ id: '', price: 0 }, '0')" round type="primary">{{ t("report.detail.custom") }}</n-button> -->
        </template>
      </n-empty>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { useI18n } from "#imports";
import { ref, reactive, onMounted, watch, onUnmounted } from "vue";
import {
  NButton,
  NPagination,
  createDiscreteApi,
  NEmpty,
  NModal,
  NSpin,
} from "naive-ui";
import QrcodeVue from "qrcode.vue";
import { useUserStore } from "@/store/user";
const config = useRuntimeConfig();
const BaseUrl = ref(config.public.baseUrl);
const { t, locale, setLocale } = useI18n();
const pageSize = 10;
const userStore = useUserStore();
const pcShow = ref(true);
const props = defineProps({
  isMobile: {
    type: Boolean,
    default: false,
  },
});

const queryParams = reactive({
  pageNo: 1,
  pageSize: 5,
  orderNumber: "",
});

const pageData = ref({});
const wxQRCode = ref("");
const payVisible = ref<boolean>(false);
const payTitle = ref<string>("");
const count = ref(0);
const timer = ref();
const spinShow = ref(false);
const description = ref(t("myInfo.loading"));
const payShow = ref(false);
const closePayVisible = ref(false);
const closePayId = ref(null);
const emailShow = ref(false);
const activeItem = ref();
// const Message = createDiscreteApi(["message"]);
const model = ref({
  email: "",
  affirmEmail: "",
});
const openInpEmail = (item) => {
  activeItem.value = item;
  emailShow.value = true;
};
const getList = async () => {
  spinShow.value = true;
  description.value = t("myInfo.loading");
  let apiFun = getMyOrder_Api;
  if (userStore.getLang != "zh-CN") {
    apiFun = websiteUserResearchOrderList;
  }
  const { code, data } = await apiFun(queryParams);
  if (code === 200) {
    pageData.value = data;
  }
  spinShow.value = false;
};

// 提交邮箱
const submitEmit = () => {
  if (model.value.affirmEmail != model.value.email) {
    message.message.error("The email addresses are inconsistent.");
    return;
  }
  let param = {
    id: activeItem.value.id,
    email: model.value.email,
  };
  websiteUserResearchOrderUpdateEmail(param).then((res) => {
    if (res.code == 200) {
      message.message.success(t("report.demand.submitSuccess"));
      close();
      queryParams.pageNo = 1;
      getList();
    }
  });
};
const close = () => {
  emailShow.value = false;
};
// onMounted(() => {
getList();
// });
onBeforeMount(async () => {
  pcShow.value = !isMobile();
});
onUnmounted(() => {
  payEnd();
});

watch(
  () => payVisible.value,
  (newVal, oldVal) => {
    if (newVal === false) {
      payEnd();
    }
  }
);

const searchData = (val: string | any) => {
  queryParams.orderNumber = val;
  getList();
};
const goPay = (item) => {
  window.open(item.orderPayUrl);
};
const message = createDiscreteApi(["message"]);

// 下载
const handleTools = async (item: Object, fileType: string) => {
  if (fileType == "pay") {
    if (props.isMobile) {
      if (item.payMethod == "zfb" || item.payMethod == "wx") {
        return message.message.info("请前往PC端个人中心支付订单");
      }
    } else {
      if (item.payMethod == "zfb_h5" || item.payMethod == "wx_h5") {
        return message.message.info("请前往H5端个人中心支付订单");
      }
    }
    toPay(item);
  } else {
    const { code, data } = await getDownUrl_Api({
      researchBriefReportId: item.researchBriefReportId,
      fileType: fileType,
    });
    if (code === 200) {
      let url = `${BaseUrl}/fileupload/${data.filePath}${data.fileName}`;
      if (typeof window !== "undefined") {
        window.open(url);
      }
    }
  }
};

const toPay = (item) => {
  if (item.payMethod == "wx") {
    payVisible.value = true;
    wxQRCode.value = item.orderPayUrl;
    setTimeout(() => {
      payDetail(item);
    }, 500);
  } else {
    downloadFile(item.orderPayUrl);
  }
};

const payDetail = async (item) => {
  payShow.value = true;
  const { code, data } = await bulletinDetailPay_Api({
    researchBriefReportId: item.researchBriefReportId,
    orderNumber: item.orderNumber,
  });
  if (code === 200) {
    if (data.payStatus == 1) {
      message.message.success("支付成功");
      payEnd();
    } else if (data.payStatus != 1) {
      if (payVisible.value) {
        if (count.value >= 5) {
          payEnd();
          message.message.error("请检查是否支付完成");
        } else {
          timer.value = setTimeout(() => {
            count.value++;
            payDetail(item);
          }, 10 * 1000);
        }
      }
    }
  }
};

const payEnd = () => {
  count.value = 0;
  payVisible.value = false;
  clearTimeout(timer.value);
};

const handleClosePay = async (item) => {
  closePayId.value = item.id;
  closePayVisible.value = true;
};

const submitClosePayCallback = async () => {
  let apiFun = closePay_Api;
  if (userStore.getLang == "en-US") {
    // 英文  取消订单
    apiFun = websiteUserResearchCancelOrder;
  }
  const { code } = await apiFun({
    id: closePayId.value,
  });
  if (code === 200) {
    getList();
    message.message.success(t("myInfo.PaymentOrderCancelledSuccessfully"));
  }
  closePayId.value = null;
  closePayVisible.value = false;
};

const cancelClosePayCallback = () => {
  closePayId.value = null;
  closePayVisible.value = false;
};

// 改变页数
const changePage = (page: number) => {
  document.documentElement.scrollTop = 0;
  queryParams.pageNo = page;
  getList();
};

defineExpose({
  searchData,
});
</script>

<style lang="scss"  scoped>
@import "~/assets/css/tool.scss";
.list-box {
  .titleBox {
    display: flex;
    justify-content: space-between;
    padding-bottom: var(--size-7);
    border-bottom: var(--size-1) solid #e6e6e6;
    .titleBox_l {
      font-size: var(--size-24);
      font-family: Arial, Arial-Bold;
      font-weight: 700;
      color: #1a1a1a;
      line-height: var(--size-44);
    }
    .titleBox_r {
      display: flex;
      align-items: center;
      width: var(--size-500);
      height: var(--size-44);
      background: #f5f5f5;
      border-radius: var(--size-8);
      overflow: hidden;
      .titleBox_r_l {
        flex-grow: 1;
        .n-input {
          --n-height: var(--size-26) !important;
          line-height: var(--size-26) !important;
          background: #f5f5f5 !important;
          font-size: var(--size-14) !important;
        }
      }
      .titleBox_r_r {
        width: var(--size-105);
        font-size: var(--size-16);
        color: #ffffff;
        text-align: center;
        height: var(--size-44);
        background: linear-gradient(0deg, #7b9c4f 0%, #2da19d 100%), #1a1a1a;
        line-height: var(--size-44);
        cursor: pointer;
      }
    }
  }
  .list {
    margin-top: var(--size-45);
    .item {
      border: var(--size-1) solid #e6e6e6;
      position: relative;
      margin-bottom: var(--size-30);
      &:last-child {
        margin-bottom: 0;
      }
      .item_title {
        font-size: var(--size-20);
        font-family: Arial, Arial-Bold;
        font-weight: 700;
        text-align: left;
        color: #1a1a1a;
        line-height: var(--size-44);
        letter-spacing: 0.06px;
        padding: var(--size-14) var(--size-25);
        background: #f5f5f5;
      }
      .item_content {
        padding: var(--size-20) var(--size-25) var(--size-23);
        display: flex;
        align-items: center;
        > img {
          width: var(--size-148);
          height: var(--size-216);
          object-fit: contain;
        }
        > div {
          margin-left: var(--size-40);
          .item_content_title {
            font-size: var(--size-21);
            font-family: Arial, Arial-Regular;
            color: #1a1a1a;
            line-height: var(--size-28);
            img {
              display: none;
            }
          }
          .item_content_time,
          .item_content_method {
            display: flex;
            font-size: var(--size-16);
            font-family: Arial, Arial-Regular;
            color: #1a1a1a;
            letter-spacing: 0.05px;
            span {
              color: #808080;
            }
          }
          .item_content_time {
            margin: var(--size-20) 0 0;
          }
          .item_content_method {
            margin: var(--size-6) 0 var(--size-10);
          }
          .item_content_amount {
            display: flex;
            font-size: var(--size-16);
            font-family: Arial, Arial-Regular;
            color: #1a1a1a;
            line-height: var(--size-44);
            letter-spacing: 0.05px;
            align-items: baseline;
            span {
              font-size: var(--size-30);
              color: #ee001f;
            }
          }
        }
      }
      .btnBox {
        display: flex;
        position: absolute;
        right: var(--size-20);
        bottom: var(--size-45);
        > div {
          width: var(--size-144);
          height: var(--size-48);
          border-radius: var(--size-8);
          font-size: var(--size-14);
          font-family: Arial, Arial-Regular;
          text-align: center;
          color: #ffffff;
          line-height: var(--size-48);
          margin-right: var(--size-14);
          cursor: pointer;
          &:last-child {
            margin-right: 0;
          }
        }
        .blue {
          background: #60ac92;
        }
        .green {
          background: #84a86c;
        }
      }
    }
  }
}
@include responseTo("phone") {
  .list-box {
    .titleBox {
      padding-bottom: var(--size-20);
      display: block;
      .titleBox_r {
        width: 100%;
      }
    }
    .list {
      margin-top: var(--size-20);
      .item {
        .item_title {
          padding: var(--size-10) var(--size-15);
          font-size: var(--size-18);
          line-height: var(--size-24);
        }
        .item_content {
          padding: var(--size-10);
          > img {
            display: none;
          }
          > div {
            margin: 0;
            .item_content_title {
              display: flex;
              > div {
                font-size: var(--size-18);
                line-height: var(--size-26);
                overflow: hidden;
                text-overflow: ellipsis;
                display: -webkit-box;
                -webkit-line-clamp: 4;
                -webkit-box-orient: vertical;
              }
              > img {
                width: var(--size-74);
                height: var(--size-108);
                object-fit: contain;
                margin-right: var(--size-10);
                display: block;
              }
            }
            .item_content_time,
            .item_content_method {
              font-size: var(--size-14);
            }
            .item_content_amount {
              font-size: var(--size-14);
              line-height: var(--size-30);
              span {
                font-size: var(--size-26);
              }
            }
          }
        }
        .btnBox {
          position: static;
          width: 100%;
          justify-content: center;
          padding-bottom: var(--size-20);
        }
      }
    }
  }
}
</style>
