<template>
  <div id="index">
    <el-row>
      <el-col :span="24" class="main animate__animated animate__backInRight">
        <el-col :span="24" class="one w_1200">
          <el-col :span="24" class="one_1"> {{ siteInfo.zhTitle }}</el-col>
          <el-col :span="24" class="one_2">
            <div class="login">
              <el-col :span="24" class="login_1"> 平台用户登录 </el-col>
              <el-col :span="24" class="login_2">
                <el-col :span="24" class="type">
                  <el-radio-group v-model="login_type">
                    <el-radio-button label="1">个人用户</el-radio-button>
                    <el-radio-button label="2">管理用户</el-radio-button>
                  </el-radio-group>
                </el-col>
                <el-col :span="24" class="form">
                  <el-form ref="formRef" :model="form" :rules="rules" label-width="auto">
                    <el-form-item label="" prop="account">
                      <el-input v-model="form.account" placeholder="请输入登录账号">
                        <template #prefix>
                          <el-icon><User /></el-icon>
                        </template>
                      </el-input>
                    </el-form-item>
                    <el-form-item label="" prop="password">
                      <el-input v-model="form.password" type="password" show-password placeholder="请输入登录密码">
                        <template #prefix>
                          <el-icon><Unlock /></el-icon>
                        </template>
                      </el-input>
                    </el-form-item>
                    <el-form-item label="" prop="type" v-if="login_type == '1'">
                      <el-select v-model="form.type" clearable placeholder="请选择用户类型" style="width: 100%">
                        <el-option v-for="t in typeList" :key="t.value" :label="t.label" :value="t.value" />
                      </el-select>
                    </el-form-item>
                    <el-form-item label="" prop="code">
                      <el-input v-model="form.code" placeholder="请输入验证码">
                        <template #prefix>
                          <el-icon><Key /></el-icon>
                        </template>
                        <template #append>
                          <component :is="validcode" @toCode="toCode"></component>
                        </template>
                      </el-input>
                    </el-form-item>
                    <el-col :span="24" class="btn">
                      <el-button type="primary" @click="toSave(formRef)">提交登录</el-button>
                      <el-button type="danger" @click="toRegister" v-if="login_type == '1'">账号注册</el-button>
                    </el-col>
                  </el-form>
                </el-col>
              </el-col>
            </div>
          </el-col>
        </el-col>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
// 基础
import { siteInfo } from '@common/src/layout/site';
import validcode from '@common/src/components/ValidCode.vue';
import type { Ref } from 'vue';
import { onMounted, ref, reactive } from 'vue';
import { useRouter } from 'vue-router';
import type { FormInstance, FormRules } from 'element-plus';
import { ElMessage } from 'element-plus';
// 接口
import { AdminStore } from '@common/src/stores/admins/admin'; // 管理员
import { PersonalStore } from '@common/src/stores/admins/personal'; // 个人
import { CompanyStore } from '@common/src/stores/admins/company'; // 企业
import { ExpertStore } from '@common/src/stores/admins/expert'; // 专家
import { TokenStore } from '@common/src/stores/user/token'; // 专家
import type { IQueryResult } from '@/util/types.util';
const adminAxios = AdminStore();
const personalAxios = PersonalStore();
const companyAxios = CompanyStore();
const expertAxiso = ExpertStore();
const tokenAxiso = TokenStore();

// 路由
const router = useRouter();

// 登录类型
const login_type: Ref<any> = ref('1');
// 表单
const formRef = ref<FormInstance>();
const form: Ref<any> = ref({});
const rules = reactive<FormRules>({
  account: [{ required: true, message: '请输入登录账号', trigger: 'blur' }],
  password: [{ required: true, message: '请输入账号密码', trigger: 'blur' }],
  type: [{ required: true, message: '请选择用户类型', trigger: 'change' }],
  code: [{ required: false, message: '请输入验证码', trigger: 'blur' }]
});
// 验证码
const code: Ref<any> = ref('');

// 字典表
const typeList: Ref<any> = ref([
  { label: '个人用户', value: '4' },
  { label: '企业用户', value: '5' },
  { label: '专家用户', value: '6' }
]);

// 请求
onMounted(async () => {});
// 验证码
const toCode = (e) => {
  code.value = e;
};
// 提交登录
const toSave = async (formEl: any) => {
  if (!formEl) return;
  await formEl.validate((valid) => {
    if (valid) {
      // if (form.value.code.toLowerCase() !== code.value.toLowerCase()) {
      //   ElMessage({ message: '验证码错误', type: 'error' });
      //   return;
      // }
      toLogin(form.value);
    } else {
      console.log('error submit!');
    }
  });
};
// 登录
const toLogin = async (e) => {
  delete e.code;
  // 个人（个人，企业，专家）1=>4,5,6
  // 管理（超级，管理员，机构，业务）2=>0,1,2,3
  let res: IQueryResult;
  let loginType = login_type.value;
  let type = e.type;
  delete e.type;
  if (loginType == '1') {
    if (type == '4') res = await personalAxios.login(e);
    if (type == '5') res = await companyAxios.login(e);
    if (type == '6') res = await expertAxiso.login(e);
  } else if (loginType == '2') res = await adminAxios.login(e);
  if (res.errcode == '0') {
    ElMessage({ message: '登录成功', type: 'success' });
    localStorage.setItem('token', `${res.data}`);
    // 解析token跳转页面
    tokenView();
  } else {
    ElMessage({ message: `${res.errmsg}`, type: 'error' });
  }
};
const tokenView = async () => {
  let res: IQueryResult = await tokenAxiso.tokenInfo();
  if (res.errcode == '0') {
    let user = res.data as any;
    let env = import.meta.env.VITE_APP_ENV;
    let path = '';
    if (env == 'development') {
      if (user.type == '0' || user.type == '1' || user.type == '2' || user.type == '3') path = 'http://localhost:8003/zkzxadmin';
      else if (user.type == '4' || user.type == '5' || user.type == '6') path = 'http://localhost:8002/zkzxuser';
    } else {
      if (user.type == '0' || user.type == '1' || user.type == '2' || user.type == '3') path = '/zkzxadmin';
      else if (user.type == '4' || user.type == '5' || user.type == '6') path = '/zkzxuser';
    }
    window.open(path);
  }
};
// 账号注册
const toRegister = () => {
  router.push({ path: '/register' });
};
</script>
<style scoped lang="scss">
.main {
  display: flex;
  flex-direction: column;
  width: 100vw;
  height: 100vh;
  overflow: hidden;
  background: url('@/assets/bglogin.jpg');
  background-repeat: no-repeat;
  background-size: 100% 100%;
  .one {
    .one_1 {
      text-align: center;
      color: #ffffff;
      font-size: 40px;
      font-family: monospace;
      margin: 5% 0 40px 0;
    }
    .one_2 {
      text-align: center;
      display: flex;
      justify-content: center;
      .login {
        width: 500px;
        height: 500px;
        background-color: #ffffff;
        border-radius: 5px;
        padding: 10px;
        .login_1 {
          text-align: center;
          margin: 30px 0;
          font-size: 30px;
          color: #409eff;
          font-family: cursive;
          font-weight: 700;
        }
        .login_2 {
          .type {
            margin: 0 0 10px 0;
          }
        }
      }
    }
  }
}
:deep(.el-input-group__append, .el-input-group__prepend) {
  padding: 0;
}
</style>
