<template>
  <view class="wrap">
    <!-- 首页背景图片 -->
    <!-- <image src="/static/aidex/login/login-bg.png" class="logo"></image> -->
    <view class="logo">
		<view class="EnglishFont">
		  ZETA CLOUD
		</view>
    </view>
    <image src="/static/aidex/login/bg-logo1.png" class="center-logo"></image>

    <!--首页用户密码输入框  -->

    <view class="EnglishFont">
      Welcome to Zetatech！
    </view>

    <u-select v-model="langShow" :list="Langlist" @confirm="changeLanguage"></u-select>

<!-- 	<u-radio-group v-model="StationValue" @change="radioGroupChange" active-color="#009C77">
      <u-radio @change="radioChange" v-for="(item, index) in $t('homePage.home.stationType')" :key="index" :name="item.name">
        {{ item.name }}
      </u-radio>
    </u-radio-group> -->

    <view class="user-card">
      <view class="list">

        <view class="zhanghao">
          {{ $t('homePage.home.account') }}
        </view>
        <view class="list-call-user">
          <input class="u-input" type="text" v-model="username" maxlength="32" :placeholder="$t('homePage.home.placeAccount')" />
          <image class="u-icon-delete" src="/static/aidex/login/user-delete.png" @click="clearUser" style="z-index: 0;">
          </image>
        </view>

        <view class="zhanghao">
          {{ $t('homePage.home.password') }}
        </view>
        <view class="list-call-password">

          <input class="u-input" type="text" v-model="password" maxlength="32" :placeholder="$t('homePage.home.placePassword')" :password="!showPassword" />
          <image class="u-icon-right" :src="'/static/aidex/login/eye_' +
            (showPassword ? 'open' : 'close') +
            '.png'" style="z-index: infinity;" @click="showPass()"></image>
        </view>
      </view>
    </view>

    <!-- 登录按钮 -->

    <view class="button" @click="submit('app')"><text>{{ $t('homePage.home.login') }}</text></view>

   
    <view class="shouquan">
      <u-checkbox v-model="checked" shape="circle" active-color="#009C77"></u-checkbox>
      <view class="yonghuxieyi">
        {{ $t('homePage.home.ydty') }}
        <span class="xieyi" @click="openMsg">《{{ $t('homePage.home.yhxy') }}》</span>
        {{ $t('homePage.home.and') }}
        <span class="xieyi" @click="openMsg">《{{ $t('homePage.home.yszc') }}》</span>
      </view>
    </view>

    <view style="margin-top: 60rpx;display: flex;align-items: center;">
      <view class="Line">

      </view>
      <view style="margin-left:10rpx;margin-right: 10rpx;color: grey;">
        {{ $t('homePage.home.lang') }}
      </view>
      <view class="Line2">

      </view>
    </view>

    <view style="margin-top: 10rpx;display: flex;align-items: center;" @click="langShow = true">
      <u-icon name="/static/aidex/images/lang.png" size="50" color="#009c77" style="margin-right: 10rpx;"></u-icon>
      <view style="color: #009c77">{{ langValue === 'zh_CN' ? 'ZH' : 'EN' }}</view>
    </view>
		 <!-- 新增游客登录按钮 -->
    <view class="guest-button" @click="guestLogin">
      <text>{{ $t('homePage.home.guestLogin') }}</text>
    </view>

    <messageModel v-if="showMsg" @submit="agree" @quit="quit" />
  </view>
</template>
<script>
import {
  encryptPsd,
  JSEncryptData
} from "@/common/common.js"
import messageModel from './components/dialog.vue'
import config from '@/common/config.js'
import { Langlist } from '@/common/lang.js'
export default {
  components: { messageModel },
  data () {
    return {
		Langlist:Langlist,
      phoneNo: "",
      username: "",
      password: "",
      loginType: "app",
      langShow: false,
      showPassword: false,
      remember: true,
      isValidCodeLogin: false,
      validCode: "",
      imgValidCodeSrc: null,
      list: [{
        name: "用户名",
      },
      {
        name: "手机号",
      },
      ],
      current: 0,
      activeColor: "#007aff",
      show: false,
      showDialog: false,
      newFileData: {},
      newVersion: null,
      isShowProgress: false,
      progress: 0,
      innerVer: null,
      versionCode: null,
      message: '',
      checked: false,
      showMsg: false,
      Stationlist: this.$t('homePage.home.stationType'),
      // u-radio-group的v-model绑定的值如果设置为某个radio的name，就会被默认选中
      StationValue: 'en_US',
    }
  },
  onLoad () {
    this.username = uni.getStorageSync('username')
    this.password = uni.getStorageSync('password')
  },
  computed: {
    userName () {
      return this.vuex_username
    },
    userPassword () {
      return this.vuex_password
    },
    langValue () {
      return this.vuex_language
    },
    language () {
      return this.vuex_language
    },
  },
  watch: {
    language: {
      immediate: true,
      deep: true,
      handler (val) {
        if (val === 'zh_CN') {
          if (this.StationValue === 'China Station' || this.StationValue === '') {
            this.StationValue = '中国站'
          } else if (this.StationValue === 'Overseas Station') {
            this.StationValue = '海外站'
          }
        }else{
           if (this.StationValue === '中国站' || this.StationValue === '') {
            this.StationValue = 'China Station'
          } else if (this.StationValue === '海外站') {
            this.StationValue = 'Overseas Station'
          }
        }
      }
    },
    StationValue: {
      immediate: true,
      deep: true,
      async handler (val) {
        // console.log(123,this.vuex_stationValue)
        this.StationValue = this.vuex_stationValue
        //  this.$u.vuex("vuex_stationValue", val);
        if (val === '海外站' || val === 'Overseas Station') {
          this.$u.http.setConfig({
            // baseUrl: 'http://1.95.170.86:8002/api',
			baseUrl: 'https://zetatech.zzkj-cloud.com/api'
          });
        } else if (val === '中国站' || val === 'China Station') {
          this.$u.http.setConfig({
			// baseUrl: 'http://1.95.170.86:8002/api'
			baseUrl: 'https://zetatech.zzkj-cloud.com/api'
			// baseUrl: 'https://zzkj-cloud.com/api'
          });
        }
        const res = await this.$u.api.GetLanguageConfig('zh')
        const res2 = await this.$u.api.GetLanguageConfig('en')
        const res3 = await this.$u.api.GetLanguageConfig('fr')
        const res4 = await this.$u.api.GetLanguageConfig('es')
        const res5 = await this.$u.api.GetLanguageConfig('ar')
        const res6 = await this.$u.api.GetLanguageConfig('de')
        const res7 = await this.$u.api.GetLanguageConfig('pl')
        const result = JSON.parse(res.data[0].content)
        const result2 = JSON.parse(res2.data[0].content)
        const result3 = JSON.parse(res3.data[0].content)
        const result4 = JSON.parse(res4.data[0].content)
        const result5 = JSON.parse(res5.data[0].content)
        const result6 = JSON.parse(res6.data[0].content)
        const result7 = JSON.parse(res7.data[0].content)
        this.$i18n.mergeLocaleMessage('en_US', result2)        //添加英文
        this.$i18n.mergeLocaleMessage('zh_CN', result)        //添加中文
        this.$i18n.mergeLocaleMessage('fr_FR', result3)        //添加法语
        this.$i18n.mergeLocaleMessage('es_ES', result4)        //添加西班牙语
        this.$i18n.mergeLocaleMessage('ar_EG', result5)        //添加阿拉伯语
        this.$i18n.mergeLocaleMessage('de_DE', result6)        //添加德语
        this.$i18n.mergeLocaleMessage('pl_PL', result7)        //添加波兰语
      }
    }
  },
  methods: {
    radioGroupChange () {

    },
		// 新增游客登录方法
    guestLogin() {
      const encryptData = encryptPsd('666666')
        const publicData = JSEncryptData(
          encryptData.iv,
          encryptData.key
        )
        const params = {
          username: 'zzdemo',
          password: encryptData.password,
          type: "app",
          aesKey: publicData.keyData,
          iv: publicData.ivData,
        }

        this.$u.api
          .login(params)
          .then((res) => {
            this.$u.vuex("vuex_token", res.data.accessToken)
            this.getMenuList()
            this.$u.vuex("vuex_iv", encryptData.iv)
            this.$u.vuex("vuex_psdkey", encryptData.key)
            this.getAllDict()
            this.getStationByUser()
            this.getProvinceStation()
            uni.setStorageSync('username', this.username)
            uni.setStorageSync('password', this.password)
            const timer = setTimeout(() => {
              uni.reLaunch({
                url: "/pages/tabbar/dashboard"
              })
              clearTimeout(timer)
            }, 500)
            if (res.isValidCodeLogin) {
              this.isValidCodeLogin = true
              this.refreshImgValidCode()
            }
          })
    },
    openMsg () {
      this.showMsg = true
    },
    agree () {
      this.checked = true
      this.showMsg = false
    },
    quit () {
      this.showMsg = false
      this.checked = false
    },
    changeLanguage (val) {
      this.$u.vuex("vuex_language", val[0].value);
	  this.$u.vuex("vuex_configLang", val[0].prop);
      this.$i18n.locale = val[0].value
    },
    uploadFile () {
      this.isShowProgress = true;
      const downloadTask = uni.downloadFile({

        url: this.newFileData.url,
        success: (downloadResult) => {
          if (downloadResult.statusCode === 200) {
            plus.runtime.openFile(downloadResult.tempFilePath);

          }
        }
      });
      downloadTask.onProgressUpdate((res) => {
        if (res.progress > 0) {
          this.isShowProgress = true;
        }

        this.progress = res.progress;
        if (res.totalBytesWritten === res.totalBytesExpectedToWrite) {
          this.isShowProgress = false;
        }
      })

    },
    showPass () {
      this.showPassword = !this.showPassword
    },
    zfbLogin () {
      this.loginType = "currentPhone"
    },
    qiehuanLogin () {
      this.loginType = "other"
    },
    onClickItem (index) {
      this.current = index
    },
    refreshImgValidCode (e) {
      if (this.vuex_token == "") {
        this.$u.api.index().then((res) => {
          this.imgValidCodeSrc =
            this.vuex_config.baseUrl +
            "/validCode?__sid=" +
            res.sessionid +
            "&t=" +
            new Date().getTime()
        })
      } else {
        this.imgValidCodeSrc =
          this.vuex_config.baseUrl +
          "/validCode?__sid=" +
          this.vuex_token +
          "&t=" +
          new Date().getTime()
      }
      this.validCode = ""
    },
    nextStep () {
      //验证码登录下一步
      uni.showLoading({
        title: "正在获取验证码",
        mask: true,
      })
      this.$u.api
        .sendCode({
          phoneNo: this.phoneNo,
          validCodeType: "2",
        })
        .then((res) => {
          if (res.code == "200") {
            setTimeout(() => {
              uni.hideLoading()
              uni.navigateTo({
                url: "/pages/sys/login/code?phoneNo=" + this.phoneNo,
              })
            }, 500)
          } else {
            this.$u.toast(res.msg)
            uni.hideLoading()
            setTimeout(() => {
              uni.navigateTo({
                url: "/pages/sys/login/code?phoneNo=" + this.phoneNo,
              })
            }, 500)
          }
        })
    },
    submit (loginType) {
      if (this.checked) {
        this.$u.vuex("vuex_username", this.username)
        this.$u.vuex("vuex_password", this.password)
        if (this.username.length == 0) {
          this.$u.toast(this.$t('homePage.home.placeAccount'))
          return
        }
        if (this.password.length == 0) {
          this.$u.toast(this.$t('homePage.home.placePassword'))
          return
        }
        const encryptData = encryptPsd(this.password)
        const publicData = JSEncryptData(
          encryptData.iv,
          encryptData.key
        )
        const params = {
          username: this.username.trim(),
          password: encryptData.password,
          type: "app",
          aesKey: publicData.keyData,
          iv: publicData.ivData,
        }
        this.$u.api
          .login(params)
          .then((res) => {    
            this.$u.vuex("vuex_token", res.data.accessToken)
            this.getMenuList()
            this.$u.vuex("vuex_iv", encryptData.iv)
            this.$u.vuex("vuex_psdkey", encryptData.key)
            this.getAllDict()
            this.getStationByUser()
            this.getProvinceStation()
            uni.setStorageSync('username', this.username)
            uni.setStorageSync('password', this.password)
            const timer = setTimeout(() => {
              uni.reLaunch({
                url: "/pages/tabbar/dashboard"
              })
              clearTimeout(timer)
            }, 500)
            if (res.isValidCodeLogin) {
              this.isValidCodeLogin = true
              this.refreshImgValidCode()
            }
          })
      } else {
        this.$u.toast(this.$t('homePage.home.checkFirst'))
      }

    },
    getAllDict () {
      this.$u.api.getAllDict().then((res) => {
        const {
          data
        } = res
        const dicts = {}
        data.forEach((element) => {
          dicts[element.type] = element.list
        })
        this.$u.vuex("vuex_dicts", dicts)
      })
    },
    getMenuList () {
      this.$u.api.getMenuList().then((res) => {
        this.$u.vuex("vuex_menu", res.data.menuList)
        this.$u.vuex("vuex_user", res.data)
        this.$u.vuex("vuex_permissions", res.data.powerList)
      })
    },
    getStationByUser () {
      this.$u.api.getStationByUser().then((res) => {
        this.$u.vuex("vuex_station", res.data)
      })
    },
    getProvinceStation () {
      this.$u.api.alarm.GetNewStationlist().then((res) => {
        this.$u.vuex("vuex_provinceStation", res.data.list)
        this.$u.vuex("vuex_currentStation", res.data.list[0].list[0].list[0])
		this.$u.vuex("vuex_inverterFlag", res.data.list[0].list[0].list[0].inverterFlag)
      })
    },
    wxLogin (res) {
      this.$u.toast(this.$t('homePage.home.noLogin'))
    },
    qqLogin () {
      this.$u.toast("QQ 登录")
    },
    // 清空用户输入框
    clearUser () {
      this.username = ""
    },
    // 打开模态框
    mobileReg () {
      this.show = true
    },
    // 关闭模态框
    closeCard () {
      this.show = false
    },
    async radioChange (val) {
      this.$u.vuex("vuex_stationValue", val)
      console.log(val);
      // if (val === '海外站' || )
      // this.stationType = this.$t('homePage.home.stationType')[0].name

      // config.baseUrl = 'http://192.168.100.244/api'
      // 更新请求拦截器中的baseUrl配置
      // this.$u.http.setConfig({
      //   baseUrl: 'http://192.168.100.244/api'
      // });
      // console.log(val, config);
      // const res = await this.$u.api.GetLanguageConfig('zh')
      // const res2 = await this.$u.api.GetLanguageConfig('en')
      // const result = JSON.parse(res.data[0].content)
      // const result2 = JSON.parse(res2.data[0].content)
      // this.$i18n.mergeLocaleMessage('en_US', result2)        //添加英文
      // this.$i18n.mergeLocaleMessage('zh_CN', result)        //添加中文
    }
  },
};
</script>
<style lang="scss">
@import "index.scss";

.progress-container {
  position: fixed;
  top: 0;
  left: 0;
  z-index: 99;
  background: rgba(0, 0, 0, 0.2);
  width: 750rpx;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;

  .progress-box {
    background: #ffffff;
    border-radius: 20rpx;
    padding: 30rpx;

    .text {
      margin-bottom: 20rpx;
    }
  }
}

.Line {
  width: 80rpx;
  height: 1px;
  background: linear-gradient(
    -244deg,
    rgba(165, 165, 165, 0) 0%,
    rgba(165, 165, 165, 1) 50%
  );
}

.Line2 {
  width: 80rpx;
  height: 1px;
  background: linear-gradient(
    244deg,
    rgba(165, 165, 165, 0) 0%,
    rgba(165, 165, 165, 1) 50%
  );
}

.shouquan {
  width: 100%;
  display: flex;
  align-items: center;
  margin-top: 10rpx;
  padding: 0rpx 75rpx 0px 75rpx;

  .yonghuxieyi {
    font-size: 28rpx;
    color: #383f43;

    .xieyi {
      color: #009c77;
    }
  }
}

/* 新增游客登录按钮样式 */
.guest-button {
  width: 600rpx;
  height: 80rpx;
  line-height: 80rpx;
  text-align: center;
  margin: 30rpx auto 0;
  color: #009C77;
  font-size: 30rpx;
}
</style>