<template>
  <div class="wrap">
    <div class="top-wrap"></div>
    <div class="center-info">
      <div class="wei_code_wrap">
        <div class="wei_title">请先添加企业微信，保证申请流程正常进行。</div>
        <div class="wei_code_bg">
          <img v-if="qrCodeUrl" :src="qrCodeUrl" alt="企业微信二维码" />
        </div>
      </div>
    </div>
    <div class="btn_wrap">
      <div class="btn" @click="nextStep">下一步</div>
    </div>
  </div>
</template>

<script>
  import QRCode from 'qrcode'
  import {getOrCodeInfo, getContactQrCodeResult, saveSupplier} from "@/api/mine"
  import {myMixins} from "@/utils/myMixins"
  import {Toast, Dialog} from "vant";
  export default {
    name: "addWechat",
    mixins: [myMixins],
    data() {
      return {
        name: '',
        potentialFlag: '',
        formPayload: null,
        qrCodeUrl: '',
        qrCode: '',
        configId: '',
        wechatId: '',
        clickFlag: true,
      }
    },
    async mounted() {
      const urlParams = new URLSearchParams(window.location.search);
      this.potentialFlag = this.$route.query.potentialFlag || urlParams.get('potentialFlag') || '';
      const cached = localStorage.getItem('supplierAddForm');
      if (cached) {
        this.formPayload = JSON.parse(cached);
        this.wechatId = this.formPayload.wechatId;
        this.name = this.formPayload.name;
      }
      if (this.name) {
        await this.QrCodeHandler();
      }
    },
    methods: {
      async QrCodeHandler() {
        await this.QrCodeInfo();
        await this.getQrCode();
      },
      async QrCodeInfo() {
        let res = await getOrCodeInfo({ name: this.name });
        this.configId = res?.configId;
        this.qrCode = res?.qrCode;
      },
      async getQrCode() {
        try {
          this.qrCodeUrl = await QRCode.toDataURL(this.qrCode, {
            width: 150,
            margin: 2,
            color: { dark: '#000000', light: '#FFFFFF' },
          });
        } catch (error) {
          console.error('生成二维码失败:', error);
        }
      },
      async nextStep() {
        if (!this.clickFlag) return;
        if(!this.wechatId) {
          let res = await getContactQrCodeResult({ configId: this.configId, name: this.name, phone: this.formPayload.linkPhone });
          this.wechatId = res?.data?.wechatId;
        }
        /*if (!this.wechatId) {
          Toast('请先添加企微再继续');
          return;
        }*/
        try {
          this.clickFlag = false;
          const res = await saveSupplier({
            ...this.formPayload,
            wechatId: this.wechatId,
          });
          if (res?.noToast) {
            if (res?.code != 0) {
              Dialog.alert({ title: '提示', message: '该服务商已存在，查看信息' }).then(() => {
                localStorage.removeItem('supplierAddForm');
                const target = { name: 'supplierInfo', query: { id: res?.code, potentialFlag: this.potentialFlag } };
                localStorage.setItem('lastRoute', JSON.stringify(target));
                this.goPage('supplierInfo', { id: res?.code, potentialFlag: this.potentialFlag });
              });
            } else {
              Toast('该服务商已存在');
            }
          } else {
            localStorage.removeItem('supplierAddForm');
            const supplierId = res?.data;
            const potentialFlag = this.potentialFlag;
            const target = { name: 'supplierAddResult', query: { id: supplierId, potentialFlag } };
            localStorage.setItem('lastRoute', JSON.stringify(target));
            Dialog.confirm({
              title: '提示',
              message: '添加车辆和驾驶员会加快审核进度，是否去添加？',
              confirmButtonText: '去添加',
              cancelButtonText: '取消',
            }).then(() => {
              localStorage.setItem('lastRoute', JSON.stringify({ name: 'vehicleManage', query: { id: supplierId, potentialFlag } }));
              this.goPage('vehicleManage', { id: supplierId, potentialFlag });
            }).catch(() => {
              localStorage.setItem('lastRoute', JSON.stringify({ name: 'supplierAddResult', query: { id: supplierId, potentialFlag } }));
              this.goPage('supplierAddResult', { id: supplierId, potentialFlag });
            });
          }
        } catch (e) {
          Toast(e?.message || '提交失败');
        } finally {
          setTimeout(() => { this.clickFlag = true; }, 1000);
        }
      }
    }
  }
</script>

<style scoped lang="scss">
  @import "@/styles/mixin.scss";
  @import "@/styles/common.scss";
  .wrap {
    @include wh(100%, 100%);
    box-sizing: border-box;
    padding-bottom: 100px;
    overflow-y: auto;
    background: linear-gradient(180deg, #FBFDFE 0%, #F6FBFF 73%, #F0F7FF 100%);
    backdrop-filter: blur(5.602678571428572px);
  }
  .top-wrap {
    width: 100%;
    height: 175px;
    background: linear-gradient(180deg, #DAECFF 0%, rgba(233, 243, 255, 0) 100%);
  }
  .center-info {
    text-align: center;
  }
  .wei_code_wrap {
    margin-top: 10px;
    .wei_title {
      font-size: 15px;
      color: #FF553B;
      text-align: center;
    }
    .wei_code_bg {
      width: 163px;
      height: 173px;
      background-image: url("~@/assets/supplier/weiCodeBg.png");
      background-size: 100% 100%;
      margin: 8px auto;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
  .btn_wrap {
    width: 100%;
    padding: 15px 0;
    position: fixed;
    bottom: 10px;
    z-index: 10000 !important;
    .btn {
      width: calc(100% - 80px);
      margin-left: 40px;
      height: 46px;
      background: #0E76F4;
      border-radius: 5px;
      font-size: 15px;
      color: #FFFFFF;
      text-align: center;
      line-height: 46px;
    }
  }
</style>
