<template>
  <view class="page-login" :style="{ backgroundImage: `url(${image.login.bg3})` }">
    <view class="header" :style="{ backgroundColor: `rgba(23, 83, 234, ${scrollTop / 100})` }">
      <view class="left"></view>
      <view class="title"></view>
      <view class="right">
        <u-icon class="setting" @click="uni.navigateTo({ url: page.login.server })" size="30" name="/static/icons/icon-47.png"></u-icon>
      </view>
    </view>
    <view class="logo">
      <u-image width="288rpx" height="85rpx" :src="image.global.logo1"></u-image>
      <span>V1.6</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
          v-model="form.username"
          :placeholder="$t('message.PleaseInputUserName')"
          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
          v-model="form.password"
          :placeholder="$t('message.PleaseInputPassword')"
          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' : '简体中文' }}</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"
      >{{ $t('message.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 { BasePage } from '@/components/base/page';
import { VForm } from 'vue/types/form';
import { Lang } from '@/i18n';
// mixin 引入示例目前用于弹窗自定义
// import { any } from 'lodash/fp';

@Component({
  components: { Alerts },
})
export default class LoginPage extends BasePage {
  /**
   * 访客权限
   */
  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: '',
  };

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

  i18nOptionsShow = false;

  i18nList = [
    {
      text: '简体中文',
      color: 'black',
    },
    {
      text: 'English',
      color: 'black',
    },
  ];

  onLanguageSelect(index: number) {
    const languages = ['cn', 'en'];
    this.$i18n.locale = languages[index];
  }

  onReady(): void {
    this.$form.setRules(this.rules);
    console.log('image', this.image);
  }
  Version = '1.0.0';
  async update() {
    await session.QueryVersion();
    if (this.Version != session.Version) {
      // 版本更新提示
      uni.showModal({
        content: this.$t('message.Tip1') as string,
        confirmText: this.$t('message.workArea_Confirm') as string,
        cancelText: this.$t('message.Cancel') as string,
        success: function (res) {
          if (res.confirm) {
            //确定执行下载
            let downloadApkUrl = session.url;
            ////////////////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();
                  });
                  // uni.showModal({
                  //   //content: '更新更新',
                  //   content: this.$t('message.Tip2') as string,
                  //   confirmText: this.$t('message.restart') as string,
                  //   cancelText: this.$t('message.Cancel') as string,
                  //   success: function (res) {
                  //     if (res.confirm == true) {
                  //       plus.runtime.install(downloadResult.tempFilePath, { force: true }, function (res) {
                  //         //uni.showToast('更新成功，重启');
                  //         plus.runtime.restart();
                  //       });
                  //     }
                  //   },
                  // });
                }
              },
            });
            ///////////////////// plus方法
            // plus.downloader
            //   .createDownload(downloadApkUrl, {}, function (d, status) {
            //    uni.showModal({
            //      content: status,
            //    });
            //     if (status == 200) {
            //     uni.showModal({
            //         title: '',
            //         content: this.$t('message.Tip2') as string,
            //         confirmText: this.$t('message.restart') as string,
            //         cancelText: this.$t('message.Cancel') as string,
            //         success: function (res) {
            //           if (res.confirm == true) {
            //             plus.runtime.install(plus.io.convertLocalFileSystemURL(d.filename), { force: true }, function (res) {
            //               //uni.showToast('更新成功，重启');
            //               plus.runtime.restart();
            //             });
            //           }
            //         },
            //       });
            //     } else {
            //       console.log('Download failed: ' + status);
            //     }
            //   })
            //   .start();
            // dtask.start();
            /////////////////plus 方法
          } else if (res.cancel) {
            //console.log('用户点击取消');
          }
        },
      });
    }
  }
  /////////////////无用代码无用代码
  // 更新应用资源
  async installApk(path) {
    plus.runtime.install(
      path,
      {},
      function () {
        console.log('安装文件成功！');
        plus.runtime.restart();
      },
      function (e) {
        uni.hideLoading();
        console.log(JSON.stringify(e)); //这里！e一直为null，path路径为_downloads/apk/10.apk
        uni.showToast({
          title: '安装失败',
          mask: false,
          duration: 1500,
        });
      },
    );
  }
  /* 安装失败 */
  failed() {
    uni.showToast({
      icon: 'none',
      mask: true,
      title: '更新失败！请退出重试或向工作人员反映',
      duration: 1500,
    });
    setTimeout(function () {
      plus.runtime.quit();
    }, 1500);
  }
  ////////////////////////////
  login(): void {
    this.$form.validate(async (valid: boolean) => {
      if (valid) {
        if (!server.isServerAddressSet) {
          await uni.showToast({
            icon: 'none',
            title: this.$t('message.Tip') as string,
          });
          setTimeout(() => {
            uni.navigateTo({ url: page.login.server });
          }, 2000);
        } else {
          const { username, password } = this.form;
          const loginResult = await session.login({
            username,
            password,
            lang: this.$i18n.locale as Lang,
          });
          const { code, factoryCode, list, loginName, msg, userId, userName } = loginResult;
          session.setUser({
            code,
            factoryCode,
            loginName,
            list,
            msg,
            userId,
            userName,
            lang: this.$i18n.locale as Lang,
          });
          uni.showToast({
            icon: 'success',
            title: this.$t('message.LoginSuccessful') as string,
          });
          //debugger;
          this.update();
          uni.navigateTo({
            url: page.login.area,
          });
        }
      }
    });
  }
}
</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>
