<template>
  <div class="login-container">
    <div class="login-wrap">
      <div class="login-title">
        <img src="@/assets/images/wms.png" alt="">
      </div>
      <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" class="login-form" auto-complete="on"
        label-position="left">
        <el-form-item prop="userId">
          <el-input ref="userId" v-model="loginForm.userId" placeholder="用户名" name="username" type="text" tabindex="1"
            auto-complete="on" :prefix-icon="User" size="default" />
        </el-form-item>

        <el-form-item prop="passWord">
          <el-input ref="passwordRef" v-model="loginForm.passWord" placeholder="密码" name="passWord" tabindex="2"
            auto-complete="on" :prefix-icon="Lock" @keyup.enter="handleLogin" show-password size="default" />
        </el-form-item>

        <el-form-item prop="orgNo">
          <el-select size="default" v-model="loginForm.orgNo" placeholder="组织" default-first-option>
            <el-option v-for="item in state.orgList" :key="item.ERPFACTORY" :label="item.DESCRIPTION"
              :value="item.ERPFACTORY" />
          </el-select>
        </el-form-item>
        <el-checkbox v-model="state.remeberPwd">记住密码</el-checkbox>
        <div class="login-btn">
          <el-button size="default" :loading="loading" type="primary" @click.prevent="handleLogin">{{ $t('login.login')
            }}
          </el-button>
        </div>

      </el-form>
    </div>
    <!--  切换语言  -->
    <div class="login-change-lang">
      <lang-select />
    </div>
  </div>
</template>

<script setup lang="ts">
import { getRSAPublic, loginApi, getORG } from '@/api/auth';
import { onMounted, reactive, ref, toRefs, watch, nextTick, getCurrentInstance } from 'vue';

// 组件依赖,全局或局部
import { ElForm, ElInput } from 'element-plus';
import { User, Lock } from '@element-plus/icons-vue'
import router from '@/router';
import LangSelect from '@/components/LangSelect/index.vue';

// 状态管理依赖
import useStore from '@/store';

// API依赖
import { useRoute } from 'vue-router';
import { JSEncrypt } from "jsencrypt";

const route = useRoute();
const { user, app } = useStore();
const { proxy }: any = getCurrentInstance();

const loginFormRef = ref(ElForm);
const passwordRef = ref(ElInput);

const state = reactive({
  redirect: '',
  remeberPwd: false,
  orgList:[] as any,
  loginForm: {
    userId: '',
    passWord: '',
    orgNo: ''
  },
  loginRules: {
    userId: [{ required: true, trigger: 'blur', message: '请输入用户名' }],
    passWord: [{ required: true, trigger: 'blur', message: '请输入密码' }],
    orgNo: [{ required: true, trigger: 'change', message: '请选择组织' }]
  },
  loading: false,
  rsa: ''
});

const {
  orgList,
  loginForm,
  loginRules,
  loading,
  rsa
} = toRefs(state);

// 监听
watch(
  route,
  () => {
    const query = route.query;
    if (query) {
      state.redirect = query.redirect as string;
    }
  },
  {
    immediate: true
  }
);

onMounted(() => {
  if(localStorage.getItem('remeberPwd')) {
    let remeberPwd = JSON.parse(localStorage.getItem('remeberPwd'));
    state.loginForm.userId = remeberPwd.userId;
    state.loginForm.passWord = remeberPwd.passWord;
    state.loginForm.orgNo = remeberPwd.orgNo;
    state.remeberPwd = remeberPwd.remeberPwd
  }
  
  window.onresize = () => {

  };
  getORGFn()
  //getRSA();
});
function getRSA() {
  getRSAPublic().then((res: any) => {
    state.rsa = res.data;
  }).catch(() => { });
}
function validatePassword(rule: any, value: any, callback: any) {
  if (value.length < 6) {
    callback(new Error('密码不能少于6位'));
  } else {
    callback();
  }
}

function getORGFn() {
  getORG({ orgNo: null}).then((res: any) => {
    console.log(res)
    state.orgList = res.resultObj;
  }).catch(() => { });
}

/**
 *  登录处理
 */

function handleLogin() {
  loginFormRef.value.validate((valid: boolean) => {
    console.log(111,valid)
    if (valid) {
      if(state.remeberPwd) {
        let remeberPwd = {...state.loginForm,remeberPwd: state.remeberPwd}
        localStorage.setItem('remeberPwd',JSON.stringify(remeberPwd))
      }else {
        localStorage.removeItem('remeberPwd');
      }
      localStorage.setItem('orgNo',JSON.stringify(state.loginForm.orgNo))
      let form = { params : {
          userId: state.loginForm.userId,
          password: state.loginForm.passWord,
          orgNo: state.loginForm.orgNo,
          siteName : "SDK"
        }
      };
      localStorage.removeItem('ut');
      localStorage.removeItem('userId');
      localStorage.removeItem('userName');
      // 1、store请求
      user.login(form)
        .then((res) => {
          console.log(res)
          router.push({ path: state.redirect || '/', force: true });
        }).catch(res => {
          // 请求失败时的处理逻辑
          console.log(res);
        });
    } else {
      state.loading = false;
      return false;
    }
  });
}

function getUrl(arr: any): any {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i].relObj.url) {
      return arr[i].relObj.url;
    } else {
      return getUrl(arr[i].children);
    }
  }
}

</script>

<style lang="scss" scoped>
.login-container {
  width: 100%;
  height: 100%;
  background-image: url("../../assets/images/login_bg.png");
  background-size: 100%;
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  position: relative;

  .login-wrap {
    position: absolute;
    top: 19%;
    right: 12.5%;
    background: white;
    box-shadow: 0 2px 30px 0 rgba(22, 42, 76, 0.1);
    border-radius: 8px;
    height: 450px;
    width: 400px;
    padding: 40px 40px 40px 40px;
    box-sizing: border-box;

    .login-title {
      text-align: center;
      margin-bottom: 38px;

      img {
        width: 120px;
        margin: 0 auto;
      }
    }

    .login-btn {
      .el-button {
        width: 320px;
        height: 40px;
        margin-top: 5px;
        font-size: 16px;
      }
    }

    .el-form-item {
      margin-bottom: 40px;
    }
  }

  .login-change-lang {
    position: absolute;
    right: 20px;
    top: 20px;
  }
}
</style>
