<template>
  <div class="login-layer">
    <el-dialog
      v-model="loginShow"
      width="560"
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :before-close="handleClose"
    >
      <div style="text-align: center">
        <el-form
          class="panel dialoglogin"
          ref="formEl"
          :model="form"
          :rules="rules"
          @submit.stop
        >
          <h2 class="title1">现场勘查平面图</h2>
          <div class="title2">支持户型图、平面图绘制</div>
          <el-form-item class="panel-form-item" prop="account">
            <p class="err-info">{{ verification.phone }}</p>
            <el-input
              :maxlength="11"
              v-model.trim="form.account"
              placeholder="账号"
              @keydown.enter="submitClick"
            ></el-input>
          </el-form-item>
          <el-form-item class="panel-form-item" prop="password">
            <p class="err-info">{{ verification.psw }}</p>
            <el-input
              v-model="form.password"
              :maxlength="16"
              placeholder="密码"
              :type="flag ? 'password' : 'text'"
              @keydown.enter="submitClick"
            >
              <template v-slot:suffix>
                <img
                  v-if="flag"
                  @click="flag = !flag"
                  style="width: 20px"
                  src="@/assets/image/pasword.png"
                  alt=""
                />
                <el-icon
                  :size="20"
                  @click="flag = !flag"
                  class="icon-style"
                  v-else
                >
                  <View />
                </el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item class="panel-form-item">
            <el-checkbox v-model="rememberMe" label="记住密码" size="large" />
          </el-form-item>
          <!-- <el-form-item class="panel-form-item code-form-item">
          <p class="err-info">{{ verification.code }}</p>
          <el-input
            v-model="form.code"
            placeholder="验证码"
            @keydown.enter="submitClick"
            class="code-input"
          >
            <template v-slot:append>
              <img :src="codeImg" class="code-img" @click="refer" />
            </template>
          </el-input>
        </el-form-item> -->

          <el-form-item class="panel-form-item">
            <el-button type="primary" class="fill" @click="submitClick"
              >登录</el-button
            >
            <el-button style="margin: 24px 0" class="fill" @click="submitClick(1)"
              >免费注册</el-button
            >
            <el-button style="margin: 0" class="fill" @click="submitClick(2)"
              >案事件三维重建及数字化建档系统</el-button
            >
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <div class="tips">
            公安部鉴定中心 & 江门市公安局 & 四维时代
          </div>
          <div class="tips" >公安部科技强警基础工作计划(2022JC13)</div>
          <!-- <el-button @click="loginShow = false">Cancel</el-button>
        <el-button type="primary" @click="loginShow = false">
          Confirm
        </el-button> -->
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { reactive, watch, ref, computed, onMounted } from "vue";
import { openErrorMsg, baseURL, getCode } from "@/request";
import { PHONE } from "@/constant/REG";
import { guid, strToParams } from "@/util";
import { RouteName, router } from "@/router";
import { login } from "@/store/system";
import { appConstant } from "@/app";
import { user } from "@/store/user";
import { loginShow } from "@/store/system";

// 是否显示明文密码
const flag = ref(true);
// 表单
const jsonrUrl = ref({
  register: '',
  setting: '/admin/index.html?key=gabjdzx',
});
  fetch('/admin/register.json')
    .then((response) => response.json())
    .then((data) => {
      jsonrUrl.value.register = data.url;
    });
const form = reactive({
  account: localStorage.getItem("userName") || "",
  password: localStorage.getItem("password") || "",
  code: "",
  remember: import.meta.env.DEV || localStorage.getItem("remember") === "1",
});
const formEl = ref(null);
const rememberMe = ref(false);
const verification = reactive({ phone: "", psw: "", code: "" });
const rules = reactive<FormRules<RuleForm>>({
  account: [
    { required: true, message: "请输入账号", trigger: "blur" },
    { max: 16, message: "最大长度16", trigger: "blur" },
  ],
  password: [
    {
      required: true,
      message: "请输入密码",
      trigger: "change",
    },
  ],
});
onMounted(() => {
  let localePass = localStorage.getItem("password");
  if (localePass) {
    let password = decodeURIComponent(escape(window.atob(localePass)));
    form.account = localStorage.getItem("username") || "";
    form.password = password;
    rememberMe.value = true;
  }
});
// 验证
// watch(
//   form,
//   () => {
//     console.log("form", form);
//     if (!form.account) {
//       verification.phone = "请输入手机号";
//     } else if (form.account == "88888888888") {
//       verification.phone = "";
//     } else {
//       verification.phone = PHONE.REG.test(form.account) ? "" : PHONE.tip;
//     }
//     if (!form.password) {
//       verification.psw = "请输入密码";
//     } else {
//       verification.psw = "";
//     }
//     if (!form.code.trim()) {
//       verification.code = "请输入验证码";
//     } else {
//       verification.code = "";
//     }
//   },
//   { immediate: true }
// );

// 图片验证码
const imgKey = ref(guid());
const refer = () => (imgKey.value = guid());
const codeImg = computed(() => baseURL + getCode + "?key=" + imgKey.value);

// 表单提交
const submitClick = async (value) => {
  if(value == 1 || value == 2){
    return window.open(value==1?jsonrUrl.value.register:jsonrUrl.value.setting);
  }
  if (!formEl.value) return;
  await formEl.value.validate(async (valid, fields) => {
    if (valid) {
      console.log("submit!");
      try {
        await login({
          username: form.account,
          password: form.password,
        });

        if (rememberMe.value) {
          let password: string = window.btoa(
            unescape(encodeURIComponent(form.password))
          );
          localStorage.setItem("password", password);
          localStorage.setItem("username", form.account);
        } else {
          localStorage.removeItem("password");
          localStorage.removeItem("username");
        }

        // const params = strToParams(window.location.search);
        // if ("redirect" in params) {
        //   const url = new URL(unescape(params.redirect));
        //   url.searchParams.delete("token");
        //   url.searchParams.append("token", user.value.token);
        //   window.location.replace(url);
        // } else {
          location.reload()
          // router.replace({ name: RouteName.scene, params: { caseId: 360 } });
        // }
      } catch (e) {
        console.error(e);
        return refer();
      }
    } else {
      console.log("error submit!", fields);
    }
  });
  // if (verification.phone && verification.phone !== "88888888888") {
  //   return openErrorMsg(verification.phone);
  // }
  // if (verification.psw) return openErrorMsg(verification.psw);
  // if (verification.code) return openErrorMsg(verification.code);
};
</script>

<style lang="scss" scoped>
.login-layer {
  text-align: center;
  .dialoglogin {
    padding: 0 80px;
  }
  .title1 {
    font-weight: bold;
    font-size: 40px;
    color: #000000;
    line-height: 60px;
    letter-spacing: 8px;
    font-style: normal;
  }
  .title2 {
    font-weight: 400;
    font-size: 14px;
    color: #666666;
    line-height: 30px;
    font-style: normal;
    margin-bottom: 32px;
  }
}
.tips {
  font-weight: 400;
  font-size: 12px;
  color: #999999;
  line-height: 30px;
  letter-spacing: 1px;
  text-align: center;
}
.content {
  display: flex;
  justify-content: center;
  align-items: flex-start;
}
</style>
