<script setup lang="ts">
import {ElForm, ElFormItem, ElButton, ElRow} from "element-plus";
import {onMounted, reactive, ref} from "vue";
import MessageUtils from "@/utils/MessageUtils.ts";
import StringUtils from "@/utils/StringUtils.ts";
import {Lock, User} from "@element-plus/icons-vue";
import type {ILoginUser} from "@/interface/page/user/ILoginUser.ts";
import type {AppServeDataResponse} from "@/interface/api/AppServeDataResponse.ts";
import type {ILoginResponse} from "@/interface/page/user/ILoginResponse.ts";
import {AppServeResponseCodeEnum} from "@/constant/enums/AppServeResponseCodeEnum.ts";
import {CookieUtils} from "@/utils/CookieUtils.ts";
import UserApi from "@/api/user.ts";
import router from "@/router";
import {tabsStore} from "@/stores/tabs.ts";
import {menuStore} from "@/stores/menu.ts";
import {userStore} from "@/stores/user.ts";
import type {IThisUserInfo} from "@/interface/app/IThisUserInfo.ts";
import LanguageSwitch from "@/components/custom/LanguageSwitch.vue";
import {useI18n} from "vue-i18n";
import {appStore} from "@/stores/app.ts";
import {ConfigApi} from "@/api/config.ts";

const loginUser: ILoginUser = reactive<ILoginUser>({ userId: '', password: ''});
const loginUserId = ref();
const tabsStoreInstance = tabsStore();
const menuStoreInstance = menuStore();
const userStoreInstance = userStore();
const appStoreInstance = appStore();
const { t } = useI18n();

onMounted(() => {
  resetData(); // 重置所有信息
  loginUserId.value.focus();
  queryCustomerName(); // 查询客户名称
})

// 登录
const login = () => {
  if(StringUtils.isNullOrEmpty(loginUser.userId) || StringUtils.isNullOrEmpty(loginUser.password)) {
    MessageUtils.errMessageBox('请填写您的账号或者密码', '信息缺失');
    return;
  }
  loginUser.password = StringUtils.getPwdMd5(loginUser.password);
  const loading = MessageUtils.loading('正在登录');
  UserApi.login(loginUser).then((res) => {
    const responseString = JSON.stringify(res.data);
    const response: AppServeDataResponse<ILoginResponse> = JSON.parse(responseString) as AppServeDataResponse<ILoginResponse>;
    if(response && response.code == AppServeResponseCodeEnum.SUCCESS && response.data != undefined) {
      const cookieUtils = new CookieUtils();
      cookieUtils.clear();// 先清除所有 cookie
      cookieUtils.setItem('wcsToken', response.data.token ?? '', 8);
      const user: IThisUserInfo = {
        userId: loginUser.userId,
      }
      userStoreInstance.setUserInfo(user); // 设置用户信息
      router.push({name:'home'});
      MessageUtils.successMessage('登录成功');
      return;
    }
    MessageUtils.warningMessageBox(response.msg, '失败');
  }).catch(() => {}).finally(() => {
    loginUser.password = '';
    loading.close();
  })
}

// 第三方登录
const loginWithOther = () => {
  MessageUtils.warningMessageBox('您的系统不支持第三方登录', '警告');
}
// 激活软件
const active = () => {
  MessageUtils.successMessageBox('您的系统已经永久激活', '欢迎使用');
}
// 打印服务
const printServe = () => {
  router.push({name:'printCodePage'});
};
// 运行主页
const home = () => {
  router.push({name:'homePage'});
}



// 重置
const resetData = () => {
  tabsStoreInstance.resetAppTabs();
  menuStoreInstance.resetSelectMenu();
};
// 查询客户名称
const queryCustomerName = () => {
  ConfigApi.getConfig('CUSTOMER_NAME').then((res) => {
    const responseString = JSON.stringify(res.data);
    const response: AppServeDataResponse<string> = JSON.parse(responseString) as AppServeDataResponse<string>;
    if(response && response.code == AppServeResponseCodeEnum.SUCCESS && response.data != undefined) {
      appStoreInstance.setCustomerName(response.data);
      return;
    }
    MessageUtils.errMessage('查询客户名称失败:' + response.msg);
  }).catch(() => {})
}

</script>

<template>
  <div style="background-image: url('/image/app/warehouseBackground.png'); float: left; left: 0; top: 0; width: 100vw; height: 100vh">
    <div class="loginDiv">
      <el-row>
        <h2 style="text-align: center; width: 100%; margin-top: 10px; color: #b4b0b0">{{t('app.applicationName')}}</h2>
      </el-row>
      <el-row>
        <h5 style="text-align: center; width: 100%; margin-top: 5px; color: #b4b0b0">{{appStoreInstance.getCustomerName()}}</h5>
      </el-row>
<!--      <el-row>-->
<!--        <h5 style="text-align: center; width: 100%; margin-top: 5px; color: #b4b0b0">{{t('login.login')}}</h5>-->
<!--      </el-row>-->
      <el-row style="width: 100%; margin: auto">
        <el-form :model=loginUser label-width="auto" label-position="top" style="margin: 10px auto;" @submit.prevent="login">
          <el-form-item :label= "t('login.username') + '：'" style="width: 400px;margin-bottom: 5px;">
            <el-input v-model="loginUser.userId" ref="loginUserId">
              <template #prefix>
                <el-icon class="el-input__icon"><User /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item :label= "t('login.password') + '：'"  style="width: 400px;">
            <el-input v-model="loginUser.password" show-password>
              <template #prefix>
                <el-icon class="el-input__icon"><Lock /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="语言（language）：" style="width: 400px;">
            <LanguageSwitch style="width: 400px"/>
          </el-form-item>
          <el-form-item style="margin-bottom: 5px;">
            <el-button native-type="submit" type="primary" style="width: 100%; margin-top: 10px">{{t('login.login')}}</el-button>
          </el-form-item>
          <el-form-item style="margin-bottom: 5px;">
            <el-button-group style="width: 100%;">
              <el-button type="warning" style="width: 50%" @click="loginWithOther()" disabled>{{t('login.loginWithOther')}}</el-button>
              <el-button type="info" style="width: 50%" @click="printServe()">{{t('login.codePrinter')}}</el-button>
            </el-button-group>
          </el-form-item>
          <el-form-item>
            <el-button type="success" style="width: 100%;" @click="home()">{{t('login.runningMessage')}}</el-button>
          </el-form-item>
        </el-form>
      </el-row>
      <el-link @click="active" style="color: cornflowerblue; position: absolute; right: 10px; bottom: 10px">{{t('app.version') + "：V2.2501.1(bate)" }}</el-link>
    </div>
  </div>
</template>

<style scoped>
.loginDiv {
  border: 1px solid rgba(204, 204, 204, 0.21);
  border-radius: 10px;
  width: 500px;
  height: 480px;
  margin-left: calc(50vw - 250px);
  margin-top: calc(15vh);
  background-color: rgba(255, 255, 255, 0.1);
}

:deep(.el-form-item__label) {
  color: #b4b0b0;
}

</style>