<template>
  <view class="page-login" :style="{ backgroundImage: `url(${image.login.bg1})` }">
    <view class="logo">
      <u-image width="288rpx" height="85rpx" :src="image.global.logo2"></u-image>
      <!-- <span>V{{ Version }}</span> -->
    </view>
    <u-form class="form" :model="form" ref="form" :border-bottom="false" :error-type="['toast']">
      <u-form-item
        class="form-item"
        prop="username"
        :border-bottom="false"
        left-icon="/static/icons/icon-48.png"
        :left-icon-style="{
          width: '36rpx',
          height: '36rpx',
          margin: '24rpx 20rpx',
        }"
      >
        <u-input
          @confirm="onBarCodeConfirm"
          class="input"
          @keyup.enter="EnterPress"
          v-model="form.username"
          placeholder="请输入账号"
          placeholder-style="color: rgba(255, 255, 255, 0.36)"
          :custom-style="{
            height: '88rpx',
            marginRight: '36rpx',
            color: 'rgba(255, 255, 255, 0.67)',
          }"
        />
      </u-form-item>

      <u-form-item
        class="form-item"
        prop="password"
        :border-bottom="false"
        left-icon="/static/icons/icon-49.png"
        :left-icon-style="{
          width: '36rpx',
          height: '36rpx',
          margin: '24rpx 20rpx',
        }"
      >
        <u-input
          :focus="focustwo"
          @confirm="onBarCodeConfirmteo"
          class="input"
          @keyup.enter="EnterPress"
          v-model="form.password"
          placeholder="请输入密码"
          type="password"
          placeholder-style="color: rgba(255, 255, 255, 0.36)"
          :custom-style="{
            height: '88rpx',
            marginRight: '36rpx',
            color: 'rgba(255, 255, 255, 0.67)',
          }"
        />
      </u-form-item>
    </u-form>
    <!-- <view class="i18n" @click="i18nOptionsShow = true">
      <view class="dropdown-text">{{ $i18n.locale === 'en' ? 'English' : $i18n.locale === 'cn' ? '简体中文' : 'русск' }} </view>
      <u-icon :class="i18nOptionsShow ? 'dropdown-icon-active' : 'dropdown-icon'" size="16" name="/static/icons/icon-50.png"></u-icon>
      <u-action-sheet :list="i18nList" v-model="i18nOptionsShow" @click="onLanguageSelect"></u-action-sheet>
    </view> -->
    <u-button
      shape="circle"
      :custom-style="{
        marginTop: '48rpx',
        height: '88rpx',
        backgroundColor: 'rgba(31, 51, 89, 1)',
        color: 'rgba(255, 255, 255, 0.66)',
      }"
      hover-class="button-hover"
      type="primary"
      @click="login"
      >登录</u-button
    >
    <alerts />
  </view>
</template>

<script lang="ts">
import { Component, Ref, Watch } from 'vue-property-decorator';
//import { server } from '@/pages/login/server/model';
import Alerts from '@/components/alert/alerts.vue';
import { page } from '@/utils/page';
import { session } from '@/store/modules/session';
import { auth } from '@/store/modules/auth';
import { BasePage } from '@/components/base/page';
import { VForm } from 'vue/types/form';
import model from './model';
// mixin 引入示例目前用于弹窗自定义
@Component({
  components: { Alerts },
})
export default class LoginPage extends BasePage {
  model = model;
  /**
   * 访客权限
   */
  get guest() {
    return true;
  }
  /**
   * 表单引用
   */
  @Ref('form') readonly $form!: VForm;

  // get serverAddress(): string | null {
  //   return server.serverAddress;
  // }
  // 小数点保留
  username = '';
  @Watch('username')
  typeNum() {
    this.$nextTick(() => {
      this.username = this.username.replace(/^(\d+)\.(\d\d).*$/, '$1.$2');
    });
  }
  form = {
    username: '',
    password: '',
  };
  focustwo = false;

  rules = {
    username: [{ required: true, message: this.$t('message.PleaseInputUserName') }],
    password: [{ required: true, message: this.$t('message.PleaseInputPassword') }],
  };

  onLanguageSelect(index: number) {
    const languages = ['cn', 'en', 'ru'];
    this.$i18n.locale = languages[index];
  }
  onReady(): void {
    this.$form.setRules(this.rules);
    //this.customToast('版本号' + plus.runtime.version);
    //this.update();
    // console.log('image', this.image);
    // console.log('Version////', this.Version);
  }
  ///********版本号修改区域**********
  version = '0.0.194'; //正式版本号
  //version = '0.0.14'; //测试版本号
  //***************标志修改区域：是否是测试标志： false 正式版本； true 测试版本****************
  //isTest = true;

  compareVersion(version1: any, version2: any) {
    //如果version1 大 会返回1  &&&  如果version2 大 会返回 -1
    const newVersion1 = `${version1}`.split('.').length < 3 ? `${version1}`.concat('.0') : `${version1}`;
    const newVersion2 = `${version2}`.split('.').length < 3 ? `${version2}`.concat('.0') : `${version2}`;
    //计算版本号大小,转化大小
    function toNum(a) {
      const c = a.toString().split('.');
      const num_place = ['', '0', '00', '000', '0000'],
        r = num_place.reverse();
      for (let i = 0; i < c.length; i++) {
        const len = c[i].length;
        c[i] = r[len] + c[i];
      }
      return c.join('');
    }
    //检测版本号是否需要更新
    function checkPlugin(a: any, b: any) {
      const numA = toNum(a);
      const numB = toNum(b);
      return numA > numB ? 1 : numA < numB ? -1 : 0;
    }
    return checkPlugin(newVersion1, newVersion2);
  }
  //检查更新
  async checkupdate() {
    try {
      await this.model.checkupdate();
      console.log('3333333', this.model.checkversion);
      if (this.model.checkversion != undefined) {
        // const fileName = this.model.checkversion.fileName;
        // const isTestUpdate = fileName.includes('test'); // 检查fileName是否包含'test'
        const queryversion = this.model.checkversion.version;
        //const queryversion = this.checkversion.Version.match(/\d+\.\d+\.\d+/)[0];
        let versionNumber = this.compareVersion(this.version, queryversion); //this.version, queryversion
        if (versionNumber == -1) {
          // 版本更新提示
          uni.showModal({
            content: '新版本为：' + this.model.checkversion.version + ',' + '是否更新？',
            success: (res) => {
              if (res.confirm) {
                //确定执行下载
                let downloadApkUrl = this.model.checkversion.fileAddress;
                uni.showLoading({
                  title: '下载中',
                });
                ////////////////uni下载方法,
                uni.downloadFile({
                  url: downloadApkUrl,
                  success: (downloadResult) => {
                    uni.hideLoading();
                    if (downloadResult.statusCode == 200) {
                      //安装更新
                      plus.runtime.install(downloadResult.tempFilePath as any, { force: true }, function () {
                        //uni.showToast('更新成功，重启');
                        plus.runtime.restart();
                      });
                    }
                  },
                });
              } else if (res.cancel) {
                console.log();
                uni.navigateTo({
                  url: page.shouye,
                });
              }
            },
          });
          return;
        } else {
          uni.navigateTo({
            url: page.shouye,
          });
          // uni.showToast({
          //   title: '无更新内容',
          //   icon: 'none',
          // });
        }
      } else {
        uni.navigateTo({
          url: page.shouye,
        });
      }
    } catch (e) {
      console.log('error', e);
    }
  }
  //不同国家设置不同版本号
  onShow(): void {
    // console.log('......', server.serverAddress);
    // if (server.serverAddress.includes('https://eurmom.haier.net')) {
    //   //修改俄罗斯版本号
    //   this.Version = '1.1.41';
    // } else {
    //   this.Version = '1.0.59';
    // }
    // console.log('////', this.Version);
  }
  //console.log('......', server.serverAddress);
  EnterPress(e) {
    console.log(e);
    let inputs = document.getElementsByTagName('input');
    console.log('aaaaa', inputs);
    let inputlength = inputs.length;
    for (var i = 0; i < inputs.length; i++) {
      if (i == inputlength - 1) {
        inputs[0].focus();
        break;
      }
    }
  }
  onBarCodeConfirm() {
    this.focustwo = true;
    console.log('zhaobudao');
  }
  onBarCodeConfirmteo() {
    this.focustwo = false;
    //this.login();
  }
  async login() {
    const { username, password } = this.form;
    const loginResult = await session.login({
      username,
      password,
    });
    const loginResultuser: any = await session.getInfo({
      username,
    });
    console.log('123guguo', loginResultuser);
    uni.setStorageSync('userinfo', loginResultuser.user);
    // const aaa = {
    //   code: '1',
    //   access_token: 'wdwe2ewdwcds',
    //   msg: null,
    //   userId: '0ae08766df214803a098beb0ad55dbf1',
    //   loginName: 'admin9771',
    //   userName: 'admin9771',
    //   factoryCode: '9771',
    //   factory: true,
    //   list: [
    //     {
    //       loginName: null,
    //       warehouseCode: 'WH_FG_9771',
    //       warehouseName: 'WH_FG_9771',
    //       warehouseType: '2',
    //       regionCode: 'WR_FG_9771',
    //       regionDesc: 'WR_FG_9771',
    //       workareaCode: 'WA_FG_9771',
    //       workareaName: 'WA_FG_9771',
    //     },
    //     {
    //       loginName: null,
    //       warehouseCode: 'WH_RAW_9771',
    //       warehouseName: 'WH_RAW_9771',
    //       warehouseType: '1',
    //       regionCode: 'WR_RAW_9771',
    //       regionDesc: 'WR_RAW_9771',
    //       workareaCode: 'WA_RAW_9771',
    //       workareaName: 'WA_RAW_9771',
    //     },
    //   ],
    //   sapList: [
    //     {
    //       factoryRsapId: '9f995e9d431e4f21a58dcd01149d1213',
    //       factoryCode: '9771',
    //       sapFactoryCode: '9771',
    //       sapFactoryName: 'Thailand RF',
    //       createBy: 'WMS',
    //       gmtCreate: '2021-12-28T08:39:20.000+0000',
    //       lastModifiedBy: 'WMS',
    //       gmtModified: '2021-12-28T08:39:20.000+0000',
    //       activeFlag: '1',
    //       remark: null,
    //     },
    //   ],
    // };

    const bbb = loginResult.data;
    //const ccc = { data: loginResultuser };
    //console.log('123guguoccc', ccc);
    //const { access_token, userName, loginName } = aaa;
    const { access_token } = bbb;
    const poolNameList = loginResultuser.poolNameList;
    const userName = loginResultuser.user.userName;
    const loginName = username;
    const userId = loginResultuser.user.userId;
    const nickName = loginResultuser.user.nickName;
    const roles = loginResultuser.user.roles;
    const createBy = loginResultuser.user.createBy;
    const menuListold = loginResultuser.menuList;
    let menuList = [];
    for (let i = 1; i < menuListold.length; i++) {
      menuList.push({
        menuName: menuListold[i].menuName,
        path: menuListold[i].path,
        perms: menuListold[i].perms,
      });
    }
    session.setUser({
      access_token,
      userName,
      password,
      loginName,
      poolNameList,
      createBy,
      menuList,
      userId,
      nickName,
      roles,
    });
    auth.setVersion(this.version);
    uni.showToast({
      //icon: 'success',
      duration: 2000,
      title: this.$t('message.LoginSuccessful') as string,
      image: '/static/icons/icon-51.png',
    });
    this.checkupdate();
    // uni.navigateTo({
    //   url: page.shouye,
    // });
  }
}
</script>

<style lang="scss" scoped>
.page-login {
  background-size: cover;
  padding: 118rpx 60rpx 162rpx;
  min-height: 100%;
  color: #fff;

  .header {
    position: fixed;
    top: 36rpx;
    left: 0;
    right: 0;
    z-index: 99;
    display: flex;
    height: 88rpx;
    line-height: 88rpx;
    color: #fff;
    font-size: 34rpx;
    font-weight: 500;
    text-align: center;

    .title {
      flex: 3;
    }

    .left,
    .right {
      flex: 1;
    }

    .icon {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 88rpx;
      height: 88rpx;
    }
  }

  .logo {
    margin-top: 100rpx;
    display: flex;
    justify-content: center;
  }

  .form {
    margin-top: 104rpx;

    .form-item {
      height: 90rpx;
      border: 1px solid rgba(255, 255, 255, 0.5);
      border-radius: 90rpx;
      margin-top: 48rpx;
      padding: 0 28rpx;
    }
  }

  .i18n {
    margin-top: 42rpx;
    padding-right: 16rpx;
    display: flex;
    justify-content: flex-end;
    align-items: center;

    .dropdown-text {
      font-size: 24rpx;
      padding-right: 12rpx;
      color: rgba(255, 255, 255, 0.66);
    }

    .dropdown-icon {
      transition: all 0.3s ease-out;
    }

    .dropdown-icon-active {
      transform: rotate(180deg);
      transition: all 0.3s ease-out;
    }
  }

  .setting {
    margin-left: 60rpx;
  }
}

.button-hover {
  opacity: 0.7;
}
</style>
