<template>
  <div class="personal-center-container">
    <qrCode :loading="false" :testNum="testNum" :trade_state_closed="trade_state_closed"
      :centerDialogVisible.sync="centerDialogVisible" :wxPayCode="wxPayCode" @closePayDialogs="closePayDialogs"
      :price="price" @getReacquireCodes="getReacquireCodes" />

    <div class="flex-row top-line">
      <el-breadcrumb separator="/">
        <!-- :to="{ path: '/welcome/MainTable' }" -->
        <el-breadcrumb-item style="cursor: pointer" @click.native="goBack()">首页</el-breadcrumb-item>
        <el-breadcrumb-item style="cursor: pointer"><a href="#">测试记录</a></el-breadcrumb-item>
      </el-breadcrumb>
      <el-input placeholder="请输入测试名称" clearable v-model="searchKey" class="input-with-select"
                @keyup.enter="searchRecord" @clear="searchRecord">
        <el-button slot="append" icon="el-icon-search" @click="searchRecord"></el-button>
      </el-input>
    </div>
    <div class="card-list" v-loading="loading" element-loading-background="rgba(255, 255, 255, 0.3)">
      <ul>
        <li v-for="(item, index) in dataList" :key="index">
          <img src="../assets/60e9526e0b432@2x(0).png" alt="" />
          <div style="display: block">
            <h2>{{ item.name }}</h2>
            <!-- <p :title=item.testResult class="view-text">{{ item.testResult }}</p> -->
            <div class="content">
              {{ item.testDate }}
            </div>
            <div class="goDetail" @click="detailP(item)">
              查看详情
              <i class="el-icon-arrow-right" />
            </div>
          </div>
        </li>
      </ul>
    </div>
    <div class="flex-center">
      <el-pagination background layout="prev, pager, next" :total="total" :current-page="pageNum"
                     @current-change="handleCurrentChange">
      </el-pagination>
    </div>
  </div>
</template>

<script>
var systemVersion = process.env.VUE_APP_VERSION;

export default {
  data() {
    return {
      trade_state_closed: "",

      testNum: "",
      baseUrl: baseUrl,
      pageSize: 12,
      pageNum: 1,
      dataList: [],
      total: 0,
      userBid: "",
      institutionNo: "",
      persionDetailData: null,
      centerDialogVisible: false,
      wxPayCode: "",
      timer: "",
      price: "",
      searchKey: "",
      itemList: {},
      loading: false
    };
  },
  //页面初始化函数
  created() {
    this.$parent.searchShow = false;
  },
  mounted() {
    this.getPhoneNo();
    this.getRecordList();
  },
  destroyed() {
    clearInterval(this.timer);
  },
  methods: {
    getReacquireCodes() {
      let _this = this;
      clearInterval(_this.timer);
      _this.detailP(_this.itemList);
    },
    closePayDialogs() {
      let _this = this;
      _this.centerDialogVisible = false;
      clearInterval(_this.timer);
      //  this.$router.go(0);
    },
    getPhoneNo() {
      //取非空的参数
      let phoneNo = this.$route.query.phone;
      this.institutionNo = sessionStorage.getItem(
        "f7a42fe7211f98ac7a60a285ac3a9527"
      );
      if (phoneNo != null && phoneNo != "" && phoneNo != "undifine") {
        //管理员账号进来之后通过url参数获取，若url参数不空则是普通用户,通过session获取
        this.userBid = phoneNo;
      } else {
        this.userBid = sessionStorage.getItem(
          "f7a42fe7211f98ac7a60a285ac3a9e87"
        );
      }
    },
    handleCurrentChange(val) {
      this.pageNum = val;
      this.getRecordList();
    },
    // 获取测试记录列表
    getRecordList() {
      this.loading = true
      this.$http.get(
        `mineTest/${this.userBid}/${this.institutionNo}?pageSize=${this.pageSize}&pageNum=${this.pageNum}&searchKey=${this.searchKey}`,
        {},
        (res) => {
          this.persionDetailData = res.data;
          this.total = res.data.allNum;
          this.dataList = res.data.userRecordEntityList;
          setTimeout(() => {
            this.loading = false
          }, 350)
        }, (err) => {
          console.log(err)
          this.loading = false
        }
      );
    },
    // 搜索测试记录
    searchRecord() {
      this.pageNum = 1;
      this.getRecordList();
    },
    detailP(item) {
      // console.log("第二次调用", item);
      let _this = this;
      _this.itemList = item;
      sessionStorage.setItem("persionId", item.id);
      let userId = sessionStorage.getItem("b80bb7740288fda1f201890375a60c8f");
      //跳转页面到结果页面
      let userType = sessionStorage.getItem("f7a42fe7211f98ac7a60a285ac3a9528");
      let productId = item.subjectOrCognitiveId;
      let resultId = item.id;
      if (userType == 1) {
        //普通用户
        sessionStorage.setItem("persionId", item.id);
        console.log("-item.id-------->", item);
        if (systemVersion == "public" && item.type != "1") {
          _this.$http.get(
            `/api/orderInfo/queryOrderByResultIdAndUserId/${productId}/${userId}/${resultId}`,
            {},
            (res) => {
              console.log("查询支付订单", res);
              if (res.code == "200") {
                if (res.data == null) {
                  _this.$http.get(
                    `/api/promotionInfo/queryPromotionBySubjectId/${productId}`,
                    {},
                    (res) => {
                      console.log("获取支付金额", res);
                      _this.price = res.data.price;
                      if (this.price != 0) {
                        let params = {
                          productId,
                          userId,
                          resultId,
                          description: res.data.name,
                          total: res.data.price,
                        };
                        console.log("二维码参数", params);
                        // 获取二维码参数
                        _this.$http.post(
                          `/api/wx-pay/native`,
                          params,
                          (res) => {
                            console.log(
                              "======fanghui==8888===============>",
                              res.data
                            );

                            if (res?.data?.codeUrl) {
                              console.log(
                                "======fanghui=codeUrl=88880===============>",
                                res.data.codeUrl
                              );

                              _this.wxPayCode = res.data.codeUrl;
                              _this.testNum = res.data.testNum;
                              _this.centerDialogVisible = true;
                              // _this.centerDialogVisible = false;            //先关闭，
                              // _this.$nextTick(function () {
                              //     _this.centerDialogVisible = true;         //再打开
                              // })
                              console.log(
                                "====== enterDialogVisible ===============>",
                                _this.centerDialogVisible
                              );
                              _this.timer = setInterval(() => {
                                _this.$http.get(
                                  `/api/wx-pay/queryOrder/${res?.data?.orderNo}`,
                                  {},
                                  (res) => {
                                    let queryOrderNo = JSON.parse(
                                      res.data.body
                                    );
                                    if (res.code == "200") {
                                      console.log(
                                        "订单支付回调成功订单状态",
                                        queryOrderNo.trade_state
                                      );
                                      console.log("订单支付回调成功", res);
                                      if (
                                        queryOrderNo.trade_state == "SUCCESS"
                                      ) {
                                        _this.JumpJudgment(item.id);
                                        _this.centerDialogVisible = false;
                                        console.log("订单支付回调成功", res);
                                      } else if (
                                        queryOrderNo.trade_state == "CLOSED"
                                      ) {
                                        _this.wxPayCode =
                                          queryOrderNo.trade_state;
                                        _this.trade_state_closed =
                                          queryOrderNo.trade_state;
                                        console.log(
                                          "订单支付回调成功===========CLOSED》",
                                          _this.trade_state_closed
                                        );
                                      } else {
                                        _this.trade_state_closed =
                                          queryOrderNo.trade_state;
                                        //  clearInterval(_this.timer);
                                        console.log(
                                          "订单支付回调成功CLOSED===========》",
                                          _this.trade_state_closed
                                        );
                                      }
                                    } else {
                                      _this.centerDialogVisible = false;
                                      _this.$message.error("支付失败");
                                    }
                                  }
                                );
                              }, 1000);
                            } else {
                              console.log("====== 999999==============>");
                            }
                          },
                          (res) => {
                            console.log(
                              "======fanghui=99999================>",
                              res
                            );
                          }
                        );
                      } else {
                        _this.JumpJudgment(item.id);
                        _this.centerDialogVisible = false;
                        console.log("=====成功过-------===============>");
                      }
                    }
                  );
                } else {
                  _this.JumpJudgment(item.id);
                  _this.centerDialogVisible = false;
                  console.log("=====成功过-------===============>");
                }
              }
            }
          );
        } else {
          _this.JumpJudgment(item.id);
        }
        // 支付end
        //跳转页面到结果页面
        // this.JumpJudgment(item.id);
      } else {
        this.$router.push({
          path: "ContainerSys/persionDetail",
          query: {
            phone: this.userBid,
            id: item.id,
          },
        });
      }
    },
    JumpJudgment(id) {
      this.$http.get(`getRecordById?id=${id}`, {}, (res) => {
        if (res.code == 2001) {
          this.$message.warning(res.msg);
          return;
        }
        if (res && res.code == 200) {
          if (res.data?.userRecordEntity.type == '1') {
            sessionStorage.setItem("testResult", JSON.stringify(res?.data));
            let versionNo = JSON.parse(res.data?.userRecordEntity?.testResult).versionNo;
            if (versionNo == '2.0.1' || versionNo == '2.0' ) {
              sessionStorage.setItem("backToPageFlag", 'testResultNew')
              this.$router.push({
                name: "testResultNew",
                query: {
                  id: res.data?.userRecordEntity?.id,
                  title: res.data?.userRecordEntity?.name,
                  come: 2, //1-来自认知任务列表，2-测试记录列表
                },
              });
            } else {
              sessionStorage.setItem("backToPageFlag", 'PersionDetail')
              this.$router.push({
                path: "/PersionDetail",
                params: {
                  id: id,
                },
                query: {
                  phone: this.userBid,
                  id: id,
                  backPage: 1,
                },
              });
            }
          } else {
            sessionStorage.setItem("backToPageFlag", 'personalCenter')
            this.$router.push({
              path: "/persionDetailSCl",
              params: {
                id: id,
              },
              query: {
                // phone: this.userBid,
                id: id,
                come: 2,
              },
            });
          }
        } else {
          this.$message({
            message: "获取数据失败！服务器异常",
            type: "error",
          });
        }
      });
    },
    goBack() {
      let userType = sessionStorage.getItem("f7a42fe7211f98ac7a60a285ac3a9528");
      if (userType == 1) {
        //普通用户
        this.$router.push({
          name: "MainTable",
        });
      } else {
        //管理员用户
        this.$router.push({
          path: "/ContainerSys",
        });
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.personal-center-container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;

  .top-line {
    justify-content: space-between;

    ::v-deep .el-breadcrumb {

      .el-breadcrumb__inner,
      .el-breadcrumb__separator,
      .el-breadcrumb__inner a {
        color: white;
        font-size: 0.086rem;

        &:hover {
          color: white;
        }
      }
    }

    .input-with-select {
      width: 240px;
    }
  }

  .card-list {
    width: 100%;
    height: calc(100% - 112px);

    ul {
      display: flex;
      height: 100%;
      justify-content: flex-start;
      flex-wrap: wrap;
      font-family: PingFang SC;

      li {
        width: 230px;
        height: calc(50% - 30px);
        background: rgb(255, 255, 255);
        box-shadow: 0 3px 6px #d4d4d4;
        border-radius: 12px;
        margin: 0 28px 30px;
        overflow: hidden;
        position: relative;

        img {
          width: 100%;
          height: 48%;
          margin-bottom: 9px;
        }

        h2 {
          width: calc(100% - 18px);
          margin-left: 9px;
          font-size: 0.086rem;
          font-weight: 500;
          line-height: 20px;
          color: #333333;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }

        .content {
          font-size: 0.076rem;
          font-weight: 400;
          line-height: 20px;
          color: #999999;
          width: calc(100% - 18px);
          margin-left: 9px;
          margin-top: 8px;
        }

        .goDetail {
          width: calc(100% - 18px);
          position: absolute;
          left: 9px;
          bottom: 12px;
          font-size: 0.086rem;
          font-weight: 400;
          line-height: 20px;
          color: #007EFF;
          cursor: pointer;
        }
      }
    }
  }
}

@media screen and (max-width: 1024px) {
  .cardList ul li {
    margin: 30px 10px;
  }

  .wrap {
    width: 100%;
    margin: 0;
  }
}



.pageNationBox {
  padding: 20px 10px;
  text-align: center;
}

.view-text {
  /**
	思路：
	1.设置inline-block属相
	2.强制不换行
	3.固定高度
	4.隐藏超出部分
	5.显示“……”
  */
  display: inline-block;
  word-break: keep-all;
  white-space: nowrap;
  width: 960px;
  overflow: hidden;
  text-overflow: ellipsis;
}

.imgSiz {
  width: 120px;
  height: 75px;
  margin-right: 15px;
}

.search_box {
  display: flex;
}

.search_box /deep/ .el-input {
  width: 300px;
  margin: 16px 0 0 35px;
}
</style>
