<template>
  <div class="login-box" :style="'height:' + fullHeight + 'px'" v-loading="loading">
    <img src="../assets/imageOne/222.jpg" alt class />
    <div class="piece">
      <!-- title -->
      <div class="title">
        <!-- <div class="title-text">病虫测报数据采集系统</div> -->
        <div class="title-text">虫害识别系统</div>
      </div>

      <!-- input -->
      <div class="login" v-if="inptShow">
        <el-form :model="ruleForm" ref="ruleForm" label-width="50px" class="demo-ruleForm">
          <el-form-item prop="username">
            <el-input
              v-model="ruleForm.username"
              ref="input1"
              maxlength="11"
              placeholder="请输入账户"
              clearable
              prefix-icon="el-icon-mobile-phone"
              autocomplete="on"
            ></el-input>
          </el-form-item>

          <div class="paswd_box">
            <img src="../../static/suo.png" alt class="paswd_box_imgA" />
            <div class v-if="pwdType">
              <input
                class="paswd_ipt pasword"
                type="password"
                v-model="ruleForm.password"
                placeholder="请输入密码"
                ref="input2"
              />
            </div>
            <div class v-else>
              <input
                class="paswd_ipt textword"
                type="text"
                v-model="ruleForm.password"
                placeholder="请输入密码"
                ref="input2"
              />
            </div>
            <img :src="seen ? seenImg : unseenImg" @click="changeType()" class="paswd_box_imgB" />
          </div>

          <div class="box clearfix">
            <div class="automate">
              <el-checkbox v-model="checked" style="color:#a0a0a0;">
                <span class="automate_text">记住密码</span>
              </el-checkbox>
            </div>
          </div>

          <el-form-item>
            <el-button type="primary" @click.13="login()">
              <i class="el-icon-loading" v-show="iShow"></i>
              登录
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 首次登陆时要输入验证码 -->
      <div class="verification_box" v-else>
        <!-- <div class="verify_text">请先输入验证码，验证成功后才能进入程序进行操作</div> -->
        <el-input
          v-if="iptSHow"
          class="verify_ipt verification"
          placeholder="请输入激活码,激活成功后才可进入程序"
          v-model="inputV"
          clearable
        ></el-input>
        <!-- <el-input v-else class="verify_ipt verification" readonly=true v-model="inputV" clearable></el-input> -->
        <el-input v-else class="verify_ipt verification" v-model="inputV" clearable></el-input>
        <div class="verify_btn">
          <el-button type="primary" @click.13="verify()">
            <i class="el-icon-loading" v-show="iShow"></i>
            提交
          </el-button>
        </div>
      </div>

      <!-- 更新提示弹框-->
      <el-dialog title="提示" :visible.sync="dialogVisible" width="60%">
        <span>是否更新到最新版本</span>
        <span slot="footer" class="dialog-footer">
          <div class="login-box_div">
            <!-- 测试 -->
            <el-button @click="dialogVisible = false, offApp()" class="kunchongBtn">取 消</el-button>
          </div>

          <div class="login-box_div">
            <!-- 测试 -->
            <el-button @click="dialogVisible = false, newApp()" class="binghaiBtn">确 定</el-button>
          </div>
        </span>
      </el-dialog>

      <!-- 进度条 -->
      <div class="schedule_box" v-if="scheduleShow" :style="'height:' + fullHeight + 'px'">
        <div class="schedule_box_div">
          <div class="schedule_box_title">正在下载...</div>
          <el-progress :percentage="percentage" :color="customColors"></el-progress>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
function filterInput(val) {
  // 这里过滤的是除了英文字母和数字的其他字符
  return val.replace(/[^A-z0-9]/, "");
}
import VueInputCode from "vue-input-code"; //验证码样式
export default {
  name: "login",
  data() {
    let self = this;
    return {
      isClick: true,
      loading: true, //加载
      ruleForm: {
        username: "",
        password: ""
      },
      seen: "",
      checked: false,
      iShow: false, //登录缓冲图标
      fullHeight: document.documentElement.clientHeight,
      unseenImg: "./static/eyes.png", //看不见
      seenImg: "./static/eye.png", //看得见密码
      pwdType: true, //此时文本框隐藏，显示密码框
      loaded: false,
      center: [121.59996, 31.197646],
      lng: 0,
      lat: 0,
      // loaded: false,
      timer: "", //定时器
      checked: false, //记住密码多选框

      dialogVisible: false, //更新弹框
      scheduleShow: false, //进度条
      redataName: "", //获取到后端发来的app的名字
      //测试进度条
      percentage: 0,
      customColor: "#409eff",
      customColors: [
        { color: "#f56c6c", percentage: 5 },
        { color: "#e6a23c", percentage: 10 },
        { color: "#5cb87a", percentage: 20 },
        { color: "#1989fa", percentage: 30 },
        { color: "#6f7ad3", percentage: 40 },
        { color: "#f56c6c", percentage: 50 },
        { color: "#e6a23c", percentage: 60 },
        { color: "#5cb87a", percentage: 70 },
        { color: "#1989fa", percentage: 80 },
        { color: "#6f7ad3", percentage: 90 },
        { color: "#6f7ad3", percentage: 100 }
      ],
      radio: "1", //账号身份的单选
      inptShow: false, //激活验证码显示登陆按钮
      inputV: "", //验证码
      iptSHow: true //判断当前设备是否激活过
    };
  },
  components: {
    VueInputCode
  },
  watch: {
    fullHeight(val) {
      //监控浏览器高度变化
      if (!this.timer) {
        this.fullHeight = val;
        this.timer = true;
        let that = this;
        setTimeout(function() {
          //防止过度调用监测事件，导致卡顿
          that.timer = false;
        }, 400);
      }
    },

    //判断进度条是否为100%
    percentage(time) {
      if (time === 100) {
        this.scheduleShow = false;
        this.$message({
          message: "已经下载成功，可以安装",
          type: "success",
          duration: 1000
        });
      }
    },

    // //监听账号
    // "ruleForm.username"(val) {
    //   this.$nextTick(() => {
    //     this.ruleForm.username = filterInput(val);
    //   });
    // },

    //监听密码
    "ruleForm.password"(val) {
      this.$nextTick(() => {
        this.ruleForm.password = filterInput(val);
      });
    }
  },
  created() {
    this.getLocalStorage(); //页面加载调用获取LocalStorage值
  },
  mounted() {
    let _this = this;
    _this.get_boderHeight();
    _this.ceshi();

    // _this
    //   .$axios({
    //     method: "get",
    //     url: "bigservers/app_upgrade"
    //   })
    //   .then(res => {
    //     if (res.data.app_num === "1.1.7") {
    //     } else if (res.data.app_num > "1.1.7") {
    //       this.$message({
    //         message: "检测到有新版本",
    //         type: "success",
    //         duration: 1000
    //       });
    //       _this.dialogVisible = true;
    //       localStorage.setItem("redataName", res.data.app_name);
    //       _this.redataName = res.data.app_name;
    //       console.log(res.data.app_name);
    //     }
    //   })
    //   .catch(error => {});
  },
  methods: {
    //动态获取浏览器高度
    get_boderHeight() {
      const that = this;
      window.onresize = () => {
        return (() => {
          window.fullHeight = document.documentElement.clientHeight;
          that.fullHeight = window.fullHeight;
        })();
      };
    },

    ceshi() {
      //判断用户是否激活app
      var _this = this;
      var uuID = localStorage.getItem("uuID");
      console.log(localStorage.getItem("uuID") + "还未请求时的参数");

      let postData = this.$qs.parse({
        imei: uuID
      });
      _this
        .$axios({
          method: "post",
          url: "bigservers/decide",
          data: postData
        })
        .then(res => {
          console.log("请求成功了");
          console.log(localStorage.getItem("uuID") + "请求成功的参数");
          if (res.data !== null && res.data !== 2 && res.data !== 0) {
            _this.inptShow = true;
            _this.inputV = res.data[0].cipher;
            _this.loading = false;
            console.log("已经注册过了");
          } else if (res.data == 2) {
            //还未注册
            _this.inptShow = false; //登录按钮
            _this.iptSHow = true;
            _this.loading = false;
            console.log("需要填写验证码");
          } else if (localStorage.getItem("uuID") == null) {
            this.$alert("获取设备信息失败，请重启软件", "提示", {
              confirmButtonText: "确定",
              callback: action => {
                var webview = plus.webview.currentWebview(); //获取当前页面的
                plus.runtime.quit(); //退出应用
              }
            });
          }
        })
        .catch(error => {});
    },

    //密码的显示隐藏
    changeType() {
      this.seen = !this.seen; //小眼睛的变化
      this.pwdType = !this.pwdType; //跟着小眼睛变化，密码框隐藏显示文本框，内容就显示了
    },

    setLocalStorage(u, p) {
      localStorage.setItem("Name", u);
      localStorage.setItem("passWord", p);
    },

    //读取localStorage
    getLocalStorage() {
      let _this = this;
      if (
        localStorage.getItem("Name") !== null &&
        localStorage.getItem("passWord") !== null
      ) {
        _this.ruleForm.username = localStorage.getItem("Name");
        _this.ruleForm.password = localStorage.getItem("passWord");
        _this.checked = true;
      }
    },

    //清除localStorage
    clearLocalStorage() {
      localStorage.removeItem("Name");
      localStorage.removeItem("passWord");
    },

    // 登录
    login() {
      let _this = this;
      _this.username = _this.$refs.input1.value; //获取input
      _this.password = _this.$refs.input2.value;
      var isClick = _this.isClick;
      if (isClick === true) {
        _this.isClick = false;
        if (_this.ruleForm.username === "" || _this.ruleForm.password === "") {
          this.$notify({
            title: "失败",
            message: "账号密码不能为空",
            type: "error",
            duration: 1000
          });
        } else {
          let login = this.$qs.stringify({
            username: this.username,
            password: this.password
          });
          this.iShow = true;
          this.$axios({
            method: "post",
            url: "bigservers/app_log",
            data: login
          }).then(res => {
            if (res.data !== 1 && res.data !== 2) {
              //判断用户是否没有把app升级到最新版本
              if (sessionStorage.getItem("offApp") === null) {
                sessionStorage.setItem("login", this.ruleForm.username);
                this.iShow = false;
                this.$notify({
                  title: "成功",
                  message: "您已成功登陆",
                  type: "success",
                  duration: 1000
                });
                this.$router.replace("/home");
                if (_this.checked == true) {
                  _this.setLocalStorage(
                    _this.ruleForm.username,
                    _this.ruleForm.password
                  );
                } else {
                  //清空localStorage
                  _this.clearLocalStorage();
                }

                //判断账号是什么身份
                if (
                  res.data[0].is_active === true &&
                  res.data[0].is_staff === true &&
                  res.data[0].is_superuser === true
                ) {
                  console.log("这是管理者");
                  sessionStorage.setItem("Administrator", "管理员"); //管理员
                  sessionStorage.removeItem("common");
                } else {
                  console.log("这是普通用户");
                  sessionStorage.setItem("common", "普通用户"); //普通用户
                  sessionStorage.removeItem("Administrator");
                }
                _this
                  .$axios({
                    method: "get",
                    url: "bigservers/app_user_in"
                  })
                  .then(res => {
                    localStorage.setItem(
                      "personAxios",
                      JSON.stringify(res.data)
                    );
                  })
                  .catch(error => {
                    this.$notify({
                      title: "失败",
                      message: "请求失败",
                      type: "error",
                      duration: 1000
                    });
                  });

                //
                if (localStorage.getItem("personAxios") !== null) {
                  _this.isShow = true;
                } else {
                  _this.isShow = false;
                }
              } else if (sessionStorage.getItem("offApp") !== null) {
                this.$notify({
                  title: "警告",
                  message: "请您先升级到最新版",
                  type: "error",
                  duration: 1000
                });
                const timer = setInterval(() => {
                  this.iShow = false;
                }, 3000);
              }
            } else if (res.data === 1) {
              console.log("失败");
              this.$notify({
                title: "失败",
                message: "用户名错误或用户不存在",
                type: "error",
                duration: 1000
              });
              console.log("error submit!!");
              const timer = setInterval(() => {
                this.iShow = false;
              }, 3000);
              return false;
            } else if (res.data === 2) {
              console.log("失败1");
              this.$notify({
                title: "失败",
                message: "密码错误",
                type: "error",
                duration: 1000
              });
              console.log("error submit!!");
              const timer = setInterval(() => {
                this.iShow = false;
              }, 3000);
              return false;
            }
          });
        }
        setTimeout(function() {
          _this.isClick = true;
        }, 1500);
      }
    },

    //升级到最新版本弹框
    newApp() {
      // console.log(this.redataName);
      // window.location.href =
      //   "bigservers/app_file/" + this.redataName;
      // this.scheduleShow = true;
      // const timer = setInterval(() => {
      //   this.percentage += 10;
      //   if (this.percentage > 100) {
      //     this.percentage = 100;
      //   }
      // }, 4000);
      // var wait = plus.nativeUI.showWaiting("下载更新中，请勿关闭");
      // //创建一个下载任务
      // var dtask = plus.downloader.createDownload(
      //   "bigservers/app_file/" + this.redataName,
      //   {
      //     method: "GET"
      //   },
      //   function(d, status) {
      //     if (status == 200) {
      //       console.log("Download success: " + d.filename);
      //       plus.runtime.install(d.filename); // 安装下载的apk文件
      //     } else {
      //       alert("更新失败");
      //       //						plus.runtime.install('../H5B2852C7_0925104810.apk'); // 安装下载的apk文件
      //     }
      //     wait.close();
      //   }
      // );
      // //开始下载
      // dtask.start();
    },

    //关闭app
    offApp() {
      // window.location.href = "about:blank";
      // window.close();
      sessionStorage.setItem("offApp", "1"); //在本地存一个标识如果有这个标识，用户就不能进入home进行操作
    },

    //点击提交验证码
    verify() {
      let _this = this;
      var isClick = _this.isClick;
      if (isClick === true) {
        _this.isClick = false;
        let postData = _this.$qs.parse({
          num: _this.inputV,
          imei: localStorage.getItem("uuID")
        });
        _this
          .$axios({
            method: "post",
            url: "bigservers/census",
            data: postData
          })
          .then(res => {
            if (res.data === 0) {
              //没有获取手机meid
              this.$notify.error({
                title: "失败",
                message: "验证失败",
                duration: 1000
              });
            } else if (res.data === 1) {
              //该手机已绑定其它验证码
              this.$notify.error({
                title: "失败",
                message: "该手机已绑定其它验证码",
                duration: 1000
              });
            } else if (res.data === 2) {
              // 验证码输入错误
              this.$notify.error({
                title: "失败",
                message: " 验证码输入错误",
                duration: 1000
              });
            } else if (res.data === 3) {
              //该验证码已绑定其它手机号
              this.$notify.error({
                title: "失败",
                message: " 该验证码已绑定其它手机号",
                duration: 1000
              });
            } else if (res.data === 4) {
              //绑定验证码
              this.$notify({
                title: "成功",
                message: "绑定成功",
                duration: 2000,
                type: "success"
              });
              _this.inptShow = true;
              localStorage.setItem("decide", "1"); //存储一个标识，进行判断当前需要显示激活码
            } else if (res.data === 5) {
              //验证成功
              this.$notify({
                title: "成功",
                message: "验证成功",
                duration: 1000,
                type: "success"
              });
              _this.inptShow = true;
              localStorage.setItem("decide", "1"); //存储一个标识，进行判断当前需要显示激活码
            }
          })
          .catch(error => {
            this.$notify.error({
              title: "失败",
              message: "验证失败",
              duration: 1000
            });
          });

        setTimeout(function() {
          _this.isClick = true;
        }, 1500);
      }
    }
  }
};
</script>

<style lang="scss">
@import "../assets/style/bus.scss";
@import "../assets/style/scss/login.scss";
</style>