<template><page-meta :root-font-size="fontSize+'px'"></page-meta>
  <home-base :show="false">
    <view class="div container">
      <view class="div common-header-wrap">
        <view :style="'height:'+navHeight+'px'"></view>
        <view class="common-header-holder"></view>
        <view class="common-header-fixed">
        <title-header />
        <uni-nav-bar title="登录" class="common-header" left-icon="back" @clickLeft="goBack()">
          <!-- <view v-if="config && (config.sms_register==1 || config.member_normal_register==1)" class="div common-btn btn"
            slot="right" @click="onSignup">注册</view> -->
        </uni-nav-bar>
      </view>
      </view>
      <view class="div main-content">
        <view class="div topList">
          <view class="div list">
            <view class="div item" v-for="(item, index) in items" :key="index" v-on:click="onClickItem(index)">
              <label class="title" v-bind:class="{
					active: index === currentIndex,
					normal: index !== currentIndex
				}">{{ getTitle(item) }}</label>
            </view>
          </view>
        </view>
        <view class="div top-wrapper">
          <flex-line class="input-wrapper" v-if="currentIndex === 0" :show-border="true">
            <input v-model="username" placeholder="用户名/邮箱/手机号" type="text" />
          </flex-line>
          <flex-line v-if="currentIndex !== 0" class="input-wrapper" :show-border="true">
            <input v-model="mobileusername" placeholder="请输入手机号"
              :attr="{oninput: 'if(value.length>11)value=value.slice(0,11)'}" type="text" />
          </flex-line>
<!--          <flex-line v-if="currentIndex === 0 && config.captcha_status_login=='1'" class="input-wrapper"
            :show-border="true">
            <input v-model="pictureCode" placeholder="请输入图片验证码" maxlength="6" />
            <image mode="aspectFit" slot="right" @click="changePictureCode" :src="pictureCodeUrl" class="img countdown">
          </flex-line> -->

          <flex-line v-if="currentIndex !== 0" class="input-wrapper" :show-border="true">
            <input v-model="code" placeholder="请输入短信验证码" type="number"
              :attr="{ oninput: 'if(value.length>6)value=value.slice(0,6)' }" />
            <view slot="right" class="div common-btn send-btn" @click="sendVerifyCodeMobile">{{sendStateTextMobile}}
            </view>
          </flex-line>
          <flex-line v-if="currentIndex === 0" class="input-wrapper" :show-border="true">
            <input type="password" v-model="password" placeholder="请输入密码" />
          </flex-line>
        </view>
        <view class="div common-btn ds-button-large mt-10 mb-10" @click="signin">登录</view>
        <view class="div retrieve-wrapper" style="display: flex;justify-content: space-between;">
          <text class="span retrieve-item" @click="onRetrieve">忘记密码？</text>
		  <text class="span retrieve-item" v-if="config && (config.sms_register==1 || config.member_normal_register==1)" @click="onSignup">立即注册</text>
        </view>
      </view>
      <view class="div bottom-wrapper" v-if="isShowWechat || isShowSina || isShowQQ">
        <view class="div auth-title-wrapper">
          <view class="div auth-line"></view>
          <label class="auth-title">第三方登录</label>
          <view class="div auth-line"></view>
        </view>
        <view class="div auth-bottom-wrapper">
          <view class="div auth-item" v-if="isShowWechat" @click="onWechat">
            <view class="div auth-item-icon">
              <image mode="aspectFit" class="img icon" src="../../../static/image/weixin.png" />
            </view>
            <label class="auth-title auth-item-title">微信</label>
          </view>
          <view class="div auth-item" v-if="isShowSina" @click="onSina">
            <view class="div auth-item-icon">
              <image mode="aspectFit" class="img icon" src="../../../static/image/weibo.png" />
            </view>
            <label class="auth-title auth-item-title">微博</label>
          </view>
          <view class="div auth-item" v-if="isShowQQ" @click="onTencent">
            <view class="div auth-item-icon">
              <image mode="aspectFit" class="img icon" src="../../../static/image/qq.png" />
            </view>
            <label class="auth-title auth-item-title">QQ</label>
          </view>
        </view>
      </view>
    </view>
  </home-base>
</template>

<script>
import {getFontSize} from '@/util/common'
  import TitleHeader from '../../TitleHeader'
  import HomeBase from '../HomeBase'
  import { urlencode } from '@/util/common'
  import {
    login,
    wechatLogin,
    LoginByMobile,
    getThirdLogin,
    wechatcheck,
    wechatUser
  } from '../../../api/memberLogin'
  import {
    isWechat
  } from '../../../util/wechat'
  import {
    getSmsCaptcha,
    checkPictureCaptcha
  } from '../../../api/common'
  import {
    mapMutations,
    mapActions,
    mapState
  } from 'vuex'
  import flexLine from '../../flexLine'
  import {
    env
  } from '../../../static/config'
  export default {
    name: 'Login',
    data(){
      return {
        navHeight: 0,
        clear: 0,
        isTokenInvalid: 0,
        isFromInfoEdit: 0,
        isFromShare: 0,
        referrer: '',
        pictureCodeUrl: '',
        pictureCode: '',
        code: '',
        verifyCodeMobile: '',
        canSendMobile: true,
        timeIntervalMobile: false,
        sendStateTextMobile: '发送',
        mobileusername: '',
        username: '',
        password: '',
        currentIndex: 0,
        items: [{
          id: 1,
          title: '普通登录'
        }]
      }
    },
    components:{
      TitleHeader,
      HomeBase,
      flexLine
    },
    computed:{
      fontSize(){
        return getFontSize()
      },
      ...mapState({
        inviter_id: state => state.member.inviterId,
        config: state => state.config.config
      }),
      isShowWechat: function() {
        if(this.config && this.config.weixin_isuse == 1){
        // #ifdef H5
        if (isWechat()) {
          return true
        }
        return false
        // #endif

        // #ifndef H5
        return true
        // #endif
        }else{
          return false
        }

      },
      isShowSina: function() {
        // #ifdef H5
        if (!isWechat() && !this.uniapp && this.config && this.config.sina_isuse == 1) {
          return true
        }
        // #endif
        return false
      },
      isShowQQ: function() {
        // #ifdef H5
        if (!isWechat() && !this.uniapp && this.config && this.config.qq_isuse == 1) {
          return true
        }
        // #endif
        return false
      }
    },
    watch: {
      mobileusername(newVal, oldVal) {
        newVal = newVal.replace(/[^\d]/g, '')
        if (!newVal) {
          this.$nextTick(() => {
            this.mobileusername = newVal
          })
        }
      },
    },
    beforeDestroy: function() {
      clearInterval(this.timeIntervalMobile)
    },
    onLoad: function(option) {
      this.isTokenInvalid = option.isTokenInvalid
      this.isFromInfoEdit = option.isFromInfoEdit
      this.isFromShare = option.isFromShare
      this.clear = option.clear
      this.referrer = option.referrer
      uni.hideLoading()
      if(option.id){
        this.getThirdLogin(option.id)
      }

      if (this.clear) {
        this.memberLogout()
      }
      this.fetchConfig({}).then(
        res => {
          var config = res.result.config_list
          if (config.sms_login == 1) {
            this.items.push({
              id: 2,
              title: '手机登录'
            })
          }
        },
        error => {
          uni.showToast({
            icon: 'none',
            title: error.message
          })
        }
      )
    },
    mounted(){
      // #ifdef  MP-WEIXIN
      this.navHeight = uni.getMenuButtonBoundingClientRect().top
      // #endif
      let isTokenInvalid = this.isTokenInvalid
      if (isTokenInvalid) {
        uni.showToast({
          icon: 'none',
          title: '登录过期'
        })
      }
      // this.changePictureCode()
    },
    methods: {
      getThirdLogin(id){
        getThirdLogin(id).then(res => {
          let user_info = res.result.user_info
          let key = res.result.key
          if (user_info && key) {
            this.saveAuthInfo({
              token: key,
              info: user_info
            })
            this.goHome()
          }
        })
      },
      goBack() {
        let referrer
        var pages = getCurrentPages()
          var page = pages[pages.length - 2]
          if (page) {
            referrer = '/'+page.route
          }
        if (!referrer || (referrer.search('pages/member') != -1)) {
          uni.reLaunch({
              url: '/pages/home/index/Index'
          });
        }else{
          uni.navigateBack({
            delta: 1
          })
        }
      },
      ...mapMutations({
        saveAuthInfo: 'memberLogin',
        memberLogout: 'memberLogout'
      }),
      ...mapActions({
        fetchConfig: 'fetchConfig'
      }),
      changePictureCode() {
        this.pictureCodeUrl = env.API_HOST + '/Seccode/makecode?r=' + Math.random()
      },
      sendVerifyCodeMobile() {
        if (!this.mobileusername) {
          uni.showToast({
            icon: 'none',
            title: '请先输入手机号'
          })
          return
        }
        if (!this.canSendMobile) {
          return
        }
        getSmsCaptcha(2, this.mobileusername).then(res => {
          this.canSendMobile = false
          let second = 60
          uni.showToast({
            icon: 'none',
            title: res.message
          })
          let _this = this
          this.timeIntervalMobile = setInterval(function() {
            if (second <= 0) {
              _this.canSendMobile = true
              _this.sendStateTextMobile = '发送'
              clearInterval(_this.timeIntervalMobile)
            } else {
              _this.sendStateTextMobile = second + 's'
            }
            second--
          }, 1000)
        }).catch(function(error) {
          uni.showToast({
            icon: 'none',
            title: error.message
          })
        })
      },
      getTitle(item) {
        return item ? item.title : ''
      },
      isShowLine(index) {
        return index === this.currentIndex
      },
      onClickItem(index) {
        if (this.currentIndex !== index) {
          this.currentIndex = index
        }
      },
      onTencent() {
        window.location.href = env.API_HOST + '/api/oa_qq'
      },
      onSina() {
        window.location.href = env.API_HOST + '/api/oa_sina'
      },
      signin() {
        if (this.currentIndex == 0) {
          let username = this.username
          let password = this.password
          if (username.length === 0) {
            uni.showToast({
              icon: 'none',
              title: '请输入用户名/邮箱/手机号'
            })
            return
          }
          // TODO: 用户名（为手机号或邮箱）校验
          if (password.length === 0) {
            uni.showToast({
              icon: 'none',
              title: '请输入密码'
            })
            return
          }
          if (password.length < 6) {
            uni.showToast({
              icon: 'none',
              title: '至少输入6位密码'
            })
            return
          }
          uni.showLoading({
            title: '加载中'
          })
          login(username, password, this.pictureCode).then(
            response => {
              uni.hideLoading()
              this.saveAuthInfo({
                token: response.result.token,
                info: response.result.info
              })
              this.goHome()
            },
            error => {
              uni.hideLoading()
              uni.showToast({
                icon: 'none',
                title: error.message
              })
            }
          )
        } else {
          let mobileusername = this.mobileusername
          if (mobileusername.length != 11) {
            uni.showToast({
              icon: 'none',
              title: '请输入11位手机号'
            })
            return
          }
          uni.showLoading({
            title: '加载中'
          })
          LoginByMobile(mobileusername, this.code).then(
            response => {
              uni.hideLoading()
              this.saveAuthInfo({
                token: response.result.token,
                info: response.result.info
              })
              this.goHome()
            },
            error => {
              uni.hideLoading()
              uni.showToast({
                icon: 'none',
                title: error.message
              })
            }
          )
        }
      },

      goHome() {
        let referrer = this.getReferrer()

        if (referrer) { // 返回之前的页面
          referrer = decodeURIComponent(referrer)
          uni.redirectTo({
            url: referrer
          })
        } else {
          uni.redirectTo({
            url: '/pages/member/index/Index'
          })
        }
      },
      getReferrer() {
        let referrer = this.referrer
        if (!referrer) {
          var pages = getCurrentPages()
          var page = pages[pages.length - 2]
          if (page) {
            referrer = '/'+page.route+(page.options?('?'+urlencode(page.options)):'')
          }
        }
        if (referrer && (referrer.search('memberlogin') != -1 || referrer.search('memberregister') != -1 || referrer
            .search('memberbind') != -1)) {
          referrer = '/pages/member/index/Index'
        }
        return referrer
      },
      onSignup() {
        uni.navigateTo({
          url: '/pages/home/memberregister/Register'
        })
      },

      onRetrieve() {
        uni.navigateTo({
          url: '/pages/home/memberforget/Forget'
        })
      },

      onWechat() {
        let referrer = this.getReferrer()
        if (referrer) { // 返回之前的页面
          referrer = decodeURIComponent(referrer)
        }
        // #ifdef H5
        let ref = encodeURIComponent(referrer)
        wechatLogin(ref?ref:'', this.inviter_id).then(res => {
          window.location.href = res.result
        }).catch(function(error) {
          uni.showToast({
            icon: 'none',
            title: error.message
          })
        })
        // #endif

        // #ifndef H5
        var _this = this
        uni.login({
          provider: 'weixin',
          onlyAuthorize:true,
          success: function(res) {
            var from = ''
            // #ifdef APP-PLUS
            from = 'app'
            // #endif
            // #ifdef MP-WEIXIN
            from = 'miniprogram'
            // #endif
            wechatUser({code:res.code,from:from}).then(res=>{
              wechatcheck({
                inviter_id: _this.inviter_id,
                openid: res.result.openid,
                unionid: res.result.unionid,
                access_token: res.result.access_token,
                from: from,
              }).then(res => {
                if(res.result.has_user){
                  _this.getThirdLogin(res.result.unionid)
                }else{
                  uni.navigateTo({
                    url: res.result.ret_url
                  })
                }

              }).catch(error => {
                uni.showToast({
                  icon: 'none',
                  title: error.message
                })
              })
            }).catch(error=>{
              uni.showToast({
                  icon: 'none',
                  title: error.message
                })
            })

          },
          fail: function(err) {
            uni.showToast({
              icon: 'loading',
              title: '登录失败'
            })
          }
        });
        // #endif
      }

    }
  }
</script>

<style scoped lang='scss'>
  .common-header {
    .btn {
      background: #000;
      color: #fff;
      box-shadow: 0px 2px 4px #d2d2d2;
    }
  }

  .ds-button-large {
    margin: 0 $pageSpace
  }

  .container {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    align-items: stretch;

    .main-content {
      background: #fff;
      padding: 1rem 0;
    }

    .countdown {
      min-width: 4rem;
    }

    .send-btn {
      border: 1px solid $primaryColor;
      color: $primaryColor;
      min-width: 2rem
    }

    .top-wrapper {
      .input-wrapper {
        display: flex;
        align-content: center;
        align-items: center;
        padding-left: 0.4rem;
        background-color: #fff;
        height: 2.2rem;

        .img {
          height: 1.75rem;
          width: auto;
          margin: 0;
          padding: 0;
        }

        input {
          flex: 1;
          font-size: $subFontSize;
        }
      }
    }
  }

  .retrieve-wrapper {
    margin: 0 $pageSpace;
    display: flex;
    flex-direction: row;
    font-size: $h2;
    color: $primaryColor
  }

  .bottom-wrapper {
    display: flex;
    flex: 1;
    flex-direction: column;
    justify-content: flex-end;
    align-items: stretch;
  }

  .auth-wrapper {
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    align-items: center;
    height: 13rem;
  }

  .auth-title-wrapper {
    height: 1rem;
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
    align-items: center;
    margin-bottom: 2rem;
    margin-top: 1rem;
  }

  .auth-title {
    color: $descTextColor;
    font-size: $subFontSize;
  }

  .auth-line {
    display: flex;
    flex: 1;
    height: 1px;
    background-color: #eee;
    margin-left: 0.8rem;
    margin-right: 0.8rem;
  }

  .auth-item {
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    align-items: center;
  }

  .auth-item-icon {
    width: 3rem;
    height: 3rem;
    border-radius: 50%;
    background: #fff;
    font-size: 3rem;
    box-shadow: 0px 4px 4px #e0e0e0;
    display: flex;
    justify-content: center;
    align-items: center;

    .icon {
      width: 60%;
    }
  }

  .auth-item-title {
    margin-top: 0.6rem;
    color: $formInputColor
  }

  .auth-bottom-wrapper {
    display: flex;
    flex-direction: row;
    justify-content: space-around;
    align-items: center;
    margin-left: 0.75rem;
    margin-right: 0.75rem;
    margin-bottom: 1rem;
  }

  .topList {
    height: 2rem;
    padding: 1rem $pageSpace;

    .list {
      height: 100%;
      display: flex;
      flex-direction: row;
      justify-content: flex-start;
      align-content: center;
      align-items: stretch;
      background-color: #fff;
    }

    .item {
      padding: 0 .5rem;
      position: relative;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
    }

    .title {
      text-align: center;
      font-size: $h2;
      color: $formInputColor;
    }

    .active {
      color: $primaryColor;
      font-size: 1.1rem;
    }

    .normal {
      color: #404245;
    }

  }

  .top-wrapper {
    margin: 0 $pageSpace;
  }
</style>
