<script setup lang="ts">
import Motion from "./utils/motion";
import { useRouter } from "vue-router";
import type { FormInstance } from "element-plus";
import { ElMessage } from "element-plus";
import { storageSession } from "@pureadmin/utils";
import { ref, reactive, watch, computed } from "vue";
import { useUserStoreHook } from "/@/store/modules/user";
import { resType } from "/@/store/modules/types";
import { bg, currentWeek } from "./utils/static";
import { ReImageVerify } from "/@/components/ReImageVerify";
import { useRenderIcon } from "/@/components/ReIcon/src/hooks";
import { initRouter } from "/@/router/utils";
import { loadEnv } from "@build/index";
import logo from "/@/assets/logo.png";
import { REGEXP_PWD } from "./utils/rule"
import { isMobile } from "/@/utils/validate";


defineOptions({ name: "Login" });


const imgCode = ref("");
const router = useRouter();
const loading = ref(false);
const checked = ref(false);
const ruleFormRef = ref<FormInstance>();
const codePassword = ref("")
const currentPage = computed(() => {
  return useUserStoreHook().currentPage;
});

const { loginByUsername } = useUserStoreHook();
// 15501067031
// wugg1234

const { VITE_IS_PROD, WECHAT_URL, BACK_URL } = loadEnv();

const ruleForm = reactive({
  username: "",
  password: "",
  verifyCode: ""
});

const onLogin = async (formEl: FormInstance | undefined) => {
  loading.value = true;
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      loginByUsername(ruleForm).then(async (res: resType) => {
        const { code, message, data } = res;
        if (code === 0) {
          const { userinfo, token, role_level } = data ?? {};
          const { nickname } = userinfo ?? {};
          storageSession.setItem("info", { username: nickname ?? "", accessToken: token ?? "" });

          if(role_level == 3){
            loading.value = false
            ElMessage.warning('供应商端账号不能登录该系统')
            return
          }

          initRouter()
            .then((list: any) => {
                ElMessage.success("登录成功");
                router.push("/");
            })
            .catch(err => {
              if (err === 10000) {
                router.push("/welcome?error=roleExcption");
              }
            });
        } else if (code > 100 && code < 200) {
          loading.value = false;
        } else {
          loading.value = false;
          ElMessage.error(message ?? "");
        }
      });
    } else {
      loading.value = false;
      return fields;
    }
  });
};

const loginRules = reactive(<FormRules>{
  username: [
    {
      validator(_, value, callback) {
        if (!value) {
          callback(new Error("请输入手机号"));
        } else if (!isMobile(value)) {
          callback(new Error("手机号格式不正确"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ],
  password: [
    {
      validator: (rule, value, callback) => {
        if (value === "") {
          callback(new Error("请输入密码"));
        } else if (!REGEXP_PWD.test(value)) {
          callback(new Error("密码格式应为6-18位数字、字母的组合"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ],
  verifyCode: [
    {
      validator: (rule, value, callback) => {
        if (value === "") {
          callback(new Error("请输入验证码"));
        } else if (String(codePassword.value) !== String(value)) {
          callback(new Error("请输入正确的验证码"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ]
});

function toWindowPath() {
  window.open("https://beian.miit.gov.cn/");
}

const ua = window.navigator.userAgent.toLowerCase();
const isWechatEnv = ua.match(/micromessenger/i) == 'micromessenger' && window.location.search !== "?from=authorization";

if (isWechatEnv) {
  window.location.href = `http://rep.test241.wanyuhengtong.com?back=http://webcx.test241.wanyuhengtong.com&name=采销结算平台`
}


watch(imgCode, value => {
  useUserStoreHook().SET_VERIFYCODE(value);
});

watch(ruleForm, () => {
  if (ruleForm.username.length > 11) {
    ruleForm.username = ruleForm.username.slice(0, 11);
  }
});
</script>

<template>
  <img :src="bg" class="wave" />
  <div class="login-container">
    <div class="img">
      <component :is="currentWeek" />
    </div>
    <div class="login-box">
      <div class="login-form">
        <!-- <avatar class="avatar" /> -->
        <div class="flex w-full items-center justify-center">
          <img :src="logo" style="height: 100px" />
        </div>

        <Motion>
          <!-- <h2>{{ title }}</h2> -->
          <h2>票务系统</h2>
        </Motion>

        <el-form v-if="currentPage === 0" ref="ruleFormRef" :model="ruleForm" :rules="loginRules" size="large"
          @keyup.enter="onLogin(ruleFormRef)">
          <Motion :delay="100">
            <el-form-item prop="username">
              <el-input clearable v-model="ruleForm.username" placeholder="账号" :prefix-icon="useRenderIcon('user')" />
            </el-form-item>
          </Motion>

          <Motion :delay="150">
            <el-form-item prop="password">
              <el-input clearable show-password v-model="ruleForm.password" placeholder="密码"
                :prefix-icon="useRenderIcon('lock')" />
            </el-form-item>
          </Motion>

          <Motion :delay="200">
            <el-form-item prop="verifyCode">
              <el-input clearable v-model="ruleForm.verifyCode" placeholder="验证码" :prefix-icon="useRenderIcon('ri:shield-keyhole-line', { online: true })
                ">
                <template v-slot:append>
                  <ReImageVerify v-model:code="imgCode" v-model:password="codePassword" />
                </template>
              </el-input>
            </el-form-item>
          </Motion>

          <Motion :delay="250">
            <el-form-item>
              <div class="w-full h-20px flex justify-between items-center">
                <el-checkbox v-model="checked">记住密码</el-checkbox>
              </div>
              <el-button class="w-full mt-4" size="default" type="primary" :loading="loading"
                @click="onLogin(ruleFormRef)">
                登录
              </el-button>
            </el-form-item>

            <el-form-item v-if="VITE_IS_PROD">
              <div class="w-full flex justify-center">
                <ElButton link @click="toWindowPath">京ICP备2022033072号-1</ElButton>
              </div>
            </el-form-item>
          </Motion>

          <!-- <Motion :delay="300">
            <el-form-item>
              <div class="w-full h-20px flex justify-between items-center">
                <el-button
                  v-for="(item, index) in operates"
                  :key="index"
                  class="w-full mt-4"
                  size="default"
                  @click="onHandle(index + 1)"
                >
                  {{ item.title }}
                </el-button>
              </div>
            </el-form-item>
          </Motion> -->
        </el-form>
      </div>
    </div>
  </div>
</template>

<style scoped>
@import url("/@/style/login.css");
</style>

<style lang="scss" scoped>
:deep(.el-input-group__append, .el-input-group__prepend) {
  padding: 0;
}

.link-btn {
  position: fixed;
  bottom: 100px;
  left: 50%;
  border: none;
}
</style>
