<template>
  <div id="bg">
    <el-container>
      <el-header></el-header>
      <el-main>
        <div class="bg">
          <!--登录框-->
          <el-card v-if="!selectShop" class="box-card">
            <h5 class="title">
              <img src="../../assets/img/login/logo.png" alt="">
            </h5>
            <span class="subtitle">小飞龙场馆管理系统</span>
            <el-form ref="form" :model="form" label-width="0px">
              <el-form-item label="">
                <el-input v-model="form.name" placeholder="用户名"></el-input>
              </el-form-item>
              <el-form-item label="">
                <el-input v-model="form.pwd" placeholder="密码" type="password"></el-input>
              </el-form-item>
              <el-form-item label="">
                <el-input v-model="form.valid" placeholder="验证码"
                          @keyup.enter.native="onSubmit"></el-input>
                <img id="validImg" :src="valImgSrc" alt="" width="100px" height="42px"
                     title="看不清？刷一下试试！" @click="getGenVerifyPic">
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="onSubmit">登陆</el-button>
              </el-form-item>
            </el-form>
          </el-card>

          <!--门店选择框-->
          <el-card v-if="selectShop" class="box-card">
            <h5 class="title">
              <img src="../../assets/img/login/logo.png" alt="">
            </h5>

            <span class="subtitle">小飞龙场馆管理系统</span>

            <el-table ref="singleTable" :data="shopTableData" highlight-current-row
                      @current-change="handleCurrentChange"
                      style="width: 100%">
              <el-table-column width="55">
                <template slot-scope="scope">
                  <el-radio v-model="tableRadio" :label="scope.row"><i></i></el-radio>
                </template>
              </el-table-column>
              <el-table-column prop="name" label="店名" width="120"/>
              <el-table-column prop="contacts" label="联系人" width="120"/>
              <el-table-column prop="addr" label="地址"/>
            </el-table>

            <el-button type="primary" @click="enterShop()" style="margin-top: 150px">确定</el-button>

          </el-card>

        </div>

      </el-main>
      <el-footer></el-footer>
    </el-container>
  </div>
</template>

<script>

import {
  GenVerifyImageRequest,
  SignInRequest,
  ShopListRequest
} from "@/grpc/base_pb";
import Global from '../../Global.js'

let qs = require('qs');

export default {
  data() {
    return {
      selectShop: false,//控制显示页面步骤
      form: {
        name: '',
        pwd: '',
        valid: '',
        picId: '',
      },
      tableRadio: [],
      shopTableData: [],
      currentRow: null,
      valImgSrc: '',
      valImgId: '',
      overtime: '',
      userLevel: '',
      userLevelText: '',
    }
  },
  mounted() {
    let that = this;
    this.overtime = new Date();
    this.getGenVerifyPic();
    // 如果是手动退出用户
    if (that.$route.query.status == 10010) {
      // 刷新验证图
      that.changeValImg();
      // 重置倒计时
      that.overtime = new Date();
    }
    // 如果是切换店铺
    if (that.$route.query.status == 10011) {
      this.checkUserShopList();
    }
    // checkScreen
    if (document.body.clientWidth < 1024) {
      this.$message.warning('请横屏使用本系统');
    }
  },
  methods: {
    //切换table当前选中行
    handleCurrentChange(val) {
      this.currentRow = val;
      this.tableRadio = val
    },
    //刷新验证码
    getGenVerifyPic() {
      let that = this;
      let getRequest = new GenVerifyImageRequest();
      getRequest.setWidth(200);
      getRequest.setHeight(100);
      that.client.genVerifyImage(getRequest, {}, (err, GenVerifyImageReply) => {
        that.valImgSrc = GenVerifyImageReply.getImagebase64()
        that.valImgId = GenVerifyImageReply.getCodeid()
        that.form.picId = GenVerifyImageReply.getCodeid()
      });
    },
    //点击验证码切换
    changeValImg: function () {
      // 刷新验证图
      this.getGenVerifyPic();
    },
    //提交登陆
    onSubmit() {
      let that = this;
      let username = this.form.name;
      let userPwd = this.form.pwd;
      let userValid = this.form.valid;
      // 重置验证码超时
      that.overtime = new Date();
      if (!globalValid(username, 2, 17, '用户名', that)) return;
      if (!globalValid(userPwd, 5, 17, '密码', that)) return;
      if (!globalValid(userValid, 3, 5, '验证码', that)) return;
      this.userLogin();
    },
    // 用户登录
    userLogin: function () {
      const that = this;
      let username = this.form.name;
      let userPwd = this.form.pwd;
      let userValid = this.form.valid;
      let currDate = new Date();
      let betweenTime = currDate - that.overtime;
      let s = 120;
      if (betweenTime > s * 1000) {
        that.changeValImg();
        that.$message.error('验证码已超时，请重新输入');
        return false
      }
      let paraRequest = new SignInRequest();
      paraRequest.setCodeid(this.form.picId);
      paraRequest.setVerifycode(userValid);
      paraRequest.setName(username);
      paraRequest.setPassword(userPwd);
      that.client.signIn(paraRequest, {}, (error, paraReply) => {
        if (error == null) {
          localStorage.token = paraReply.getToken();
          this.checkUserShopList();
        } else {
          let res = error;
          if (res.code == 403) {
            that.form.pwd = '';
            that.$notify({
              title: '警告',
              message: '密码错误，请重新输入',
              type: 'warning'
            });
          } else if (res.code == 4005) {
            that.$notify({
              title: '警告',
              message: '验证码错误，请重新输入',
              type: 'warning'
            });
          } else {
            that.$notify({
              title: '警告',
              message: res.message + ',错误代码：' + res.code,
              type: 'warning'
            });
          }
          that.form.valid = '';
          that.selectShop = false;
          that.changeValImg();
        }
      });
    },
    // 用户可选择门店列表
    checkUserShopList: function () {
      let that = this;

      let paraRequest = new ShopListRequest();
      paraRequest.setName("");
      paraRequest.setStatus(99);//99:全部 9:已删除 1:正常 0:禁止
      paraRequest.setSid(-1);//上级ID，-1查全部

      console.log(localStorage.token);
      that.client.manageableShopList(paraRequest, {"Token": localStorage.token}, (err, ShopListReply) => {
            if (err == null) {
              let res = ShopListReply.getListList();
              if (res) {
                //账号下只有一家店铺
                if (res.length === 1) {
                  localStorage.shopId = res[0].getShopuuid();
                  localStorage.shopName = res[0].getName();
                  localStorage.userName = res[0].getContacts();
                  localStorage.canChange = 0;

                  if (res[0].getStatus(0) === 1) {
                    that.$router.push({path: '/'});
                  } else {
                    that.$message.error('该商家当前状态异常' + res[0].getStatus());
                  }
                }
                // //账号下有多家店铺
                if (res.length > 1) {
                  that.selectShop = true;
                  localStorage.canChange = 1;
                  let jsonObjList = [];
                  res.forEach((item, i) => {
                    let jsonObj = {shopId: "", name: "", addr: "", contacts: "", status: 1};
                    jsonObj.shopId = item.getShopuuid();
                    jsonObj.name = item.getName();
                    jsonObj.addr = item.getAddr();
                    jsonObj.contacts = item.getContacts();
                    jsonObj.status = item.getStatus();
                    jsonObjList.push(jsonObj);
                  })
                  that.shopTableData = jsonObjList;
                }
              }
            } else {
              let res = err;
              that.$message.error(res.message + ',错误代码：' + res.code);
            }
          }
      )
    },
    //提交选中行事件
    enterShop() {
      let that = this;
      if (that.currentRow == null || that.currentRow.length == 0) {
        this.$message.error("请先选中商家");
        return false
      }
      localStorage.shopId = that.currentRow.shopId;
      localStorage.shopName = that.currentRow.name;
      localStorage.userName = that.currentRow.contacts;
      if (this.currentRow.status === 1) {
        that.$router.push({path: '/'});
      } else {
        that.$message.error('该商家当前状态异常\t' + this.currentRow.status);
      }
    },
  },
}
</script>

<style scoped>
#bg {
  width: 100%;
  height: 100%;
  overflow: hidden;
  display: block;
  margin: 0 auto;
  background: #F0F2F5 url("../../assets/img/login/bg.png") no-repeat top center;
  background-size: 100% 100%;
}

.title {
  font-size: 60px;
  text-align: center;
  color: #fff;
  margin-top: 3%;
  margin-bottom: 5px;
}

.title img {
  width: 362px;
  overflow: hidden;
  display: block;
  margin: 0 auto;
}

.subtitle {
  width: 100%;
  overflow: hidden;
  display: block;
  margin: 0 auto;
  text-align: center;
  color: #414141;
  margin-bottom: 79px;
  font-size: 41px;
}

.box-card {
  width: 577px;
  height: 733px;
  overflow: hidden;
  float: right;
  margin-top: 40px;
  margin-right: 10%;
}

.box-card .boxTitle {
  font-size: 30px;
  margin-bottom: 15px;
}

#validImg {
  position: relative;
  float: right;
  bottom: 52px;
}

/deep/ .el-form {
  width: 422px;
  overflow: hidden;
  display: block;
  margin: 0 auto;
}

/deep/ .el-input__inner {
  height: 44px;
  background: #F0F2F5;
  border-radius: 0;
  margin-bottom: 10px;
}

/deep/ .el-button--primary {
  width: 100%;
  height: 52px;
  /*line-height: 32px;*/
  overflow: hidden;
  display: block;
  margin: 0 auto;
  font-size: 18px;
}

/*ipad only*/
@media only screen and (max-width: 1366px) {
  #bg {
    background-size: 100%;
    background-color: #F2F2F2;
  }

  .box-card {
    width: 500px;
    height: 550px;
    margin-top: 0;
    margin-right: 1%;
  }

  .subtitle {
    margin-bottom: 10px;
  }

  .el-form-item {
    margin-bottom: 12px;
  }
}
</style>
