<template>
  <view
    id="container"
    class="uni-flex uni-column container"
    :style="'height:' + containerH + 'px'"
  >
    <view class="bg">
      <view class="flex-item item-logo" />
      <view class="uni-padding-wrap uni-common-mt flex-item item-form">
        <form @submit="submit">
          <view class="uni-form-item uni-row">
            <view class="flex-item iconfont icon-user icon-bold" />
            <view class="flex-item" style="width: 100%">
              <uni-combox
                :candidates="candidates"
                placeholder="请输入账号"
                @input="comBoxFun"
                v-model="username"
                style="padding-left: 20rpx"
              ></uni-combox>
            </view>
          </view>
          <view class="line" />
          <view class="uni-form-item uni-row">
            <view class="iconfont icon-pwd icon-bold" />
            <view class="flex-item"
              ><input
                name="loginPwd"
                placeholder="请输入密码"
                class="login-input"
                v-model="password"
                type="text"
                password="true"
            /></view>
          </view>
          <view class="line" />
          <view class="uni-flex uni-row item">
            <view class="flex-item">
              <checkbox-group @change="checkboxChange">
                <label>
                  <checkbox
                    value="cb"
                    style="transform: scale(0.8)"
                    :checked="ckRemeber"
                  />
                  记住密码
                </label>
              </checkbox-group>
            </view>
            <view class="flex-item" @click="serverConfig">服务器配置</view>
          </view>
          <view class="uni-btn-v"
            ><button type="primary" :loading="loading" form-type="submit">
              登录
            </button>
          </view>
          <view class="company">
            <text>
              当前版本：
              <span style="color: #007aff">{{ version }}</span>
            </text>
          </view>
        </form>
      </view>
    </view>
  </view>
</template>

<script>
import sm2 from "@/utils/sm2.js";
import { publicKey } from "@/common/setting";
import tTrVue from "../../../PDA/components/t-table/t-tr.vue";
var graceChecker = require("@/common/graceChecker.js");
export default {
  data() {
    return {
      tenantId: "000000",
      username: "",
      password: "",
      disabled: false,
      redirect: "",
      containerH: "400",
      candidates: [],
      ckRemeber: false,
      loading: false,
    };
  },
  onLoad(option) {
    const { redirect } = option;
    if (redirect) this.redirect = redirect;
  },
  onShow() {
    // this.loadConfig();
    this.updateApp();
    this.candidates = [];
    let acc = uni.getStorageSync("accountMessList");
    if (acc) {
      let accList = JSON.parse(acc);
      accList.forEach((item) => {
        this.candidates.push(item.username);
      });
    }
    const login_acc = uni.getStorageSync("cur-login-acc");
    if (login_acc) {
      this.username = login_acc["username"];
      this.password = login_acc["password"];
      this.ckRemeber = true;
    }
  },
  onResize() {
    this.resizeContainer();
  },
  mounted() {
    this.resizeContainer();
    const login_acc = uni.getStorageSync("cur-login-acc");
    if (login_acc) {
      this.username = login_acc["username"];
      this.password = login_acc["password"];
      this.ckRemeber = true;
    }
    // this.loadConfig();
  },
  methods: {
    updateApp() {
      uni.getSystemInfo({
        success: (res) => {
          //检测当前平台，如果是安卓则启动安卓更新
          if (res.platform == "android") {
            // 判断版本问题
            plus.runtime.getProperty(plus.runtime.appid, (info) => {
              // info.version  当前版本
              this.version = info.version;
              uni.setStorageSync("version", info.version);
              // 更新
              // if (!uni.getStorageSync('server-config').rootUrl) return;
              // this.$ajax.request({
              //     method: 'POST',
              //     url: 'pdaAndroid/checkUpdate',
              //     data: {
              //         version: info.version
              //     },
              //     success: data => {
              //         if (data) {
              //             uni.showModal({
              //                 title: '',
              //                 content: '发现新版本，是否要更新',
              //                 confirmText: '更新',
              //                 confirmColor: '#EE8F57',
              //                 success: function(res) {
              //                     if (res.confirm) {
              //                         uni.navigateTo({
              //                             url: '/pages/downloadApp/downloadApp'
              //                         });
              //                     }
              //                 }
              //             });
              //         }
              //     }
              // });
            });
          }
        },
      });
    },
    serverConfig() {
      uni.navigateTo({
        url: "./serverConfig",
      });
    },
    checkboxChange(e) {
      if (e.detail.value.length > 0) {
        this.ckRemeber = true;
      } else {
        this.ckRemeber = false;
      }
    },
    comBoxFun(str) {
      this.password = "";
      let acc = uni.getStorageSync("accountMessList");
      if (acc) {
        let accList = JSON.parse(acc);
        accList.forEach((item) => {
          if (item.username == str) {
            this.password = item.password;
          }
        });
      }
    },
    resizeContainer() {
      const info = uni.getSystemInfoSync();
      this.containerH = info.windowHeight - 2;
    },
    // 保存账号信息方便下次登录
    setAccountMess(obj) {
      let acc = uni.getStorageSync("accountMessList");
      let accList = [];
      if (acc) {
        accList = JSON.parse(acc);
      }
      if (!this.ckRemeber) {
        obj.password = "";
      }
      accList.unshift(obj);
      let list = this.removedup(accList, "loginName");
      uni.setStorageSync("accountMessList", JSON.stringify(list));
    },
    // 数组去重
    removedup(arr, batch) {
      if (!Array.isArray(arr)) {
        return arr;
      }
      if (arr.length == 0) {
        return [];
      }
      const obj = {};
      const uniqueArr = arr.reduce(function (total, item) {
        obj[item[batch]] ? "" : (obj[item[batch]] = true && total.push(item));
        return total;
      }, []);
      return uniqueArr;
    },
    submit(e) {
      var rule = [
        {
          name: "loginPwd",
          checkType: "string",
          checkRule: "1,20",
          errorMsg: "密码应为1-20个字符",
        },
      ];
      if (this.username.length > 20 || this.username.length < 1) {
        return uni.showToast({
          icon: "none",
          title: "账号应为1-20个字符",
        });
      }
      var formData = e.detail.value;
      var checkRes = graceChecker.check(formData, rule);

      let login_acc = {
        tenantId: this.tenantId,
        username: this.username,
        password: this.password,
      };
      if (checkRes) {
        this.loading = true;
        this.$u.api
          .token(
            this.tenantId,
            this.username,
            sm2.doEncrypt(this.password, publicKey, 0)
          )
          .then((data) => {
            this.loading = false;
            this.$u.func.login(data, true);
            this.setAccountMess(login_acc, this.ckRemeber);
            if (this.ckRemeber) {
              uni.setStorageSync("cur-login-acc", login_acc);
            } else {
              uni.setStorageSync("cur-login-acc", null);
            }
          })
          .catch((err) => {
            console.log(err);
            this.loading = false;
            // this.$u.func.showToast({ title: "用户名或密码错误" });
          });
      }
    },
    handleInputCheck() {
      this.disabled = false;
    },
  },
};
</script>

<style lang="scss" scoped>
.uni-form-item .title {
  padding: 20rpx 0;
}

.item {
  margin-top: 30px;
  color: #434343;
  justify-content: space-between;
}

.container {
  background-color: #e5f8fd;
  background-repeat: no-repeat;
  background-size: 100% 100%;
  -moz-background-size: 100% 100%;
}

.bg {
  width: 100%;
  height: 100%;
}

.label {
  color: #eeeeee;
}

.item-logo {
  height: 58px;
  margin: 50px 0;
  margin-left: 16%;
  background-image: url(../../static/images/logo.png);
  background-size: 187px;
  background-repeat: no-repeat;
}

.item-config {
  margin-left: 25px;
  background-size: 187px;
  background-repeat: no-repeat;
  font-size: 12px;
  font-weight: 500;
}

.item-center {
  display: flex;
  justify-content: center;
  margin-top: 10px;
}

.item-center div {
  height: 200px;
  width: 200px;
  background-image: url(../../static/images/login_center.png);
  background-size: 200px;
  margin-top: 0px;
  background-repeat: no-repeat;
}

.item-form {
  height: 200px;
}

.line {
  line-height: 0rpx;
  height: 3rpx;
  border: 0px;
  background-color: #999999;
}

.login-input {
  height: 50px;
  margin-left: 10px;
}

.icon-bold {
  font-size: 20px;
  font-weight: 800;
  margin-top: 5px;
}

.item-row {
  margin-top: 40rpx;
}

.company {
  height: 10%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 34rpx;
}
</style>
