<template>
  <div class="list-box" :class="{ 'mobile-order': isMobile }">
    <template v-if="pageData.count">
      <div class="items">
        <div class="order-item" v-for="item in pageData.list" :key="item.id">
          <div class="order-info">
            <div class="order-left">
              <div class="label label-num">
                <span class="num">{{t('myInfo.orderNo')}}：</span>
                <span>{{ item.orderNumber }}</span>
              </div>
              <div class="label">
                <span class="time">{{t('myInfo.orderTime')}}：</span>
                <span>{{ item.createDate }}</span>
              </div>
              <div class="label" v-if="userStore.getLang =='zh-CN'">
                <span class="way">支付方式：</span>
                <span v-if="item.payMethod == 'zfb' || item.payMethod == 'zfb_h5'">支付宝 {{ item.payMethod == "zfb" ? "PC端" : "H5端" }}</span>
                <span v-if="item.payMethod == 'wx' || item.payMethod == 'wx_h5'">微信 {{ item.payMethod == "wx" ? "PC端" : "H5端" }}</span>
              </div>
              <div class="label">
                <span class="time">{{ $t("myInfo.orderStatus") }}：</span>
                <span>
                  <span v-if="item.payStatus == 0">{{$t("myInfo.waitingPayment")}}</span>
                  <span v-else-if="item.payStatus == 1">{{$t("myInfo.paymentSuccess")}}</span>
                  <span v-else>{{ $t("myInfo.paymentFailed") }}</span>
                </span>
              </div>
            </div>
            <div class="order-right">
              <span>{{t('myInfo.payAmount')}}：</span>
              <span  v-if="userStore.getLang == 'en-US'">$</span>
              <span class="price">{{ item.payPrice }}</span>
              <span v-if="userStore.getLang == 'zh-CN'">元</span>
            </div>
          </div>
          <div class="report">
            <div class="report-title">{{ item.researchBriefReportTitle }}</div>
            <div class="report-btns">
              <n-button type="primary" color="#2683F0" @click="handleTools(item, 'pay')" v-if="item.payStatus == 0&&userStore.getLang == 'zh-CN'">
                {{t('myInfo.toPay')}}
              </n-button>
              <n-button type="primary" color="#2683F0" @click="goPay(item)" v-if="item.payStatus == 0&&userStore.getLang == 'en-US'">
                {{t('myInfo.toPay')}}
              </n-button>
              <n-button type="primary" color="#2683F0" @click="handleClosePay(item)" v-if="item.payStatus == 0">
                {{t('myInfo.cancelPay')}}
              </n-button>
              <n-button type="primary" color="#2683F0" v-if="item.payStatus == 1&&userStore.getLang == 'en-US'&&!item.email" @click="openInpEmail(item)">
                Check email
              </n-button>
              <n-button type="primary" v-if="userStore.getLang =='zh-CN'" color="#2683F0" @click="handleTools(item, 'pdf')">
                PDF下载
              </n-button>
              <n-button type="primary" v-if="userStore.getLang =='zh-CN'" color="#2683F0" @click="handleTools(item, 'ppt')">
                PPT下载
              </n-button>
            </div>
          </div>
        </div>
      </div>
      <div class="pagination">
        <n-pagination :page="queryParams?.pageNo" :page-count="pageData?.count" :page-size="queryParams?.pageSize" size="large" :on-update-page="changePage" :page-slot="7" />
      </div>
    </template>
    <div class="empty" v-else>
      <n-empty :description="t('myInfo.noData')" size="huge"> </n-empty>
    </div>

    <n-modal :show="payVisible" preset="dialog" :title="payTitle" :showIcon="false" :z-index="9" @close="payVisible = false" @esc="payVisible = false" @mask-click="payVisible = false" :class="{ 'login-dialog': isMobile }">
      <div class="wxQRCode">
        <h3>微信支付</h3>
        <qrcode-vue :value="wxQRCode" size="200" level="H" render-as="svg" />
        <p>请使用微信扫码支付</p>
        <p v-if="payShow" style="color: red">支付状态请求中,请勿重复支付</p>
      </div>
    </n-modal>

    <n-modal v-model:show="closePayVisible" preset="dialog" :title="t('myInfo.tip')" :showIcon="false" :content="t('myInfo.confirmCancelPayment')" positive-text="确认" negative-text="取消" :close-on-esc="false" :mask-closable="false" @positive-click="submitClosePayCallback" @negative-click="cancelClosePayCallback" :class="{ 'login-dialog': isMobile }" />

    <n-spin class="load" :description="description" :show="spinShow" :delay="1000">
      <div style="width: 150px"></div>
    </n-spin>

    <n-modal :show="emailShow" preset="dialog" title="Check email address" :showIcon="false" :close-on-esc="false" :mask-closable="false" @close="close" :class="{ 'login-dialog': !pcShow }">
     <n-form  :model="model" :rules="rules" label-align="right" label-placement="left" label-width="auto" require-mark-placement="left">
          <n-form-item label="Enter email address：" class="ms" path="email">
            <n-input v-model:value="model.email" placeholder="email address" />
          </n-form-item>
          <n-form-item label="Confrm email address：" class="ms" path="affirmEmail">
            <n-input v-model:value="model.affirmEmail" placeholder="email address" />
          </n-form-item>
          <n-form-item label="" class="ms">
            <div class="tig">*Email addresses do not match</div>
          </n-form-item>
        </n-form>
        <n-button class="login-btn" attr-type="button" type="info" color="#18A058" :disabled="submitLoading" @click="submitEmit()">
         {{
            submitLoading
              ? $t("report.demand.submitting")
              : $t("report.demand.submit")
          }}
      </n-button>
    </n-modal>
  </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>
.list-box {
  height: 100%;

  .items {
    height: calc(100% - 50px);
    overflow: hidden;
    overflow-y: scroll;
  }

  .pagination {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 50px;
  }

  .empty {
    padding: 50px 0;
  }
}
.order-item {
  margin-bottom: 30px;
  background-color: #ffffff;
  border: 1px solid #6ac796;

  .order-info {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px 30px;
    background-color: #e6fff2;
    font-size: 16px;
    color: #808080;

    .order-left {
      .label-num {
        font-weight: bold;
        color: #18a058;
      }

      .label {
        .time,
        .way {
          color: #1a1a1a;
        }
      }
    }
    .order-right {
      .price {
        font-size: 30px;
        color: #666666;
      }
    }
  }

  .report {
    padding: 30px;
    padding-bottom: 50px;
    font-size: 24px;
    color: #1a1a1a;

    .report-title {
      margin-bottom: 20px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }

    .report-btns {
      .n-button {
        width: 140px;
        height: 50px;
        margin-right: 20px;
        font-size: 18px;
        border-radius: 8px;
      }
    }
  }
}

.mobile-order {
  .order-item {
    margin-bottom: 15px;

    .order-info {
      padding: 10px 15px;
      font-size: 14px;

      .order-right {
        .price {
          font-size: 18px;
        }
      }
    }

    .report {
      padding: 15px;
      padding-bottom: 20px;
      font-size: 18px;

      .report-title {
        margin-bottom: 10px;
      }

      .report-btns {
        :deep(.n-button) {
          width: 90px;
          height: 45px;
          margin-right: 10px;
          margin-bottom: 10px;
          font-size: 14px;
          border-radius: 4px;
        }
      }
    }
  }
}

.login-dialog.n-dialog {
  min-width: auto;

  padding-top: 20px;
  border-radius: 10px;

  .n-dialog__title {
    font-size: 18px;
  }

  .n-dialog__content {
    .container {
      padding: 20px 10px;

      .login-btn {
        height: 45px;
      }
    }
  }
}

.login-dialog .n-dialog {
  min-width: auto;

  padding-top: 20px;
  border-radius: 10px;

  .n-dialog__title {
    font-size: 18px;
  }

  .n-dialog__content {
    .container {
      padding: 20px 10px;

      .login-btn {
        height: 45px;
      }

      .n-form {
        .n-form-item {
          .n-form-item-label {
            width: 85px !important;
            font-size: 12px;
          }

          .n-form-item-feedback-wrapper {
            min-height: 10px;
          }
        }
      }
    }
  }
}
 .login-btn {
    display: block;
    width: 50%;
    height: 50px;
    color: #fff;
    font-size: 18px;
    border-radius: 8px;
    margin: 0 auto;
    :deep(.n-button__content) {
      display: block;
    }
  }
  .tig {
  font-size: 16px;
  color: #18A058;
  margin-left:205px;
}
</style>
