<template>
  <div class="auth-index" @click.stop="agreementModal = false">
    <div class="auth-content">
      <div class="app-icon">
        <image
          class="app-icon-img"
          src="https://image.jxc4.com/image/875aadc47f8ef85badcbc31afe66dcf9.png"
          alt=""
        />
        <div class="app-title">{{title }}</div>
      </div>
      
      <!-- 微信登录 -->
      <div class="auth-btn-group" v-if="!isAccount">
			
        <!-- #ifdef MP-KUAISHOU -->
        <div class="wxLogin"  @click.stop="openArgument">快手登录</div>
        <!-- #endif -->
        
        <!-- #ifdef MP-WEIXIN -->
        <div class="wxLogin" @click.stop="openArgument" v-if="isExistWeixinApp">手机号快捷登录</div>
        <!-- #endif -->

         <!-- #ifdef APP-PLUS || APP -->
         <div class="wxLogin" @click.stop="openArgument" v-if="isExistWeixinApp">微信登录</div>
        <!-- #endif -->
        
        <!-- #ifdef MP-TOUTIAO -->
        <button open-type="getPhoneNumber"  @getphonenumber.stop="getphonenumber">授权手机号快捷登录</button>
        <!-- #endif -->

        <!-- #ifdef APP-PLUS || APP -->
        <div @click="accountLogin" style="" class="account-but">账号登录</div>	
        <!-- #endif -->
 
      </div>

      <!-- 账号密码登录 -->
      <!-- class="auth-btn-group" -->
      <div class="account" v-else>
        <div class="account-title">账号登录</div>
        <div class="account-box">
          <input class="uni-input" placeholder-class="placeholderStyle" @input="accountInput" placeholder="请输入账号" />
        </div>
        <div class="account-box" style="margin-top:20rpx">
          <input class="uni-input" password placeholder-class="placeholderStyle" @input="passwordInput" placeholder="请输入密码" />
        </div>
       
        <div class="account-button" @click.stop="openArgument">登录</div>
        
        <!-- 微信登录 -->
        <!-- <div v-if="isExistWeixinApp" @click="accountLogin">
          <img src="https://image.jxc4.com/image/e61defe870db97678964ca75d39bb59f.png" alt="" style="width: 50px;height: 50px;margin: 20px auto;">
        </div> -->
      </div>
      
    </div>
    
    <!-- #ifndef MP-KUAISHOU -->
    
    <!-- #endif -->
    <div class="info">欢迎进入京西菜市</div>

    <!-- #ifdef MP-KUAISHOU -->
     <!-- <div class="auth-footer" >
      <checkbox-group @change="radioChange">
        <label>
          <checkbox value="agree" color="#4EB331">
            <div>
              同意{{title}}
              <span class="span">
                <span @click="goAuthArgument('userAgreement')">《用户协议》</span>
                <span @click="goAuthArgument('privacyAgreement')">《隐私协议》</span>
              </span> 
            </div>
          </checkbox>
        </label>
      </checkbox-group>
    </div> -->
    <!-- #endif -->

   

    <!-- 绑定手机号弹框 -->
    <!-- <Modal class="modal" v-show="showModal">
      <div class="modal-border">
        <div class="title" style="font-weight: bold;">绑定账号</div>
        <div class="description-text">绑定手机号后可以获得更优质的体验</div>
        <div class="input-border">
          <input class="input" v-model="phone" placeholder="点击输入手机号">
          <image v-show="isPhone && phone" src="https://image.jxc4.com/image/31f1480206cd6c8b778a278a323c7a32.png" class="error-text"></image>
          <image v-show="!isPhone && phone" src="https://image.jxc4.com/image/06ff40d3ae05ac810e5628bef8e1f83f.png" class="error-text"></image>
        </div>
        <button class="but-bind" @click="bindPhone" type="primary"> 绑定</button>
        <button class="but-cancel" @click="cancelPhone"> 取消</button>
      </div>
    </Modal> -->
    <div class="box" v-show="showModal">
      <div class="content">
        <div class="modal-border">
          <div class="title" style="font-weight: bold;">绑定账号</div>
          <div class="description-text">绑定手机号后可以获得更优质的体验</div>
          <div class="input-border">
            <input class="input" v-model="phone" placeholder="点击输入手机号">
            <image v-show="isPhone && phone" src="https://image.jxc4.com/image/31f1480206cd6c8b778a278a323c7a32.png" class="error-text"></image>
            <image v-show="!isPhone && phone" src="https://image.jxc4.com/image/06ff40d3ae05ac810e5628bef8e1f83f.png" class="error-text"></image>
          </div>
          <button class="but-bind" @click="bindPhone" type="primary"> 绑定</button>
          <button class="but-cancel" @click="cancelPhone"> 取消</button>
        </div>
      </div>
    </div>
    

    <!-- 协议弹框 -->
    <div class="box" v-show="agreementModal">
      <div class="content" >
        <div class="title">用户协议及隐私协议</div>
        <div class="text">
          本协议系您与成都若溪科技有限公司就京西菜市帐号的注册和使用而订立的。成都若溪科技有限公司（如下简称“京西菜市”）在此特别提醒您认真阅读、充分理解本协议各条款，特别是涉及服务费用条款，免除或者限制京西菜市责任的条款，对您的权利限制条款，争议解决和法律适用条款等，此类条款将以加粗的形式提示您注意。请您审慎阅读并选择接受或不接受本协议（限制民事行为能力人应在监护人或法定代理人陪同下阅读）。除非您接受本协议所有条款，否则您无权注册、使用京西菜市帐号。您的注册和使用京西菜市帐号行为将视为您已充分理解本协议（即本协议及后续更新版本或开通或使用某项服务的单项协议），并同意接受本协议各项条款的约束。
        </div>
        <div>
          <span class="title">点击同意即代表您已阅读并同意</span>
          <span @tap="goAuthArgument('userAgreement')" class="userAgree">《用户协议》</span>
          <span @tap="goAuthArgument('privacyAgreement')" class="privacyAgree">《隐私协议》</span>
        </div>
        <div class="bottom" >
          <button @tap="agreementModal = false" class="refuse">拒绝</button>

          <!-- #ifdef MP-WEIXIN -->
          <button v-if="!isAccount" open-type="getPhoneNumber" @getphonenumber="wxGetUserInfo" class="agree">同意</button>
          <button v-else @click="wxLogin" class="agree">同意</button>
          <!-- #endif -->
          
          <!-- #ifdef MP-KUAISHOU -->
          <button class="agree" open-type="getPhoneNumber" @getphonenumber="getUserInfo">同意</button>
          <!-- #endif -->

          <!-- #ifdef APP-PLUS || APP -->
          <button  @click="wxLogin"  class="agree">同意</button>
          <!-- #endif -->
        </div>
      </div>
    </div>

    <!-- 加载 -->
    <zy-loading></zy-loading>
  </div>
</template>

<script>
import { errToast, toast,jumpPage } from "@/utils/uniapi.js";
import ZyLoading from "@/components/Loading/loading";

// #ifdef APP || APP-PLUS 
import Modal from "@/components/Modal/modal";
// #endif

import {store} from '@/store'
import { mapGetters } from "vuex";
import { utilsMd5 } from '@/utils/md5.js'

import login from '@/apis/login'

// #ifdef MP-WEIXIN
import { logInfo } from '@/utils/log'
// #endif

export default {
  name: "authIndex",
  components: {
    ZyLoading,
    // #ifdef APP-PLUS || APP
    Modal
    // #endif
  },
  data(){
	  return {
      // type:'',
      payInfor:{},      // 京西支付参数
      payOrderInfo:'',   // 支付订单参数
      checkBox:false,   // 阅读协议
      title: '京西菜市',
      
      phone: '',
      showModal:false,    // 打开绑定手机号的弹框
      agreementModal:false,
      type: '',
      isAccount: false,   // 是否是账号登录
      accountValue: '',  // 账号
      password:''   // 密码
	  }
  },
  onLoad(query){
    // #ifdef MP-WEIXIN
    this.type = query.type ? query.type : ""
    if (query.type === "jxPay" && query.payInfor && query.payInfor.length>0) {
      this.payInfor = JSON.parse(query.payInfor)
    }

    if(query.orderID){
      this.payOrderInfo = {
        dns:query.dns,
        orderID:query.orderID,
      }
    }
    // #endif

    // #ifdef APP-PLUS || APP
    this.title = '京西菜市'
    // #endif

    // #ifdef MP-KUAIHSOU
    this.title = '京西到家'
    // #endif
  },
  computed: {
    ...mapGetters({
      iosOrAndroid: "iosOrAndroid",
      isExistWeixinApp: "login/iSExistWeixinApp",
      tmpData:'login/tmpData'
    }),
    isPhone() {
      if(this.phone.length!==11) return false
      // const pattern = /0?(13|14|15|17|18)[0-9]{9}/
      const pattern = /^(?:(?:\+|00)86)?1\d{10}$/
      return pattern.test(this.phone)
    },
  },
  methods: {
    // 打开协议
    openArgument() {
      if (this.isAccount) {
        if (this.accountValue == '') return toast('用户名不规范')
        if (this.password.length < 4) return toast('密码不规范')
      }

      this.agreementModal = true
    },
    // 账号登录
    accountLogin() {
      this.isAccount = true
    },
    // 账号
    accountInput(e) {
      this.accountValue = e.detail.value
    },
    // 密码
    passwordInput(e) {
      this.password = e.detail.value
    },
    // 账号登录 app微信登录
    async wxLogin() {
      try {
        this.showLoad()
        if (!this.isAccount) {
          this.appWXlogin()
        } else {
          let data = {
            authType: 'localpass',
            authIDType: 'mobile',
            authID: this.accountValue,
            authSecret: utilsMd5.hex_md5(this.password),
          }
          await this.globalLogin(data)
          jumpPage('switchTab', '/pages/index/index')
        }
      } catch (e) {
        console.error(e)
        throw e
      } finally {
        this.hideLoad()
      }
      
    },
    // 绑定手机号
    async bindPhone(){
      if (!this.isPhone) {
        errToast('手机号错误')
      }
      let data ={
        authToken:this.tmpData.token,
        mobile:this.phone,
      }
      await login.addAuthBindWithMobile(data)  // 绑定
      await this.globalLogin() // 绑定成功之后，重调一遍登录
      
      if(JSON.stringify(this.tmpData) !== '{}') {
        // // #ifdef APP-PLUS || APP
        // this.showModal = true
        // // #endif
        
        // #ifndef APP
        toast('登录失败')
        
        // #endif

         // #ifdef MP-WEIXIN
          let logJson = {
              rootUrl:uni.getStorageSync('storeType') || 'c4',
              explain: '登录失败',
              time: 0,
              token:uni.getStorageSync('token') || '',
              data: JSON.stringify(this.tmpData)
          }
          logInfo(logJson)
          // #endif
      }
    },
    // #ifdef MP-WEIXIN
    closeDialog() {
      console.log('关闭弹框,阻止点击事件传递')
    },
    // 微信登录
    async wxGetUserInfo(e) {
      if (e.detail.errMsg == 'getPhoneNumber:ok') {
        try {
          this.showLoad()
          await this.globalLogin()
          if (JSON.stringify(this.tmpData) !== '{}') await store.dispatch('login/analyzePhone', e.detail)
          if (this.type === "weixinmini") {
            if(JSON.stringify(this.tmpData) !== '{}'){
              this.showModal = true
            }else{
              jumpPage('switchTab','/pages/index/index')
            }
          } else if(this.payOrderInfo){
            // 扫码支付
            jumpPage('navigateTo',`/pagesPay/JX-pay/JX-pay?orderID=${this.payOrderInfo.orderID}&dns=${this.payOrderInfo.dns}`)
          }else{
            if (JSON.stringify(this.payInfor) !== '{}') {
              jumpPage('navigateTo',`/pagesPay/JX-pay/JX-pay?jxParams=${JSON.stringify(this.payInfor)}`)
            } else {
              jumpPage('navigateTo','/pagesPay/JX-pay/JX-pay')
            }
          }
        } catch (e) {
          console.error(e)
          errToast(e)
        } finally {
          this.hideLoad()
        }
      } else {
        // 获取不到手机号信息
        await this.globalLogin()
        if(JSON.stringify(this.tmpData) !== '{}') {
          // #ifdef APP-PLUS || APP
          
          // #endif

          this.showModal = true

          // #ifndef APP
          // errToast('登录失败');
          // #endif
        }
        
      }
    },
    // #endif

    // radioChange(e){
    //   this.checkBox=e.detail.value.length > 0 ? true : false
    // },

    // #ifdef MP-TOUTIAO
    // 抖音小程序
    // async getphonenumber(e) {
    //     try {
    //       let that = this
    //       if(this.checkBox){
    //         // await this.getUserInfoRegister({encryptedData:e.detail.encryptedData,iv:e.detail.iv},this.$mp.query.ttCode)
    //         await that.globalLogin()
    //         if (JSON.stringify(this.tmpData) !== '{}') await store.dispatch('login/analyzePhone',e.detail)
    //       }else{
    //         await modal("", '您未同意京西菜市用户协议')
    //       }
    //     } catch (e) {
    //       errToast(e);
    //     } finally {
    //       this.hideLoad();
    //     }
    // },
    // #endif

    // 取消绑定
    cancelPhone() {
      this.showModal = false
    },

    // #ifdef APP-PLUS || APP
    // 微信登录
    async appWXlogin() {
      try {
        this.showLoad();
        await this.globalLogin()
        if(JSON.stringify(this.tmpData) !== '{}') this.showModal = true
        else jumpPage('switchTab','/pages/index/index')
      } catch (e) {
        console.error(e)
        throw e
      } finally {
        this.hideLoad()
      }
    },
    // #endif


    // #ifdef MP-KUAISHOU
    // 获取用户信息
    async getUserInfo(e) {
      if (e.detail.errMsg == 'getPhoneNumber:ok') {
        try {
          this.showLoad()
          await this.globalLogin()
          if (JSON.stringify(this.tmpData) !== '{}') {
            // await 获取手机号
           await store.dispatch('login/analyzePhone', {
              phone: e.detail,
              sessionKey:this.tmpData.authBindInfo.userData,
              token:this.tmpData.token
           })
          } else {
            jumpPage('switchTab','/pages/index/index')
          }
        } catch (e) {
          console.error(e)
        } finally {
          this.hideLoad()
        }
      }
    },
    // #endif
   
    // 跳转到用户协议
    goAuthArgument(type) {
      jumpPage('navigateTo',`/pagesAuth/auth-argument/index?type=${type}`)
    },
    // async getphonenumber(e) {
    //   try {
    //     console.log(e);
    //     if ("encryptedData" in e.detail) {
    //       console.log("走了if");
    //       let { encryptedData, iv } = e.detail;
    //       this.showLoad();
    //       // 检查session是否过期
    //       let [err, res] = await uni.checkSession();
    //       console.log(err, res);
    //       let jsCode = "";
    //       let { code } = await miniLogin();
    //       jsCode = code;
    //       //原本的代码
    //       // if (err) {
    //       //   // 过期
    //       //   let { code } = await miniLogin();
    //       //   jsCode = code;
    //       // }
    //       let userInfo = await bindMobile(encryptedData, iv, jsCode);
    //       console.log(userInfo, "userinfo");
    //       if (userInfo.hasOwnProperty("code")) {
    //         console.log("号码重复");
    //         alert("手机号已被绑定，请联系客服");
    //       } else {
    //         console.log("绑定成功");
    //         // 绑定成功,重新获取用户信息,保存
    //         await getSelfInfo();
    //         uni.navigateBack({ delta: 1 });
    //         // toast('登录成功')
    //       }
    //     }
    //   } catch (e) {
    //     errToast(e);
    //   } finally {
    //     this.hideLoad();
    //   }
    // },
  },
};
</script>

<style lang="scss" scoped>
@import "./auth-index.scss";
</style>