<template>
  <div>
    <div class="absolute inset-0">
      <img src="/assets/images/auth/bg-gradient.png" alt="image" class="h-full w-full object-cover" />
    </div>

    <div class="relative flex items-center justify-center bg-[url(/assets/images/auth/map.png)] bg-cover bg-center bg-no-repeat dark:bg-[#060818] sm:px-16">
      <img src="/assets/images/auth/coming-soon-object3.png" alt="image" class="absolute right-0 top-0 h-[300px]" />

      <div
        class="relative w-full max-w-[870px] rounded-md bg-[linear-gradient(45deg,#fff9f9_0%,rgba(255,255,255,0)_25%,rgba(255,255,255,0)_75%,_#fff9f9_100%)] p-2 dark:bg-[linear-gradient(52.22deg,#0E1726_0%,rgba(14,23,38,0)_18.66%,rgba(14,23,38,0)_51.04%,rgba(14,23,38,0)_80.07%,#0E1726_100%)]"
      >
        <div class="relative flex flex-col justify-center rounded-md bg-white/60 backdrop-blur-lg dark:bg-black/50 px-6 lg:min-h-[758px] py-20">
          <div class="absolute top-6 start-6">
            <el-button type="plain" text @click="typeLogin"> PlatForm </el-button>
          </div>
          <div class="absolute top-6 end-6">
            <div class="dropdown">
              <Popper :placement="store.state.rtlClass === 'rtl' ? 'bottom-start' : 'bottom-end'" offsetDistance="8">
                <button
                  type="button"
                  class="flex items-center gap-2.5 rounded-lg border border-white-dark/30 bg-white px-2 py-1.5 text-white-dark hover:border-primary hover:text-primary dark:bg-black"
                >
                  <div>
                    <img :src="currentFlag" alt="image" class="h-5 w-5 rounded-full object-cover" />
                  </div>
                  <div class="text-base font-bold uppercase">{{ store.state.locale }}</div>
                  <span class="shrink-0">
                    <icon-caret-down />
                  </span>
                </button>
                <template #content="{ close }">
                  <ul class="!px-2 text-dark dark:text-white-dark grid grid-cols-2 gap-2 font-semibold dark:text-white-light/90 w-[280px]">
                    <template v-for="item in store.state.languageList" :key="item.code">
                      <li>
                        <button
                          type="button"
                          class="w-full hover:text-primary"
                          :class="{ 'bg-primary/10 text-primary': i18n.locale === item.code }"
                          @click="changeLanguage(item), close()"
                        >
                          <img class="w-5 h-5 object-cover rounded-full" :src="`/assets/images/flags/${item.code.toUpperCase()}.svg`" alt="" />
                          <span class="ltr:ml-3 rtl:mr-3">{{ item.name }}</span>
                        </button>
                      </li>
                    </template>
                  </ul>
                </template>
              </Popper>
            </div>
          </div>
          <div class="mx-auto w-full max-w-[440px]">
            <div class="mb-10">
              <h1 class="text-3xl font-extrabold uppercase !leading-snug text-primary md:text-4xl">Company Sign in</h1>
                 <!-- <p class="text-base font-bold leading-normal text-white-dark">欢迎登录V3StudioApp</p> -->
                  <div>
                    <span class="text-base font-bold leading-normal text-white-dark" @click="tabSwitch('acc','password')" :class="switchType=='acc'?'!text-primary':''">账号密码登录</span>
                    <span class="text-base font-bold leading-normal text-white-dark">|</span>
                    <span class="text-base font-bold leading-normal text-white-dark" @click="tabSwitch('phone','phone')" :class="switchType=='phone'?'!text-primary':''">手机号登录</span>
                  </div>
            </div>
            <!--  <form class="space-y-5 dark:text-white" @submit.prevent="router.push('/')">
                            <div>
                                <label for="Email">请输入账号</label>
                                <div class="relative text-white-dark">
                                    <input id="Email" type="text" placeholder="请输入账号"
                                        class="form-input ps-10 placeholder:text-white-dark" />
                                    <span class="absolute start-4 top-1/2 -translate-y-1/2">
                                        <icon-mail :fill="true" />
                                    </span>
                                </div>
                            </div>
                            <div>
                                <label for="Password">请输入密码</label>
                                <div class="relative text-white-dark">
                                    <input id="Password" type="password" placeholder="请输入密码"
                                        class="form-input ps-10 placeholder:text-white-dark" />
                                    <span class="absolute start-4 top-1/2 -translate-y-1/2">
                                        <icon-lock-dots :fill="true" />
                                    </span>
                                </div>
                            </div>
                            <div>
                                <label class="flex cursor-pointer items-center">
                                    <input type="checkbox" class="form-checkbox bg-white dark:bg-black" />
                                    <span class="text-white-dark">记住密码</span>
                                </label>
                            </div>
                            <button type="submit"
                                class="btn btn-gradient !mt-6 w-full border-0 uppercase shadow-[0_10px_20px_-10px_rgba(67,97,238,0.44)]">
                                登录
                            </button>
                        </form> -->
            <!-- <el-button @click="goHome">测试</el-button> -->
            <el-form :model="loginForm" :rules="loginRules" v-if="switchType=='acc'" ref="loginFormRef" class="login-input" label-width="120px">
              <el-form-item label="公司名称:" prop="company_id">
                <!-- <el-select
                  v-model="loginForm.company_id"
                  filterable
                  clearable
                  :placeholder="$t('company_name')"
                  style="width: 240px"
                  @input="getInput"
                  @change="getCompany"
                >
                  <el-option v-for="item in options" :key="item.id" :label="item.name" :value="item.id" />
                </el-select> -->
                <el-input v-model="loginForm.company_name" :placeholder="$t('company_name')" autofocus clearable>
                  <template v-slot:prefix>
                    <svg-icon class="el-input__icon" icon-class="user" />
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item label="账号:" prop="username">
                <el-input v-model="loginForm.username" :placeholder="$t('username')" autofocus clearable>
                  <template v-slot:prefix>
                    <svg-icon class="el-input__icon" icon-class="user" />
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item label="密  码:" prop="password">
                <el-input
                  v-model="loginForm.password"
                  type="password"
                  autocomplete="off"
                  :placeholder="$t('password')"
                  :minlength="6"
                  :maxlength="20"
                  clearable
                >
                  <template v-slot:prefix>
                    <svg-icon class="el-input__icon" icon-class="password" />
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item label="验证码:" prop="validcode" v-if="validateInFO.validator_type === 'IMAGE'">
                <el-input v-model="loginForm.validcode" :placeholder="$t('validcode')" :maxlength="4" clearable>
                  <template v-slot:append>
                    <img class="login-validcode-img h-8 w-full p-0" :src="validcodeImg" @click="changeValidcode" />
                  </template>
                </el-input>
              </el-form-item>
              <div v-else-if="validateInFO.validator_type === 'ALIYUN'" style="margin-bottom: 20px">
                <div id="pc-valid" class="nc-container"></div>
              </div>
              <el-form-item>
                <el-button type="primary" :loading="loading" :disabled="!accountAfsSuccess" class="btn" @click="submitLogin(loginFormRef)">
                  {{ $t('logIn') }}
                </el-button>
              </el-form-item>
            </el-form>
            <el-form :model="loginForm" :rules="loginRules" v-if="switchType=='phone'" ref="loginFormRef" class="login-input" label-width="120px">
              <el-form-item label="公司名称:" prop="company_id">
                <el-input v-model="loginForm.company_name" :placeholder="$t('company_name')" autofocus clearable>
                  <template v-slot:prefix>
                    <svg-icon class="el-input__icon" icon-class="user" />
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item label="手机号:" prop="phone">
                <el-input v-model="loginForm.phone" placeholder="请输入手机号" autofocus clearable>
                  <template v-slot:prefix>
                    <svg-icon class="el-input__icon" icon-class="user" />
                  </template>
                </el-input>
              </el-form-item>
             <!--  <el-form-item label="密  码:" prop="password">
                <el-input
                  v-model="loginForm.password"
                  type="password"
                  autocomplete="off"
                  :placeholder="$t('password')"
                  :minlength="6"
                  :maxlength="20"
                  clearable
                >
                  <template v-slot:prefix>
                    <svg-icon class="el-input__icon" icon-class="password" />
                  </template>
                </el-input>v-if="validateInFO.validator_type === 'IMAGE'"
              </el-form-item> -->
              <el-form-item label="验证码:" prop="check_code" >
                <el-input v-model="loginForm.check_code" :placeholder="$t('validcode')" :maxlength="6" clearable>
                  <template v-slot:append>
                    <el-button v-if="showloginCode" type="primary" @click="getCode" class="w-40">获取验证码</el-button>
                   <!--  <img class="login-validcode-img h-8 w-full p-0" :src="validcodeImg" @click="changeValidcode" /> -->
                  </template>
                </el-input>
              </el-form-item>
              <!-- <div v-else-if="validateInFO.validator_type === 'ALIYUN'" style="margin-bottom: 20px">
                <div id="pc-valid" class="nc-container"></div>
              </div> -->
              <el-form-item>
                <el-button type="primary" :loading="loading" :disabled="!accountAfsSuccess" class="btn" @click="submitLogin(loginFormRef)">
                  {{ $t('logIn') }}
                </el-button>
              </el-form-item>
            </el-form>
            <!-- 新用户注册账号--暂不开放 -->
            <div class="relative my-7 text-center md:mb-9">
                            <span class="absolute inset-x-0 top-1/2 h-px w-full -translate-y-1/2 bg-white-light dark:bg-white-dark"></span>
                            <span class="relative bg-white px-2 font-bold uppercase text-white-dark dark:bg-dark dark:text-white-light">or</span>
                        </div>

            <div class="text-center dark:text-white">
              新用户请注册 ?
              <a href="javascript:;" @click="singnup" class="uppercase text-primary underline transition hover:text-black dark:hover:text-white">
                注册
              </a>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { computed, onMounted, reactive, ref,Ref } from 'vue';

import { useI18n } from 'vue-i18n';
import appSetting from '@/app-setting';
import { useStore } from 'vuex';
import { useRouter, useRoute } from 'vue-router';
import { useMeta } from '@/composables/use-meta';
import Storage from '@/utils/storage';
import * as API_Company from '@/api/company';
import * as API_common from '@/api/common';
import { v4 as uuidv4 } from 'uuid';
import AliyunAfs from '@/composables/AliyunAfs';
import { ElMessage, FormInstance } from 'element-plus';
import app from '@/stores/modules/app';

const loading: any = ref(false);

const options: any = ref([]);

const switchType=ref('acc')
const tabSwitch=(val,row)=>{
  switchType.value=val
  loginForm.login_type=row
}

const loginForm = reactive({
  username: '',
  password: '',
  scene: 'LOGIN',
  login_type:"password",
  validcode: '',
  company_name: '',
  type: 'com',
  phone:"",
  check_code: '',
  check_code_key: '',
});

const { t } = useI18n();
const loginRules = reactive({
  username: [{ required: true, message: t('val_username'), trigger: 'blur' }],
  password: [{ required: true, message: t('val_password'), trigger: 'blur' }],
  validcode: [{ required: true, message: t('val_validcode'), trigger: 'blur' }],
  company_name: [{ required: true, message: t('company_name'), trigger: 'blur' }],
  phone: [{ required: true, message: "请输入手机号", trigger: 'blur' }],
  check_code: [{ required: true, message: "请输入验证码", trigger: 'blur' }],
});
// 验证信息
const validateInFO: any = ref({});
let validcodeImg: any = ref('');
let uuid: any = ref(Storage.getItem('admin_uuid'));
// 阿里云验证条实例
let afs: any = ref(null);
// 当滑动验证成功之后返回的参数
const afsParam: any = ref({
  c_sessionid: '',
  sig: '',
  nc_token: '',
});
// 阿里云滑动验证是否通过 && 如果不是 阿里云验证则直接设置为 true
const accountAfsSuccess: any = ref(false);
// 是否为加盟商登录
const is_franchise: any = ref(false);
const loginFormRef = ref<any>();

useMeta({ title: 'Login Boxed' });
const router = useRouter();
const route = useRoute();
const store = useStore();
// multi language
const i18n = reactive(useI18n());
const changeLanguage = (item: any) => {
  i18n.locale = item.code;
  appSetting.toggleLanguage(item);
};
const currentFlag = computed(() => {
  return `/assets/images/flags/${i18n.locale.toUpperCase()}.svg`;
});

const typeLogin = () => {
  router.push({ path: '/platformLogin' })
 /*  router.push({ path: '/platformLogin' }); */
};

/* 查询公司 */
const getCompany = (value: any) => {};
const getInput = (val) => {
  searchText = val.data;
  API_common.getCompany(val.data).then((res) => {
    options.value = res;
  });
};
let searchText = ref('');
const companyList = () => {
  API_common.getCompany(searchText.value).then((res) => {
    options.value = res;
  });
};

onMounted(() => {
  //companyList();
  const uuids = Storage.getItem('admin_uuid');
  if (uuids) {
    uuid = uuids;
  } else {
    const _uuid = uuidv4();
    uuid = _uuid;
    Storage.setItem('admin_uuid', _uuid, { expires: 30 });
  }
  changeValidcode();
  API_common.getValidator().then((res) => {
    validateInFO.value = res;
    const { validator_type, aliyun_afs } = res;
    if (validator_type === 'ALIYUN') {
      //afs = new AliyunAfs('#pc-valid', aliyun_afs.scene, aliyun_afs.app_key, initCaptcha)
      afs.init();
    } else {
      accountAfsSuccess.value = true;
    }
  });
  // companyList()
});

/** 阿里云滑动验证 通过后的回调函数 **/
const initCaptcha = (data) => {
  afsParam.c_sessionid = data.csessionid;
  afsParam.sig = data.sig;
  afsParam.nc_token = data.nc_token;
  accountAfsSuccess.value = true;
};

/** 更换图片验证码 */
const changeValidcode = () => {
  validcodeImg.value = API_common.getValidateCodeUrl('LOGIN', uuid);
};
const MixinClone = (obj) => {
  return JSON.parse(JSON.stringify(obj));
};

/** 登录处理 */
const dispatchLoginAction = (params) => {
  loading.value = true;
  return new Promise((resolve, reject) => {
    store
      .dispatch('loginAction', params)
      .then((res: any) => {
        loading.value = false;
        if (res) {
          try {
            const WS = new WebSocket(res.access_token);
            // 使用 provide/inject 或其他方式在 Vue 3 中共享 WebSocket 实例
            app.provide('websocket', WS);
          } catch (error) {
          }
        }
        const forward = route.query.forward;
        let query = JSON.parse(JSON.stringify(route.query));
        delete query.forward;
        if (params.type == 'com') {
          store.dispatch('toggleSuperMenu', 'compan');
        } else {
          store.dispatch('toggleSuperMenu', 'super');
        }
        router.push({ path: 'dashboard', query }).catch(() => {}); //forward ||
      })
      .catch(() => {
        loading.value = false;
        reject();
      });
  });
};

const submitLogin = (formEl: FormInstance | undefined) => {
  if (!accountAfsSuccess) return;
  if (!afs) {
    const params = MixinClone(loginForm);
    params.c_sessionid = afsParam.c_sessionid;
    params.sig = afsParam.sig;
    params.nc_token = afsParam.nc_token;
    delete params.validcode;
    delete params.scene;
    dispatchLoginAction(params).catch(() => {
      accountAfsSuccess.value = false;
    });
  } else {
    loginFormRef.value.validate((valid: boolean) => {
      if (valid) {
        const params = MixinClone(loginForm);
        params.uuid = uuid;
        params.captcha = params.validcode;
        delete params.validcode;
        dispatchLoginAction(params).catch(() => {
          changeValidcode();
        });
      } else {
        // 使用 Element Plus 的消息提示
        ElMessage.error(t('val_form'));
        return false;
      }
    });
  }
};
const goHome = () => {
  router.push({ path: 'dashboard' }).catch(() => {});
};

const singnup=()=>{
  router.push({ path: '/boxed-signup' }).catch(() => {});
}
const showloginCode = ref(true);
const loginPhoneForm=ref({
  phone:"",
  check_code: '',
  check_code_key: '',
})
/* 获取手机号验证码 */
const getCode = () => {
  if (loginForm.phone === '') {
    ElMessage.error('请先输入手机号！');
    return;
  }
  API_Company.loginGetCheckCode(loginForm.phone).then((res) => {
    ElMessage.success('验证码已发送，五分钟后失效！');
    loginForm.check_code_key = res;
    /* const TIME_COUNT = 60; */
    /* if (!timer.value) {
      showloginCode.value = false;
      count.value = TIME_COUNT;
      timer.value = window.setInterval(() => {
        if (count.value > 0 && count.value <= TIME_COUNT) {
          count.value -= 1;
        } else {
          showloginCode.value = true;
          clearInterval(timer.value as number);
          timer.value = null;
        }
      }, 1000);
    } */
  });
};
</script>
<style>
.el-input-group__append {
  padding: 0;
}
</style>
