<template>
  <view class="content">
  </view>
</template>

<script>
import request from '../../utils/request';
import {
  loginAppuserName,
} from '@/api/login.js';
import {
  setToken,
  getToken,
  setTenantId,
  removeToken
} from '@/utils/auth.js'
import {
  login,
  getInfo,
  getTenantIdByWebsite
} from '@/api/login.js'
import drawQrcode from "weapp-qrcode";

export default {
  data() {
    return {
      //用户微信openId
      openId: "",
      phoneNumber: "",
      baseUrl: this.$baseUrl,
      isButtonDisabled: false,
      countdownTime: 60,
      qindex: false,
      sfindex: 'user',
      userName: '',
      yzm: '',
      wrod: '',
      activeid: 0,
      tenantCode: 'lanan',
      // 标志位，初始值为false
      isFirstLoad: false
    }
  },
  computed: {
    groupChange(n) {
      console.log('groupChange', n);
    },
    radioChange(n) {
      console.log('radioChange', n);
    },
    buttonText() {
      if (this.isButtonDisabled) {
        return `${this.countdownTime}s 后重新发送`;
      } else {
        return "获取验证码";
      }
    },
  },
  mounted() {
  },
  created(){
    // 如果是第一次加载，执行一些初始化操作
    if (!this.isFirstLoad) {
      this.isFirstLoad = true;
      // 初始化代码
      this.checkIfLogin()
    }
  },
  onShow() {
    // 如果不是第一次加载，不执行任何操作
    if (this.isFirstLoad) {
      // 每次页面显示时需要做的操作
      if(getToken()){
        //已登录
        uni.reLaunch({
          url: '/pages/home/home'
        })
      }else {
        uni.showModal({
          title: '提示',
          content: '请关闭本页面重新打开',
          success: function (res) {
            if (res.confirm) {
              console.log('用户点击确定');
              // 用户点击了确定按钮的相关逻辑可以在这里编写
            } else if (res.cancel) {
              console.log('用户点击取消');
              // 用户点击了取消按钮的相关逻辑可以在这里编写
            }
          }
        });
      }
    }
  },

  methods: {
    checkIfLogin(){
      if(getToken()){
        //已登录
        uni.reLaunch({
          url: '/pages/home/home'
        })
      }else{
        //未登录
        this.checkIfCode()
      }
    },
    /**
     *判断是否有code
     * */
    checkIfCode(){
      let code = this.getUrlCode('code')
      if (code !== null && code !== "") {
        //自动登录
        this.getOpenidAndUserinfo(code)
      } else {
        uni.showToast({
          title: '未获取到授权信息，请重新进入！！',
          icon: 'none'
        })
      }
    },
    /**
     * 微信自动登录
     * @param {Object} code 用户code
     */
    async getOpenidAndUserinfo(code) {
      await request({
        url: '/userClient/weChat/wechatLogin',
        method: 'get',
        params: {code:code}
      }).then((res) => {
        if (res.code==200) {
          if(res.data.hasOwnProperty("accessToken")){
            setToken(res.data.accessToken)
            uni.reLaunch({
              url: '/pages/home/home'
            })
          }else{
            //去注册
            this.openId = res.data
            //跳转到注册页
            this.goregister()
          }
        } else {
          uni.showToast({
            title: res.msg,
            icon: 'none'
          })
        }
      })
    },
    /**
     * 获取路径中的参数
     * @param {Object} name
     */
    getUrlCode(name) {
      return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ''])[1].replace(/\+/g, '%20')) || null
    },
    setidentity(text) {
      this.sfindex = text

    },
    //登录请求
    getlogin() {
      if (this.qindex != true) {
        uni.showToast({
          icon: "none",
          title: "请阅读并勾选用户协议",
          duration: 2000
        })
        return;
      }
      if (this.userName == '') {
        uni.showToast({
          title: '输入框不能为空！',
          icon: 'none'
        })
        return
      }

      uni.setStorageSync('identity', this.sfindex);

      const loginFun = () => {
        const data = {
          username: this.userName,
          password: this.wrod,
          type: 0
        }
        loginAppuserName(data).then(res => {
          if (res.code==200) {
            if(res.data.hasOwnProperty("accessToken")){
              setToken(res.data.accessToken)
              uni.reLaunch({
                url: '/pages/home/home'
              })
            }else{
              uni.showToast({
                title: '登录失败',
                icon: 'none'
              })
            }
          } else {
            uni.showToast({
              title: res.msg,
              icon: 'none'
            })
          }
          // if (res.data.needMobile === "1") {
          //   uni.navigateTo({
          //     url: '/pages/login/bindPhoe'
          //   })
          //   uni.setStorageSync('validaCodeToken', res.data.accessToken)
          // } else {
          //   setToken(res.data.accessToken)
          //   uni.reLaunch({
          //     url: '/pages/home/home'
          //   })
          // }
        })
      }

      getTenantIdByWebsite(this.tenantCode).then(res => {
        if (res.code === 200 && res.data && res.data.length > 0) {
          uni.showActionSheet({
            itemList: res.data.map(m => m.name),
            success: ({
                        tapIndex
                      }) => {
              setTenantId(res.data[tapIndex].id)
              loginFun()
            }
          })
        } else {
          setTenantId('')
          loginFun()
        }
      })
    },
    getxz(index) {
      this.activeid = index
    },
    goregister() {
      uni.navigateTo({
        url: '/pages/my/register?openId='+this.openId
      })
    },
    goforgot() {
      uni.navigateTo({
        url: '/pages/login/forgot'
      })
    },
    goselect() {
      console.log('执行去救援', this.sfindex);
      // pages/rescue/trafficPolice
      if (this.sfindex == 'police') {
        uni.reLaunch({
          url: '/pages/rescue/trafficPolice'
        })
      } else {
        uni.reLaunch({
          url: '/pages/rescue/rescue'
        })
      }

    },
    // 验证码方法
    sendVerificationCode() {
      let reg = /^((13[0-9])|(14[0-9])|(15[0-9])|(17[0-9])|(18[0-9]))\d{8}$/;
      if (!reg.test(this.userName)) {
        uni.showToast({
          icon: 'none',
          title: '请输入正确的11位手机号'
        })
        this.userName = '';
        return false;
      }
      if (this.isButtonDisabled) {
        return; // 如果按钮已禁用，则直接返回
      }
      const data = {
        phone: this.userName,
      }
      request({
        url: '/loginSmsCode',
        method: 'post',
        params: data
      }).then((res) => {
        console.log('验证码', res);
        if (res.code == 200) {
          uni.showToast({
            title: '验证码已发送 请注意查收',
            icon: 'none'
          })
        } else {
          uni.showToast({
            title: '网络不佳请稍后再试',
            icon: 'none'
          })
        }
      })


      this.disableButton(); // 禁用按钮
      this.startCountdown(); // 启动倒计时

    },
    disableButton() {
      this.isButtonDisabled = true;
    },
    enableButton() {
      this.isButtonDisabled = false;
    },
    startCountdown() {
      let countdown = setInterval(() => {
        this.countdownTime--;
        if (this.countdownTime === 0) {
          clearInterval(countdown);
          this.enableButton(); // 启用按钮
        }
      }, 1000);
    },
  }
}
</script>

<style scoped lang="scss">
.jsq {
  border: none !important;
  font-size: 14px;
  font-weight: 400;
  color: #0078FF;
}

button {
  border: none !important;
  background: none !important;
  margin: 0px;
  display: block;
}

button:focus {
  color: #0078FF;
  outline: none;
  box-shadow: none;
}

.content {
  box-sizing: border-box;
}

.top {
  box-sizing: border-box;
  padding: 0px 27px;
  padding-top: 100px;
  background-image: url('../../static/loginbj.png');
  // background-color:lightseagreen;
  // background-image: url('../../static/loginbj.png');
  background-size: cover;
  background-position: center;
  width: 100%;
  // height: 385px;
}

.touxiang {
  width: 88px;
  height: 88px;
  border-radius: 10px;
  background: #D7D7D7;
  margin: 0 auto;
  margin-bottom: 40px;
  overflow: hidden;

  image {
    width: 100%;
    height: 100%;
  }
}

.twotap {
  width: 100%;
  display: flex;
  align-items: center;

  view {
    font-size: 15px;
    font-family: Microsoft YaHei;
    font-weight: 400;
    color: #666666;
    margin-right: 38.5px;
  }
}

.blck {
  color: #333333 !important;
  font-weight: bold !important;
}

.inputs {
  box-sizing: border-box;
  padding: 16px 0px;
  display: flex;
  align-items: center;
  border-bottom: 2px solid #E8E8E8;
  margin-top: 20px;
}

.wjworb {
  margin-top: 5px;
  width: 100%;
  display: flex;
  font-size: 12px;
  color: #0078FF;
  justify-content: flex-end;
  align-items: center;

}

.dl {
  width: 90%;
  height: 44px;
  background: linear-gradient(-46deg, #0853C4 0%, #4282D8 80%);
  border-radius: 5px;
  margin: 0 auto;
  font-size: 16px;
  color: #FFFFFF;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 22px;
}

.hging {
  width: 100%;
  text-align: center;
  font-size: 14px;
  font-weight: 400;
  color: #636363;
  margin-top: 20px;
}

.wx {
  width: 38px;
  height: 38px;
  overflow: hidden;
  box-sizing: border-box;
  margin: 0px auto;
  margin-top: 20px;

  image {
    width: 100%;
    height: 100%;
  }
}

.hui {
  font-size: 10px;
  width: 100%;
  text-align: center;
  font-weight: 400;
  color: #666666;
}

.dbottom {
  width: 100%;
  text-align: center;
  font-size: 12px;
  color: #333333;
  margin-top: 40px;
  position: fixed;
  bottom: 25px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.quanzi {
  width: 14px;
  height: 14px;
  border: 1px solid #666666;
  border-radius: 50%;
  margin-right: 10px;
}

.lanquanzi {
  width: 14px;
  height: 14px;
  border: 1px solid #0078FF;
  border-radius: 50%;
  margin-right: 10px;
  background: #0078FF;
  color: white;
}

.lan {
  color: #0078FF;
}

.jiuzhong {
  width: 90%;
  margin: 10px auto;
  display: flex;
  align-items: center;
}

.dist {
  display: flex;
  align-items: center;
  margin: 0px 10px;
}

.d-zi {
  font-size: 14px;
}

.d-qian {
  width: 14px;
  height: 14px;
  margin-right: 5px;
  overflow: hidden;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid #666666;
  color: white;
}

.d-qian-lan {
  width: 14px;
  height: 14px;
  margin-right: 5px;
  overflow: hidden;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #0078FF;
  border: 1px solid #0078FF;
  color: white;
}
</style>
