<template>
  <div class="identity">
    <div class="codeCard">
      <van-tabs
        v-model="activeName"
        @click="init"
        sticky
        animated
        title-inactive-color="#999999"
        title-active-color="#5987FF"
        color="#5987FF"
      >
        <van-tab
          v-for="item in titleList"
          :title="item.name"
          :key="item.id"
          :name="item.id"
        >
          <div v-if="!noData" class="qrcode">
            <img
              id="qr-code"
              :src="url"
              @click="preview"
              style="width: 180px; height: 180px"
            />
          </div>
          <div class="refresh" v-if="!noData && item.id == 3" @click="reload">
            <img
              src="./img/refresh.png"
              style="width: 14px; height: 14px; margin-right: 10px"
              alt=""
            />
            点击手动刷新二维码
          </div>
          <div v-if="noData" class="noData">
            <img
              id="qr-code"
              :src="url"
              style="width: 180px; height: 180px; opacity: 0.05"
            />
            <div class="noOpen">
              <div class="name">您暂未开通</div>
              <div class="open" @click="jump(item)">立即开通</div>
            </div>
          </div>
        </van-tab>
      </van-tabs>
    </div>
    <div class="rideService">
      <div class="title">
        <div class="icon"></div>
        <div class="name">乘车服务</div>
      </div>
      <div class="rideCard">
        <div class="rideLeft">
          <img class="rideImg" src="./img/rideImg.png" alt="" />
          <div class="busCode">公交码</div>
        </div>
        <div class="byBus" @click="byBus">去乘车</div>
      </div>
    </div>
  </div>
</template>

<script>
import Vue from "vue";
import QRCode from "qrcode";
import { Tab, Tabs, ImagePreview } from "vant";
import { encryptByDES, decryptByDES } from "@/utils/utils";
import { getNucleicAcidCode } from "@/api/identity";
import { getOwn } from "@/api/reverse";
import { get } from "@/api/talents";
import { config } from "@/utils/request";

Vue.use(Tab);
Vue.use(Tabs);
Vue.use(ImagePreview);
export default {
  data() {
    return {
      activeName: 2,
      titleList: [
        {
          name: "个人通行码",
          id: 1,
        },
        {
          name: "核酸采样码",
          id: 2,
        },
        {
          name: "人才码",
          id: 3,
        },
      ],
      noData: true,
      url: "",
      userInfo: {},
      talentCode: "",
      txmCode: "",
    };
  },
  methods: {
    getCode(obj) {
      let that = this;
      QRCode.toDataURL(
        obj,
        {
          errorCorrectionLevel: "H",
          type: "image/png",
          quality: 0.5,
          margin: 1,
          w: 600,
          h: 600,
          color: {
            dark: "#000",
            light: "#fff",
          },
        },
        function (err, url) {
          if (err) throw err;
          that.url = url;
        }
      );
    },
    preview() {
      ImagePreview([this.url]);
    },
    jump(item) {
      switch (item.id) {
        case 1:
          this.$router.replace({ name: "ReverseIndex" });
          break;
        case 2:
          if (process.env.NODE_ENV === "production") {
            window.location.replace("https://appointment.smart-zj.cn");
          } else {
            window.location.replace(
              "http://81.69.44.115/zjh/html/covid/#/testing"
            );
          }
          break;
        case 3:
          this.$router.replace({ name: "TalentsIndex" });
          break;
        default:
          break;
      }
    },
    // 切换二维码类型
    init(name) {
      switch (name) {
        case 1:
          this.initTxm();
          break;
        case 2:
          this.initCym();
          break;
        case 3:
          this.initRcm();
          break;
        default:
          break;
      }
    },
    // 获取通行码信息
    initTxm() {
      if (this.txmCode) {
        if (process.env.NODE_ENV === "production") {
          this.initData(
            encodeURI(`${config.baseH5}reverse/register?code=${this.txmCode}`)
          );
        } else {
          // this.downloadData.url = encodeURI(
          //     `http://192.168.3.119:8080/#/reverse/register?code=${this.code}`
          this.initData(
            encodeURI(
              `http://192.168.3.119:8080/#/reverse/register?code=${this.txmCode}`
            )
          );
        }
      } else {
        getOwn({
          uid: encryptByDES(this.userInfo.userId.toString(), "MnuYbhGv"),
          userType: 0,
        }).then((res) => {
          if (res.data) {
            this.txmCode = res.data.code;
            if (process.env.NODE_ENV === "production") {
              this.initData(
                encodeURI(
                  `${config.baseH5}reverse/register?code=${res.data.code}`
                )
              );
            } else {
              // this.downloadData.url = encodeURI(
              //     `http://192.168.3.119:8080/#/reverse/register?code=${this.code}`
              this.initData(
                encodeURI(
                  `http://192.168.3.119:8080/#/reverse/register?code=${res.data.code}`
                )
              );
            }
          } else {
            this.initNoData();
          }
        });
      }
    },
    // 获取核酸采样码信息
    initCym() {
      let params = {
        // userId: encryptByDES(this.userInfo.userId.toString(), "MnuYbhGv"),
        idCard: this.userInfo.idCardNo ? this.userInfo.idCardNo : ''
      }
      getNucleicAcidCode(params).then((res) => {
        if (res.data) {
          // 加密内容
          let obj = {
            // 姓名
            name: encryptByDES(res.data.name, "zjyyhedj2022covid2019"),
            // 身份证号
            cardNo: encryptByDES(
              decryptByDES(res.data.idCard, "MnuYbhGv"),
              "zjyyhedj2022covid2019"
            ),
            C: res.data.cardType == "1" ? 1 : 0,
            // 居住地址
            A: encryptByDES(
              res.data.addressArea + res.data.village + res.data.detailAddress,
              "zjyyhedj2022covid2019"
            ),
            // 手机号
            P: encryptByDES(res.data.mobile, "zjyyhedj2022covid2019"),
          };
          this.initData(JSON.stringify(obj));
        } else {
          this.initNoData();
        }
      }).catch(() => {
        this.initNoData();
      });
    },
    // 获取人才码信息
    initRcm() {
      if (this.talentCode) {
        this.reload();
      } else {
        get({
          appId: 1234,
          idCard: this.userInfo.idCardNo ? decryptByDES(this.userInfo.idCardNo, "MnuYbhGv") : null
        }).then((res) => {
          if (!res || res.state != 3) {
            this.initNoData();
          } else {
            this.talentCode = res.talentCode;
            let now = new Date().getTime();
            this.initData(
              `${config.baseH5}talents/showinfo?talentCode=${res.talentCode}&time=${now}`
            );
          }
        });
      }
    },
    // 刷新人才码
    reload() {
      let now = new Date().getTime();
      this.initData(
        `${config.baseH5}talents/showinfo?talentCode=${this.talentCode}&time=${now}`
      );
    },
    // 获取到数据的二维码信息
    initData(src) {
      this.noData = false;
      this.getCode(src);
    },
    // 未获取的二维码信息，默认展示
    initNoData() {
      this.noData = true;
      let src = "http://www.smart-zj.cn:55902/zjh/html/pages/index.html";
      this.getCode(src);
    },
    // 跳转乘车二维码
    byBus() {
      window.location.replace(
        "http://zhzjgj.longyixing.cn/zhzjgj/index/toIndex?noTitle=1"
      );
    },
    // 初始化获取userInfo
    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.init(2);
      }
    },
    getUserInfo(res) {
      this.verify(res);
    },
    verify(res) {
      let userInfo = JSON.parse(res);
      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(2);
    },
    // 返回首页
    back() {
      if (window.android !== undefined) {
        window.android.backHome();
      } else {
        window.webkit && window.webkit.messageHandlers.backHome.postMessage("");
      }
    },
  },
  created() {
    let res = sessionStorage.getItem("ZJCD-UserInfo");
    this.userInfo = JSON.parse(res) || {};
    if (!this.userInfo.idCardNo) {
      this.JSBgetUserInfo();
    } else {
      this.verify(res);
    }
  },
  mounted() {
    window.getUserInfo = this.getUserInfo;
  },
};
</script>

<style lang="stylus" scoped>
.identity {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px;
  box-sizing: border-box;
  background: #F3F6F9;

  .codeCard {
    width: 100%;
    background: #FFFFFF;
    border-radius: 16px;

    .qrcode {
      width: 100%;
      height: 600px;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
    }

    .refresh {
      width: 100%;
      position: fixed;
      top: 520px;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 28px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #5987FF;
    //   margin-bottom: 50px;
    }

    .noData {
      width: 100%;
      height: 600px;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      position: relative;

      .noOpen {
        position: absolute;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;

        .name {
          font-size: 30px;
          font-family: PingFangSC-Regular, PingFang SC;
          font-weight: 400;
          color: #333333;
          margin-bottom: 50px;
        }

        .open {
          width: 240px;
          height: 64px;
          background: linear-gradient(311deg, #5987FF 0%, #8CADFF 100%);
          box-shadow: 0px 15px 18px -2px rgba(235, 78, 63, 0.2);
          border-radius: 32px;
          font-size: 32px;
          font-family: PingFangSC-Medium, PingFang SC;
          font-weight: 500;
          color: #FFFFFF;
          line-height: 64px;
          text-shadow: 0px 2px 16px rgba(0, 0, 0, 0.14);
          text-align: center;
        }
      }
    }
  }

  .rideService {
    display: flex;
    flex-direction: column;
    width: 100%;
    background: #FFFFFF;
    box-shadow: 0px 2px 12px 0px rgba(0, 0, 0, 0.06);
    border-radius: 16px;
    margin-top: 20px;

    .title {
      display: flex;
      align-items: center;
      padding: 30px;
      box-sizing: border-box;

      .icon {
        width: 6px;
        height: 28px;
        background: #EB4E3F;
        box-shadow: 0px 2px 12px 0px rgba(0, 0, 0, 0.06);
        border-radius: 2px;
        margin-right: 10px;
      }

      .name {
        font-size: 32px;
        font-family: PingFangSC-Medium, PingFang SC;
        font-weight: 500;
        color: #333333;
        text-shadow: 0px 2px 12px rgba(0, 0, 0, 0.06);
      }
    }

    .rideCard {
      display: flex;
      align-items: center;
      justify-content: space-between;

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

        .rideImg {
          width: 150px;
          height: 150px;
        }

        .busCode {
          font-size: 32px;
          font-family: PingFangSC-Regular, PingFang SC;
          font-weight: 400;
          color: #696969;
          text-shadow: 0px 2px 12px rgba(0, 0, 0, 0.06);
        }
      }

      .byBus {
        width: 150px;
        height: 60px;
        box-shadow: 0px 2px 12px 0px rgba(0, 0, 0, 0.06);
        border-radius: 30px;
        border: 2px solid #EEEEEE;
        font-size: 32px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #333333;
        line-height: 60px;
        text-shadow: 0px 2px 12px rgba(0, 0, 0, 0.06);
        text-align: center;
        margin-right: 40px;
      }
    }
  }
}
</style>