<!--登录页面-->
<template>
  <view class="header" style="border-top:3rpx solid #f6f6f6"></view>
  <view class="content" v-if="showFlag">
    <!-- 标题区域 -->
    <view class="textcenter">
      <view class="flex">
        <view class="title">{{ StaticConstant.systemName }}</view>
      </view>
    </view>
    <view class="textcenter">
      <text class="low-title">艺术生 更轻松的报志愿</text>
    </view>

    <!-- 快捷登录 showType===1 -->
    <view style="margin-top: 200rpx" v-if="showType === 1">
      <!-- #ifdef MP-TOUTIAO -->
      <button class="login-but" @click="handleQuickLogin">抖音一键登录</button>
      <!-- #endif -->
      <!-- #ifdef MP-WEIXIN -->
      <button 
        class="login-but" 
        v-if="checkFlag" 
        open-type="getPhoneNumber" 
        @getphonenumber="getPhoneNumber"
      >
        手机号快捷登录
      </button>
      <button class="login-but" v-else @click="showAgreementTip">手机号快捷登录</button>
      <!-- #endif -->
      <button class="login-pwd-but margin-top-20" @click="showType = 2">账号密码登录</button>
    </view>

    <!-- 账号密码登录 showType===2 -->
    <view style="margin-top: 180rpx" class="uni-padding-wrap border-top" v-if="showType === 2">
      <view class="forms">
        <view class="form-item">
          <view class="form-item-view form-input">
            <input 
              class="uni-input" 
              type="text"
              v-model="formData.userName"
              placeholder="请输入用户名或手机号"
            />
          </view>
        </view>
        <view class="form-item">
          <view class="form-item-view form-input">
            <input 
              class="uni-input" 
              type="password" 
              password
              v-model="formData.password"
              placeholder="请输入密码"
            />
          </view>
        </view>
        <view class="form-item">
          <button 
            class="login-but margin-top-20" 
            :disabled="!checkFlag" 
            :class="{ 'login-but-disabled': !checkFlag }"
            @click="pwdLogin"
          >
            登录
          </button>
        </view>
      </view>
    </view>

    <!-- 注册 showType===3 -->
    <view style="margin-top: 180rpx" class="uni-padding-wrap border-top" v-if="showType === 3">
      <view class="forms">
        <view class="form-item">
          <view class="form-item-view form-input">
            <input 
              class="uni-input" 
              type="text"
              v-model="formData.userName"
              placeholder="请输入手机号"
            />
          </view>
        </view>
        <view class="form-item">
          <view class="form-item-view form-input">
            <input 
              class="uni-input" 
              type="password" 
              password
              v-model="formData.password"
              placeholder="请输入密码"
            />
          </view>
        </view>
        <view class="form-item">
          <view class="form-item-view form-input">
            <input 
              class="uni-input" 
              type="password" 
              password
              v-model="formData.password2"
              placeholder="请再次输入密码"
            />
          </view>
        </view>
        <view class="form-item">
          <button 
            class="login-but margin-top-20" 
            :disabled="!checkFlag" 
            :class="{ 'login-but-disabled': !checkFlag }"
            @click="register"
          >
            注册
          </button>
        </view>
      </view>
      <view style="display: flex; justify-content: space-between;">
        <text @click="showType = 1" class="redOrange">快捷登录</text>
        <text @click="showType = 2" class="redOrange">已有账号登录</text>
      </view>
    </view>

    <view style="margin-top: 80rpx;display: flex; justify-content: space-between;" class="uni-padding-wrap border-top">
      <text @click="showType = 1" class="redOrange">快捷登录</text>
      <text @click="cancelLogin" class="redOrange">取消登录</text>
    </view>

    <!-- 用户协议 -->
    <view class="uni-flex flex agreement-wrap">
      <checkbox-group @change="checkboxChange">
        <label>
          <checkbox value="cb" />
          登录代表同意
          <text class="link-text" @click="gotoXieyi">《{{ systemName }}用户协议》</text>
          <text class="link-text" @click="gotoMianze">《免责声明》</text>
          ，并授权使用您的{{ systemName }}账号信息（如昵称、头像）以便您统一管理
        </label>
      </checkbox-group>
    </view>
  </view>
</template>

<script>
import ApiConstant from "@/common/ApiConstant";
import Request from '@/common/request'
import StaticConstant from "@/common/StaticConstant";
import commonTool from "../../common/js/commonTool";
import { stringIsNotEmpty } from "../../common/util";

const request = new Request()

export default {
  name: "login",
  data() {
    return {
      systemName: '',
      checkFlag: false,
      showType: 1,
      formData: {
        userName: '',
        password: '',
        password2: ''
      },
      showFlag: false
    }
  },
  computed: {
    StaticConstant() {
      return StaticConstant
    }
  },
  onLoad() {
    this.systemName = commonTool.getSystemName()
  },
  onShow() {
    // #ifdef MP-TOUTIAO
    this.dyLogin()
    // #endif
    // #ifdef MP-WEIXIN
    this.showFlag = true
    // #endif
  },
  methods: {
    // 显示协议提示
    showAgreementTip() {
      uni.showToast({
        title: `请阅读后同意《${this.systemName}用户协议》`,
        icon: 'none'
      })
    },

    // 快捷登录入口（抖音）
    handleQuickLogin() {
      if (!this.checkFlag) {
        this.showAgreementTip()
        return
      }
      this.dyLogin()
    },

    // 登录成功统一处理
    handleLoginSuccess(r, successMsg = '') {
      this.otherSystemMessage(r)
      uni.setStorageSync('token', r.result.token)
      if (r.result.userInfo) {
        uni.setStorageSync('userInfo', r.result.userInfo)
      }
      commonTool.checkVipInfo(r.result.vipInfo)
      
      if (successMsg) {
        uni.showToast({ title: successMsg, icon: 'none' })
      }
      this.reloadHome()
    },

    // 其他设备下线提示
    otherSystemMessage(r) {
      if (r.result.loginState === 'more') {
        uni.showToast({
          title: '其他设备已下线，请稍等',
          icon: 'none'
        })
      }
    },

    // 刷新到首页
    reloadHome() {
      setTimeout(() => {
        // #ifdef MP-WEIXIN
        wx.reLaunch({ url: '/pages/zyb/home' })
        // #endif
        // #ifndef MP-WEIXIN
        uni.reLaunch({ url: '/pages/zyb/home' })
        // #endif
      }, 500)
    },

    // 抖音登录
    dyLogin() {
      uni.login({
        provider: 'toutiao',
        success: (loginRes) => {
          request.post(ApiConstant.User.dyLogin, {
            code: loginRes.code,
            anonymousCode: loginRes.anonymousCode,
          }).then(r => {
            if (r.success) {
              this.handleLoginSuccess(r)
            } else {
              uni.showToast({ title: r.message, icon: 'none' })
            }
          })
        }
      })
    },

    // 微信手机号登录
    getPhoneNumber(e) {
      if (!this.checkFlag) {
        this.showAgreementTip()
        return
      }
      
      if (!e?.detail?.code) {
        uni.showToast({ title: '授权失败,请同意授权', icon: 'none' })
        return
      }

      uni.login({
        success: (res) => {
          if (!res.code) {
            uni.showModal({ title: '未获取到code' })
            return
          }
          
          request.post(ApiConstant.User.wxLogin, {
            code: res.code,
            encryptedData: e.detail.encryptedData,
            iv: e.detail.iv
          }).then(r => {
            if (r.success) {
              this.handleLoginSuccess(r)
            } else {
              uni.showToast({ title: '微信授权登录失败', icon: 'none' })
            }
          })
        }
      })
    },

    // 密码登录
    pwdLogin() {
      if (!stringIsNotEmpty(this.formData.userName)) {
        uni.showToast({ title: '请输入用户名', icon: 'none' })
        return
      }
      if (!stringIsNotEmpty(this.formData.password)) {
        uni.showToast({ title: '请输入密码', icon: 'none' })
        return
      }

      request.post(ApiConstant.User.login, {
        username: this.formData.userName,
        password: this.formData.password
      }).then(r => {
        if (r.success) {
          this.handleLoginSuccess(r)
        } else {
          uni.showToast({ title: r.message, icon: 'none' })
        }
      })
    },

    // 注册
    register() {
      if (!stringIsNotEmpty(this.formData.userName)) {
        uni.showToast({ title: '请输入手机号码', icon: 'none' })
        return
      }
      if (!/^1[3-9]\d{9}$/.test(this.formData.userName)) {
        uni.showToast({ title: '手机号码格式不正确', icon: 'none' })
        return
      }
      if (!stringIsNotEmpty(this.formData.password)) {
        uni.showToast({ title: '请输入密码', icon: 'none' })
        return
      }
      if (this.formData.password !== this.formData.password2) {
        uni.showToast({ title: '两次密码不一致', icon: 'none' })
        return
      }

      request.post(ApiConstant.User.register, {
        username: this.formData.userName,
        password: this.formData.password
      }).then(r => {
        if (r.success) {
          this.handleLoginSuccess(r, '注册成功')
        } else {
          uni.showToast({ title: r.message, icon: 'none' })
        }
      })
    },

    cancelLogin() {
      uni.navigateBack()
    },

    gotoMianze() {
      uni.navigateTo({ url: '/pages/zyb/other/disclaimer' })
    },

    gotoXieyi() {
      uni.navigateTo({ url: '/pages/zyb/other/userAgreement' })
    },

    checkboxChange(r) {
      this.checkFlag = r.detail.value?.length > 0
    }
  }
}
</script>

<style scoped lang="scss">
.content {
  margin-top: 200rpx;
  padding: 30rpx;
}

.textcenter {
  text-align: center;
  margin: 30rpx 0;
}

.title {
  font-family: "Bookshelf Symbol 7";
  margin: 0 auto;
  font-size: 90rpx;
  font-weight: 600;
}

.low-title {
  font-size: 40rpx;
}

.form-item {
  display: flex;
  align-items: center;
  margin: 30rpx 0;
}

.form-item-view {
  width: 100%;
  min-height: 80rpx;
}

.form-input {
  border: 1rpx solid #e6e6e6;
}

.uni-input {
  border: none;
}

.login-but {
  color: white;
  width: 500rpx;
  background: linear-gradient(#f96543, #f96543);
  border-radius: 10rpx;
  font-weight: 550;
}

.login-but-disabled {
  background: #eeeeee;
  color: #999;
}

.login-pwd-but {
  color: #222222;
  width: 500rpx;
  background: #eeeeee;
  border-radius: 10rpx;
  font-weight: 550;
}

.agreement-wrap {
  margin-top: 100rpx;
}

.link-text {
  color: #4975fd;
}
</style>
