<template>
  <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" size="large">
    <!-- <el-form-item prop="account">
      <div class="flx w-full">
        <el-select
          v-model="loginForm.account"
          class="flx-1 account-form"
          :placeholder="$t('sys.login.accountPlaceholder')"
          filterable
          @blur="handeSelAccount"
        >
          <el-option v-for="item in accounts" :key="item" :value="item" :label="item"></el-option>
          <template #prefix>
            <div class="flx-center" @click.stop="getAccountFunc">
              <el-icon v-if="loadingAccount"><Loading /></el-icon>
              <i
                v-else
                class="iconfont account-icon"
                :class="accounts.length ? 'iconlink-01 success' : 'iconlink-broken-01 fail'"
              ></i>
            </div>
          </template>
        </el-select>
      </div>
    </el-form-item> -->
    <el-form-item prop="username">
      <el-autocomplete
        class="flx-1"
        ref="FormUseridRef"
        v-model="loginForm.usercode"
        :fetch-suggestions="querySearch"
        highlight-first-item
        :placeholder="$t('sys.login.useridPlaceholder')"
        clearable
        @select="handleSelUser"
        @keydown.enter="toFocus(loginFormRef)"
      >
        <template #prefix>
          <el-icon class="el-input__icon"><user /></el-icon>
        </template>
        <template #default="{ item }">
          <div class="flx-justify-between">
            <div class="flx-1">{{ item.usercode }}</div>
            <div>
              <!-- <span class="text-disable">{{ item.account }}</span> -->
              <el-tooltip effect="dark" :content="$t('sys.login.delAccount')" placement="right" :show-after="200">
                <i class="iconfont iconDelete_light ml-8" @click.stop="toDelAccount(item)"></i>
              </el-tooltip>
            </div>
          </div>
        </template>
      </el-autocomplete>
    </el-form-item>
    <el-form-item prop="password" style="margin-bottom: 0">
      <el-input
        type="password"
        ref="FormPWRef"
        v-model="loginForm.psw"
        :placeholder="$t('sys.login.passwordPlaceholder')"
        show-password
        autocomplete="new-password"
        @keydown.enter="login(loginFormRef)"
      >
        <template #prefix>
          <el-icon class="el-input__icon"><lock /></el-icon>
        </template>
      </el-input>
    </el-form-item>
  </el-form>
  <!-- <DragVerify ref="DragVerifyRef" @success="login(loginFormRef)" /> -->
  <div class="flx-justify-between mt-8">
    <div></div>
    <el-checkbox size="large" v-model="rememberCheckbox" :label="$t('sys.login.rememberMe')" />
  </div>
  <div class="login-btn flx-justify-between mt-8">
    <el-button class="flx-1" :icon="UserFilled" @click="login(loginFormRef)" type="primary" :loading="loading" size="large">
      {{ $t("sys.login.loginButton") }}
    </el-button>
  </div>
  <!-- <div class="flx-center mt-12">
    <el-button text round size="large" :loading="loading" @click="gotoQrcodeLogin">
      <template #icon>
        <i class="iconfont iconqr-code-02"></i>
      </template>
      {{ $t("sys.login.qrSignInFormTitle") }}
    </el-button>
  </div> -->
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick, onUnmounted, computed } from "vue";
import { useRouter } from "vue-router";
// import { HOME_URL } from "@/config";
// import { getTimeState } from "@/utils";
import { Login } from "@/api/interface";
// import { ElNotification } from "element-plus";
// import { loginApi, loginApiTest } from "@/api/modules/login";
import { useUserStore } from "@/stores/modules/user";
import { useTabsStore } from "@/stores/modules/tabs";
import { useKeepAliveStore } from "@/stores/modules/keepAlive";
// import { initDynamicRouter } from "@/routers/modules/dynamicRouter";
import { Guide, Message, Setting, UserFilled, Loading, Lock, User } from "@element-plus/icons-vue";
import { ElMessage, ElNotification, type ElForm } from "element-plus";
import { useI18n } from "vue-i18n";
import { getTimeState } from "@/utils";
import { storeToRefs } from "pinia";
import { useGlobalStore } from "@/stores/modules/global";
// import DragVerify from "./DragVerify.vue";

const AppName = import.meta.env.VITE_GLOB_APP_COMPANY + import.meta.env.VITE_GLOB_APP_TITLE;
// const router = useRouter();
const userStore = useUserStore();
const { assemblySize } = useGlobalStore();
const { accounts, historyAccount } = storeToRefs(userStore);
// const tabsStore = useTabsStore();
// const keepAliveStore = useKeepAliveStore();
const { t } = useI18n();
const rememberCheckbox = ref(true);

// const DragVerifyRef = ref();
const FormUseridRef = ref();
const FormPWRef = ref();

type FormInstance = InstanceType<typeof ElForm>;
const loginFormRef = ref<FormInstance>();
const loginRules = reactive({
  usercode: [{ required: true, message: "请输入用户名", trigger: "blur" }]
  // password: [{ required: true, message: "请输入密码", trigger: "blur" }]
});

const loadingAccount = ref(false);
const loading = ref(false);
const loginForm = reactive<Login.ReqLoginForm>({
  // account: "",
  usercode: "",
  psw: ""
  // clientType: 30,
  // typeName: "Website"
});

const emit = defineEmits(["gotoQrcode", "loginSuccess"]);

const currentHistoryAccount = computed(() => {
  return historyAccount?.value;
});
const querySearch = (queryString: string, cb: any) => {
  if (!historyAccount?.value?.length) return cb([]);
  let results = currentHistoryAccount.value;
  if (queryString) {
    let _results = historyAccount?.value.filter(item => item.usercode.toLowerCase().indexOf(queryString.toLowerCase()) >= 0);
    if (_results.length == 1 && _results[0].usercode != queryString) {
      results = _results;
    }
  }
  cb(results);
};

const checkAccountFunc = (item: any) => {
  // let accountIndex = accounts.value.findIndex(_itm => _itm === item.account);

  // if (accountIndex > -1) {
  // loginForm.account = item.account;
  loginForm.usercode = item.usercode;
  return true;
  // } else {
  //   return false;
  // }
};

const handeSelAccount = () => {
  setTimeout(() => {
    FormUseridRef.value.inputRef.input.focus();
  }, 200);
};
const handleSelUser = (item: any) => {
  if (!checkAccountFunc(item)) {
    ElMessage.warning(t("sys.login.noAccount"));
  }
  setTimeout(() => {
    FormPWRef.value.focus();
  }, 200);
};

const toFocus = (formEl: FormInstance | undefined) => {
  setTimeout(() => {
    FormPWRef.value.focus();
    FormPWRef.value.select();
  }, 200);
};

// login
const login = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async valid => {
    if (!valid) return;
    // console.log("login DragVerifyRef.value.confirmSuccess :>> ", DragVerifyRef.value.confirmSuccess);
    // if (!DragVerifyRef.value.confirmSuccess) {
    //   ElMessage.error(t("sys.login.dragVerify"));
    //   return;
    // }
    loading.value = true;
    try {
      // await userStore.login({ ...loginForm }, userStore.getUserInfo).then(
      console.log("loginForm :>> ", loginForm);
      await userStore.login({ ...loginForm }).then(
        res => {
          console.log("login data  !!!res :>> ", res);
          ElNotification({
            title: getTimeState(t),
            message: t("sys.login.welcome") + " " + AppName,
            type: "success",
            duration: 3000
          });

          // 记住我
          if (rememberCheckbox.value) {
            userStore.setHistoryAccount({ usercode: loginForm.usercode });
          }

          emit("loginSuccess");
        },
        () => {
          ElMessage.error(t("sys.errorLog.login"));
          FormPWRef.value && FormPWRef.value.select();
        }
      );
      // } catch (data) {
      //   ElMessage.error(t("sys.errorLog.login"));
    } finally {
      loading.value = false;
    }
  });
};

// const gotoQrcodeLogin = () => {
//   emit("gotoQrcode");
// };

/**
 * @description 获取账套
 */
// const getAccountFunc = () => {
//   loadingAccount.value = true;
//   userStore.getToken().then(() => {
//     loadingAccount.value = false;
//     if (historyAccount?.value?.length) {
//       checkAccountFunc(historyAccount.value[0]);
//     }
//   });
// };

/**
 * @description 删除用户名记录
 */
const toDelAccount = (item: any) => {
  userStore.delAccountFunc(item);
};

onMounted(() => {
  // 监听 enter 事件（调用登录）
  // document.onkeydown = (e: KeyboardEvent) => {
  //   // e = (window.event as KeyboardEvent) || e;
  //   // if (e.code === "Enter" || e.code === "enter" || e.code === "NumpadEnter") {
  //   //   if (loading.value) return;
  //   //   if (loginForm.account && loginForm.userid && loginForm.password) {
  //   //     login(loginFormRef.value);
  //   //   }
  //   // }
  // };
  // getAccountFunc();
});

onUnmounted(() => {
  document.onkeydown = null;
});
</script>

<style scoped lang="scss">
@import "../index.scss";

.account-form {
  .account-icon {
    font-size: 14px;
    height: 14px;
    line-height: 14px;

    &.success {
      color: $color-polar-green-7;
    }
    &.fail {
      color: $color-dust-red-7;
    }
  }
}
</style>
