<template>
  <div class="login-container">
    <div class="login-box">
      <el-form
        ref="loginForm"
        :model="loginForm"
        :rules="loginRules"
        class="login-form"
        auto-complete="on"
        label-position="left"
      >
        <div class="logo">
          <img
            src="http://jingcheng-h5temp.oss-cn-shanghai.aliyuncs.com/1543283673332.png?Expires=1545111060&OSSAccessKeyId=LTAIkc75dpkJw8Lb"
          >
        </div>
        <h3 class="title">智慧社区物业平台</h3>
        <el-form-item prop="username">
          <span class="svg-container">
            <svg-icon icon-class="user"/>
          </span>
          <el-input
            v-model="loginForm.username"
            name="username"
            type="text"
            auto-complete="on"
            placeholder="请输入手机号"
          />
        </el-form-item>
        <div class="pwdSend">
          <el-form-item prop="password">
            <!--@blur.prevent="getUserCommunity"-->
            <el-input
              v-model="loginForm.password"
              name="password"
              type="text"
              auto-complete="on"
              placeholder="请输入验证码"
              @keyup.enter.native="handleLogin"
            />
          </el-form-item>
          <el-button v-if="isCodeNum == false" type="primary" @click="sendCode();">发送验证码</el-button>
          <el-button v-else type="primary" disabled>{{ codeNum + '秒后重新获取' }}</el-button>
        </div>
        <div v-show="isCommunityDiv" :class="{selectDiv: isSelectDiv, widSelectDiv: isWidSelectDiv}">
          <el-form-item>
            <div v-if="isSelectCommunity" class="select-community">
              <i class="el-icon-circle-close-outline" style="margin-left: 60px;"/>  当前手机号未绑定任何社区
            </div>
          </el-form-item>
        </div>
        <!-- @click.native.prevent="handleLogin" -->
        <!-- v-if="isLoginButton" -->
        <el-button
          :loading="loading"
          type="primary"
          style="width:100%;"
          @click.native.prevent="getUserCommunity"
        >登录</el-button>
        <!--<el-button v-else type="primary" style="width:100%;" disabled>登录</el-button>-->
      </el-form>
    </div>
    <el-dialog :visible.sync="dialogFormVisible" title="小区" width="20%" append-to-body>
      <el-select v-model="loginForm.communityId" placeholder="请选择小区">
        <el-option
          v-for="item in communityArr"
          :key="item.id"
          :label="item.communityName"
          :value="item.id"/>
      </el-select>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleLogin">确 定</el-button>
      </div>
    </el-dialog>
    <span class="bottom-desc">Copyright © 南京锦城佳业网络科技有限公司, All Rights Reserved.</span>
  </div>
</template>

<script>
import { isvalidUsername, validatCode } from '@/utils/validate'
import { mapState, mapActions } from 'vuex'

export default {
  name: 'Login',
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!isvalidUsername(value)) {
        callback(new Error('请输入正确的手机号'))
      } else {
        callback()
      }
    }
    const validateIndexCode = (rule, value, callback) => {
      if (!validatCode(value)) {
        callback(new Error('请输入正确的验证码'))
      } else {
        callback()
      }
    }
    return {
      isCommunityDiv: false, // 是否显示带有 社区选项的div
      isWidSelectDiv: true,
      isSelectDiv: false,
      isSelectCommunity: false, // 是否显示 社区选项
      isLoginButton: false, // 默认按钮为不可点击
      dialogFormVisible: false, // 显示小区选择
      communityArr: [], // 小区集合
      loginForm: {
        username: '',
        password: '',
        communityId: ''
      },
      loginRules: {
        username: [{ required: true, trigger: 'blur', validator: validateUsername }],
        password: [{ required: true, trigger: 'blur', validator: validateIndexCode }]
      },
      loading: false,
      redirect: undefined,
      isCodeNum: false,
      codeNum: 60 // 验证码倒计时 60 秒
    }
  },
  computed: {
    ...mapState('community', {
      communityList: s => s.list
    })
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    }
  },
  methods: {
    ...mapActions('community', [
      'UserCommunity'
    ]),
    handleLogin() {
      // 隐藏选择小区弹框
      this.dialogFormVisible = false
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          this.$store.dispatch('Login', this.loginForm).then((res) => {
            if (res.code === '0') {
              console.log('登陆结果: ', res)
              this.loading = false
              // this.$router.push({ path: this.redirect || '/index' })
              this.$router.push({ name: 'index' })
            } else {
              this.$message.error(res.message)
              this.loading = false
            }
          }).catch(() => {
            this.loading = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
      // this.$router.push({ path: this.redirect || '/index' })
    },
    sendCode() {
      // 默认为1, 1表示不成功
      let resCode = 1
      this.$store.dispatch('SendCode', this.loginForm.username).then((res) => {
        // 成功则为 0
        resCode = res.code
        // 为0发送成功
        if (resCode === '0') {
          this.codeNum = 60
          this.isCodeNum = true
          const time = setInterval(() => {
            if (this.codeNum === 1) {
              clearInterval(time)
              this.isCodeNum = false
            }
            this.codeNum--
          }, 1000)
        } else {
          this.$message.error(res.message)
        }
      }).catch(() => {
        console.log('error sendcode')
      })
    },
    getUserCommunity() { // 根据用户的手机号和验证码 获取用户的管理的小区
      const loading = this.$loading({
        lock: true,
        text: '请稍后...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      this.UserCommunity(this.loginForm).then((res) => {
        if (res.code === '0') {
          this.dialogFormVisible = true
          this.communityArr = res.data
          this.loading = false
          loading.close()
        } else {
          loading.close()
          this.$message.error(res.message)
          this.loading = false
        }
        this.checkPhoneAndCode()
      }).catch(() => {
        // 提示 当前手机号未绑定任何社区
        // 显示 div
        this.isCommunityDiv = true
        this.isSelectCommunity = true
        this.isWidSelectDiv = false
        this.isSelectDiv = true
        this.isLoginButton = false
        loading.close()
        console.log('get UserCommunity list error')
      })
    },
    checkPhoneAndCode() { // 失去焦点的时候获取 获取用户的管理的小区
      console.log('失去焦点')
      const communitys = this.communityArr
      console.log('接收到的数据:', communitys)
      console.log('大小:', communitys.length)
      if (communitys.length === 0) {
        // 提示 当前手机号未绑定任何社区
        // 显示 div
        this.isCommunityDiv = true
        this.isSelectCommunity = true
        this.isWidSelectDiv = false
        this.isSelectDiv = true
        this.isLoginButton = false
      } else if (communitys.length === 1) {
        // 只有一个小区的时候, 默认选中
        // 显示 div
        // this.isCommunityDiv = true
        this.isCommunityDiv = false
        this.isWidSelectDiv = false
        this.isSelectCommunity = false
        this.isSelectDiv = false
        this.loginForm.communityId = communitys[0].id
        // 执行登陆方法
        this.handleLogin()
      } else {
        // 让用户选择
        // 显示 div
        // this.isCommunityDiv = true
        this.isCommunityDiv = false
        this.isWidSelectDiv = true
        this.isSelectCommunity = false
        this.isSelectDiv = false
      }
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
$bg: #2d3a4b;
$light_gray: #eee;

/* reset element-ui css */
.login-container {

  .bottom-desc{
    position: absolute;
    top: 95%;
    left: 39.5%;
    color: #fff
  }

  .login-box{
    position: absolute;
    width: 400px;
    height: 425px;
    background-color: rgba(21,22,58,0.53);
    top: 28%;
    left: 40%;
    border-radius: 10px;
    box-shadow:  #666 0px 0px 10px inset;
    }

  .el-input {
    display: inline-block;
    height: 40px;
    width: 85%;
    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 4px 5px 12px 15px;
      color: $light_gray;
      height: 47px;
      &:-webkit-autofill {
        -webkit-box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: #fff !important;
      }
    }
  }
  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    color: #454545;
  }
  .select-community {
    float: left;
    color: #F56C6C;
  }
  .selectDiv {
    margin-top: 80px;
  }
  .widSelectDiv {
    margin-top: 80px;
    width: 159px;
  }
}
</style>

<style rel="stylesheet/scss" lang="scss" scoped>
.logo{
  text-align:center;
  img{
    margin-bottom:10px;
  }
}
$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #eee;
.login-container {
  position: fixed;
  height: 100%;
  width: 100%;
  background-color: $bg;
  .login-form {
    position: absolute;
    left: 0;
    right: 0;
    width: 382px;
    max-width: 100%;
    padding: 35px 35px 15px 35px;
    margin: 20px auto;
    .pwdSend {
      float: left;
      .el-form-item {
        float: left;
        width: 158px;
        .el-input {
          float: left;
        }
      }
      .el-button {
        margin-left: 10px;
      }
    }
  }
  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;
    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }
  .svg-container {
    padding: 0px 5px 0px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }
  .title {
    font-size: 26px;
    font-weight: 400;
    color: $light_gray;
    margin: 0px auto 40px auto;
    text-align: center;
    font-weight: bold;
  }
  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
}
</style>
