<template>
  <div class="wrapper">
    <div class="title">
      <div class="nav">
        <img src="@/assets/common/back_icon.png" alt="" @click="back" />
        <p>镇江人才码</p>
      </div>
      <div class="talents-info">
        <div>
          <div class="logo">
            <img src="@/assets/talents/logo_icon.png" alt="" />
            <p>镇江人才码</p>
          </div>
          <div v-if="show" class="name">姓名：{{ detail.name }}</div>
          <div v-if="show" class="time">更新于：{{ detail.updateTime }}</div>
        </div>
        <img
          v-if="show"
          class="avatar"
          :src="detail.headPortrait"
          alt=""
          @click="imgpreview(detail.headPortrait)"
        />
      </div>
    </div>
    <div class="nodata" v-if="state !== 3">
      <img src="@/assets/talents/nodata_icon.png" alt="" />
      <p v-if="state === -1">您目前没有申请人才码</p>
      <p v-if="state === 0">您还未提交人才码申请～</p>
      <p v-if="state === 1">您的人才码申报信息正在审核中～</p>
      <p v-if="state === 2">
        您的人才码申报信息正在公示中，五天公示期结束后，将自动为您生成人才码，可点击人才码公示名单查看～<br /><br />
        <span>状态：已公示 </span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <span>已公示天数：{{ detail.pubDayNum ? detail.pubDayNum : 0 }}天</span>
      </p>
      <p v-if="state === 4">
        您的人才码申报信息已被暂停公示，需要等审核人员复查结束后恢复公示～
      </p>
      <p v-if="state === 5">您的人才码申报信息已被拒绝～</p>
      <p v-if="state === 6">
        您的人才码申报信息已被撤销，请查看原因后重新提交～
      </p>
      <p v-if="state === 5 || state === 6">拒绝原因：{{ reason }}</p>
      <p v-if="state === 7">您的人才码信息已过期，请重新申领人才码～</p>
      <p v-if="state === 8">审核逾期，请重新申请～</p>
    </div>
    <div class="qrcode" v-if="state === 3">
      <vue-qr
        style="display: block; margin: auto"
        :logoSrc="downloadData.icon"
        :text="downloadData.url"
        :size="230"
        :logoScale="20"
      ></vue-qr>
      <div class="reload" @click="reload">
        <van-icon name="replay" color="#1E90FF" size="16" />
        <p>手动刷新</p>
      </div>

      <!-- <p class="button_center"><span @click="nothing">可享受政策</span></p> -->
    </div>
    <div class="foot">
      <div class="buttonwrapper">
        <van-button
          v-if="state === -1"
          class="button"
          round
          color="#0687D2"
          @click="report"
          >去申请</van-button
        >
        <van-button
          v-if="state === 0"
          class="button"
          round
          color="#0687D2"
          @click="report"
          >去提交申请</van-button
        >
        <van-button
          v-if="state === 1 || state === 2 || state === 3 || state === 4"
          class="button"
          round
          color="#0687D2"
          @click="report"
          >查看申请信息</van-button
        >
        <van-button
          v-if="state === 3 || state === 7"
          class="button"
          round
          color="#EB4E3F"
          @click="reborn"
          >重新申领
        </van-button>
        <van-button
          v-if="state === 5 || state === 6 || state === 8"
          class="button"
          round
          color="#0687D2"
          @click="report"
          >重新提交
        </van-button>
      </div>
      <div class="link">
        <p @click="jumpGuide">人才码申报指南</p>
        <p @click="openNameList">人才码公示名单</p>
        <p
          @click="
            download(
              'https://www.smart-zj.cn:55901/image/talent20220613',
              'https://www.smart-zj.cn:55901/image/uploadFile/bb66af80-4489-4d59-a1dd-c77a55dac403.pdf'
            )
          "
        >
          政策一本通
        </p>
      </div>
      <div
        style="display: flex; flex-direction: column; margin-top: 10px; align-items: center; line-height: 1.5; font-size: 14px; color: #999999;"
      >
        <div
          style="border-top: 1px solid #ccc; width: 60%; text-align: center; padding-top: 10px;"
        >
          “尚贤”人才服务热线
        </div>
        <div>全年7*24小时提供服务</div>
      </div>
    </div>
    <van-popup v-model="showAreaPicker" position="bottom">
      <van-picker
        title="人才地区类型"
        show-toolbar
        :columns="['国内人员', '外籍人员及港澳台']"
        @confirm="onConfirm"
        @cancel="showAreaPicker = false"
      />
    </van-popup>
    <van-popup v-model="showName" position="bottom" :style="{ height: '70%' }">
      <div class="nameList">
        <van-pull-refresh
          v-model="refreshing"
          class="list"
          @refresh="onRefresh"
        >
          <van-list
            v-model="loading"
            :finished="finished"
            @load="onLoad"
            finished-text="没有更多了"
          >
            <div
              class="cell"
              v-for="(item, index) in list"
              :key="item.talentCode"
              :style="{ background: index % 2 !== 0 ? '#eee' : '#fff' }"
            >
              <p class="name">{{ item.name }}</p>
              <p class="phone">{{ item.phone }}</p>
              <p class="type">{{ item.categoryName + "类" }}</p>
              <p class="phone">
                {{ "已公示" + (item.pubDayNum ? item.pubDayNum : "0") + "天" }}
              </p>
              <div class="button">
                <van-button
                  color="#0687D2"
                  size="small"
                  @click="callPhone(item.branchPhone)"
                  >异 议</van-button
                >
              </div>
            </div>
          </van-list>
        </van-pull-refresh>
      </div>
    </van-popup>
  </div>
</template>

<script>
import Vue from "vue";
import vueQr from "vue-qr";
import {
  Button,
  Picker,
  Popup,
  PullRefresh,
  List,
  ImagePreview,
  Icon,
} from "vant";
import { get, getList, del, querySfbUserInfo } from "@/api/talents";
import { config2 } from "@/utils/axios";
// import { encryptByDES,decryptByDES } from "@/utils/utils";
import { decryptByDES } from "@/utils/utils";

Vue.use(Button)
  .use(Picker)
  .use(Popup)
  .use(PullRefresh)
  .use(List)
  .use(ImagePreview)
  .use(Icon);

export default {
  components: {
    vueQr,
  },
  computed: {
    show() {
      return this.state === 3 || this.state === 4 || this.state === 7;
    },
  },
  data() {
    return {
      userInfo: {},
      state: null,
      reason: "",
      talentCode: "",
      detail: {},
      showAreaPicker: false,
      showName: false,
      refreshing: false,
      loading: false,
      finished: true,
      pageNum: 1,
      list: [],
      downloadData: {
        url: "",
        icon: "",
      },
    };
  },
  methods: {
    back() {
      if (window.android !== undefined) {
        window.android.backHome();
      } else {
        window.webkit && window.webkit.messageHandlers.backHome.postMessage("");
      }
    },
    init() {
      this.$toast.loading({
        duration: 0, // 持续展示 toast
        forbidClick: true,
        message: "查询中...",
      });
      // alert(this.userInfo)
      get({
        appId: 1234,
        // userId: encryptByDES(this.userInfo.userId.toString(), "MnuYbhGv"),
        idCard: this.userInfo.idCardNo
          ? decryptByDES(this.userInfo.idCardNo, "MnuYbhGv")
          : null,
      }).then((res) => {
        console.log("res------", res);
        // alert(JSON.stringify(res))
        this.$toast.clear();
        if (!res) {
          // 说明还未申请过人才码
          this.state = -1;
        } else {
          this.state = res.state;
          this.reason = res.reason;
          this.detail = res;
          this.talentCode = res.talentCode;
          // 只有状态为3的时候需要展示二维码
          if (this.state === 3) {
            switch (res.categoryName) {
              case "A":
                this.downloadData.icon = require("@/assets/talents/A_qr.png");
                break;
              case "B":
                this.downloadData.icon = require("@/assets/talents/B_qr.png");
                break;
              case "C":
                this.downloadData.icon = require("@/assets/talents/C_qr.png");
                break;
              case "D":
                this.downloadData.icon = require("@/assets/talents/D_qr.png");
                break;
              case "E":
                this.downloadData.icon = require("@/assets/talents/E_qr.png");
                break;
              case "F":
                this.downloadData.icon = require("@/assets/talents/F_qr.png");
                break;
              case "G":
                this.downloadData.icon = require("@/assets/talents/G_qr.png");
                break;
              default:
                break;
            }
            let now = new Date().getTime();
            this.downloadData.url = `${config2.baseH5}talents/showinfo?talentCode=${res.talentCode}&time=${now}`;
          }
          // if (this.state === 2) {
          //   let endTime = new Date().getTime()
          //   let startTime = Date.parse(new Date(res.publicityTime).toString()) - (1000 * 60 * 60 * 24)
          //   let cha = (endTime - startTime)/(1000 * 60 * 60 * 24)
          //   console.log('-----------',cha)
          // }
        }
      });
    },
    reload() {
      let now = new Date().getTime();
      this.downloadData.url = `${config2.baseH5}talents/showinfo?talentCode=${this.talentCode}&time=${now}`;
      console.log(this.downloadData.url);
    },
    onRefresh() {
      this.$toast.loading({
        duration: 0, // 持续展示 toast
        forbidClick: true,
        message: "加载中...",
      });
      getList({
        appId: 1234,
        pageNum: 1,
        pageSize: 10,
      }).then((res) => {
        this.$toast.clear();
        this.refreshing = false;
        this.pageNum = 1;
        this.list = res.list;
        this.finished = !res.hasNextPage;
      });
    },
    onLoad() {
      this.$toast.loading({
        duration: 0, // 持续展示 toast
        forbidClick: true,
        message: "加载中...",
      });
      getList({
        appId: 1234,
        pageNum: this.pageNum + 1,
        pageSize: 10,
      }).then((res) => {
        this.$toast.clear();
        this.loading = false;
        this.pageNum = this.pageNum + 1;
        this.list = this.list.concat(res.list);
        this.finished = !res.hasNextPage;
      });
    },
    jumpGuide() {
      this.$router.push({ name: "TalentRule" });
    },
    openNameList() {
      this.showName = true;
    },
    reborn() {
      this.$dialog
        .confirm({
          message: "重新申领的话，将删除现有人才码数据，您确定重新申领吗？",
        })
        .then(() => {
          del({ appId: 1234, talentCode: this.talentCode }).then((res) => {
            console.log(res);
            this.$toast("删除成功");
            this.init();
            this.showAreaPicker = true;
          });
        })
        .catch(() => {
          console.log("取消");
        });
    },
    download(url, url1) {
      if (this.$route.query.ticket) {
        if (navigator.userAgent.toLowerCase().includes("mac")) {
          console.log(111);
          this.$dialog
            .confirm({
              message: "请点击复制按钮，去浏览器粘贴该链接下载文件",
              confirmButtonText: "复制",
            })
            .then(() => {
              var input = document.createElement("input"); // js创建一个input输入框
              input.value = url1; // 将需要复制的文本赋值到创建的input输入框中
              document.body.appendChild(input); // 将输入框暂时创建到实例里面
              input.select(); // 选中输入框中的内容
              document.execCommand("Copy"); // 执行复制操作
              document.body.removeChild(input); // 最后删除实例中临时创建的input输入框，完成复制操作
              // resolve();
            });
        } else {
          const link = document.createElement("a");
          link.href = url1;
          link.target = "_blank";
          link.download = "人才政策一本通";
          link.style.display = "none";
          document.body.append(link);
          link.click();
          link.remove();
        }
      } else {
        if (window.android !== undefined) {
          window.android.downLoadFile(url);
        } else if (window.webkit !== undefined) {
          window.webkit &&
            window.webkit.messageHandlers.downLoadFile.postMessage(
              `${url1}|showNav`
            );
        } else {
          const link = document.createElement("a");
          link.href = url1;
          link.target = "_blank";
          link.download = "人才政策一本通";
          link.style.display = "none";
          document.body.append(link);
          link.click();
          link.remove();
        }
      }
    },
    report() {
      if (this.state === -1) {
        // 未申请过人才码 展示picker 选择人才归属地
        // this.$router.push({ name: "TalentReport" });
        this.showAreaPicker = true;
      } else {
        this.$router.push({
          name: "ReportForm",
          query: {
            talentCode: this.talentCode,
            ticket: this.$route.query.ticket ? this.$route.query.ticket : "",
          },
        });
      }
    },
    onConfirm(value, index) {
      this.$store.commit("talents/SET_AREA", index);
      if (index === 0) {
        // 国内人员需要实名认证
        if (!this.userInfo.idCardNo) {
          this.$dialog
            .confirm({
              message: "请进入“我的”完成实名认证！",
              showCancelButton: false,
            })
            .then(() => {
              this.back();
            });
        } else {
          this.$router.push({
            name: "TalentReport",
            query: {
              ticket: this.$route.query.ticket ? this.$route.query.ticket : "",
            },
          });
        }
      } else {
        this.$router.push({
          name: "TalentReport",
          query: {
            ticket: this.$route.query.ticket ? this.$route.query.ticket : "",
          },
        });
      }
    },
    JSBgetUserInfo() {
      if (window.android !== undefined) {
        const res = window.android.getUserInfo();
        this.verify(res);
      } else if (window.webkit) {
        window.webkit &&
          window.webkit.messageHandlers.getUserInfo.postMessage("getUserInfo");
      } else {
        this.$dialog
          .confirm({
            message: "请先登录！",
            showCancelButton: false,
          })
          .then(() => {
            this.back();
          });
      }
    },
    getUserInfo(res) {
      this.verify(res);
    },
    verify(res) {
      let userInfo = JSON.parse(res);
      // alert(JSON.stringify(userInfo))
      if (!userInfo.userId) {
        this.$dialog
          .confirm({
            message: "请先登录！",
            showCancelButton: false,
          })
          .then(() => {
            this.back();
          });
        return;
      }
      sessionStorage.setItem("ZJCD-UserInfo", res);
      this.userInfo = userInfo;
      sessionStorage.setItem("token", this.userInfo.token), this.init();
    },
    callPhone(branchPhone) {
      if (window.android !== undefined) {
        window.android.callPhone(branchPhone);
      } else if (window.webkit) {
        window.webkit &&
          window.webkit.messageHandlers.callPhone.postMessage(branchPhone);
      }
    },
    imgpreview(url) {
      ImagePreview({
        images: [url],
      });
    },
    initInfo(val) {
      console.log(val);
      querySfbUserInfo({
        ticket: val,
      }).then((res) => {
        console.log(res);
        if (!res) {
          this.$dialog
            .confirm({
              message: "请先登录！",
              showCancelButton: false,
            })
            .then(() => {
              this.back();
            });
          return;
        } else {
          // alert(JSON.stringify(res))
          sessionStorage.setItem("ZJCD-UserInfo", JSON.stringify(res));
          this.userInfo = res;
          this.init();
        }
      });
    },
  },
  mounted() {
    window.getUserInfo = this.getUserInfo;
  },
  created() {
    this.onRefresh();
    if (this.$route.query.ticket) {
      // alert(sessionStorage.getItem("ZJCD-UserInfo"))
      if (sessionStorage.getItem("ZJCD-UserInfo")) {
        this.userInfo = JSON.parse(sessionStorage.getItem("ZJCD-UserInfo"));
        // alert(this.userInfo)
        this.init();
      } else {
        // 对接江苏政务服务网
        this.initInfo(this.$route.query.ticket);
      }
    } else {
      let res = sessionStorage.getItem("ZJCD-UserInfo");
      this.userInfo = JSON.parse(res) || {};
      if (!this.userInfo.idCardNo) {
        this.JSBgetUserInfo();
      } else {
        this.verify(res);
      }
    }
  },
};
</script>

<style lang="stylus" scoped>
.wrapper {
  height: 100vh;
  overflow-y: auto;

  .title {
    height: 448px;
    background: url('~@/assets/talents/title_bg.png');
    background-size: 100% 100%;

    .nav {
      position relative
      width 100%;
      height 88px;
      display flex;
      align-items center;
      justify-content center;

      img {
        position absolute
        left: 30px;
        top: 0;
        bottom: 0;
        margin: auto;
        width: 40px;
        height: 41px;
      }

      p {
        font-size: 36px;
        color: #FFFFFF;
      }
    }

    .talents-info {
      margin-top 60px;
      padding 0 30px;
      display flex;
      align-items center
      justify-content space-between

      .logo {
        display: flex;
        align-items: center;

        img {
          width: 70px;
          height: 70px;
        }

        p {
          margin-left: 30px;
          font-size: 40px;
          color: #FFFFFF;
        }
      }

      .name {
        margin-top: 20px;
        font-size: 48px;
        font-weight: 500;
        color: #FFFFFF;
        line-height: 67px;
      }

      .time {
        margin-top: 29px;
        font-size: 30px;
        color: #FFFFFF;
        line-height: 42px;
      }

      .avatar {
        width: 175px;
        max-height 220px;
      }
    }

  }

  .nodata {
    width 100%
    margin-top 50px;
    display flex;
    flex-direction: column;
    align-items center;
    justify-content center;

    img {
      width 231px;
      height: 231px;
    }

    p {
      width: 500px;
      margin-top 28px;
      text-align center;
      font-size: 30px;
      color: #999999;
      line-height: 42px;
    }
  }

  .tips {
    margin-top: 20px;
    padding: 20px;
    background: #fff;
    font-size: 32px;
    line-height: 40px;
    color: #333333;
  }

  .qrcode {
    // width: 100%;
    // height: 440px;
    margin: 30px auto 0;

    .reload {
      margin: 20px 0;
      display: flex;
      align-items center;
      justify-content center

      p {
        margin-left 10px;
        font-size 20px;
        color #333;
      }
    }

    .button_center{
      font-size:20px;
      margin: 30px auto 0;
      text-align:center;
      color:#eb4e3f;
    }
  }

  .foot {
    position: absolute;
    bottom: 30px;
    left: 0;
    width: 100%;

    .buttonwrapper {
      display flex;
      align-items center;
      justify-content space-around;

      .button {
        width: 300px;
      }
    }

    .link {
      display: flex;
      align-items: center;
      justify-content: space-around;

      p {
        margin-top: 30px;
        text-align: center;
        font-size: 24px;
        color: #0687D2;
        line-height: 33px;
      }
    }
  }

  .nameList {
    margin: 30px;
    border: 1px solid #eee;

    .list {
      height: calc(70vh - 63px);
      overflow: auto;

      .cell {
        height: 88px;
        display: flex;
        align-items: center;

        .name {
          width: 16%;
          text-align: center;
          color: #333333;
          font-size: 28px;
        }

        .phone {
          width: 27%;
          text-align: center;
          color: #333333;
          font-size: 28px;
        }

        .type {
          width: 10%;
          text-align: center;
          color: #333333;
          font-size: 28px;
        }

        .button {
          width: 20%;
          text-align: center;
        }
      }
    }
  }
}
</style>
