<template>
  <div class="register">
    <el-form class="panel" :model="form" :rules="rules" ref="baseFormRef">
      <h2>单位注册</h2>
      <span class="desc">
        此功能仅用于注册单位及单位管理员，
        单位内其它用户可由单位管理员登录后创建。
      </span>
      <el-form-item
        class="panel-form-item"
        label="单位名称"
        :maxlength="50"
        prop="orgName"
        required
      >
        <el-input
          :maxlength="11"
          v-model.trim="form.orgName"
          placeholder="请输入"
        ></el-input>
      </el-form-item>

      <el-form-item class="panel-form-item" label="类型" prop="type">
        <el-select v-model="form.type">
          <el-option
            class="register-select-option"
            :value="Number(key)"
            :label="type"
            v-for="(type, key) in OrganizationTypeDesc"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        class="panel-form-item"
        label="姓名"
        prop="contact"
        required
      >
        <el-input
          :maxlength="100"
          v-model.trim="form.contact"
          placeholder="请选择"
        ></el-input>
      </el-form-item>

      <el-form-item
        class="panel-form-item"
        prop="userName"
        label="账号"
        required
      >
        <el-input
          :maxlength="11"
          v-model.trim="form.userName"
          placeholder="请输入手机号码"
        >
        </el-input>
      </el-form-item>

      <el-form-item
        class="panel-form-item msgcode"
        prop="msgAuthCode"
        label="验证码"
        required
      >
        <el-input
          :maxlength="8"
          v-model.trim="form.msgAuthCode"
          placeholder="输入验证码"
        >
        </el-input>
        <el-button
          class="getMsgAuthCode"
          :loading="checkCodeBtn.loading"
          :disabled="checkCodeBtn.disabled"
          style="margin-left: 10px"
          @click="getCheckCode"
        >
          {{ checkCodeBtn.text }}</el-button
        >
      </el-form-item>

      <!-- <el-form-item class="panel-form-item" label="密码" prop="password" required>
                <el-input v-model.trim="form.password" placeholder="请输入8-16位数字、字母大小写组合">
                </el-input>
            </el-form-item> -->
      <el-form-item
        class="panel-form-item"
        label="密码"
        prop="password"
        required
      >
        <el-input
          autocomplete="off"
          readonly
          onfocus="this.removeAttribute('readonly');"
          v-model="form.password"
          :type="addPassFlag ? 'text' : 'password'"
          :maxlength="20"
          placeholder="请输入8-16位数字、字母大小写组合"
        >
          <template #suffix>
            <span @click="addPassFlag = !addPassFlag" style="cursor: pointer">
              <el-icon v-if="addPassFlag">
                <View />
              </el-icon>
              <el-icon v-else>
                <Hide />
              </el-icon>
            </span>
          </template>
        </el-input>
      </el-form-item>

      <el-form-item
        class="panel-form-item"
        label="密码确认"
        prop="confirmPwd"
        required
      >
        <el-input
          autocomplete="off"
          readonly
          onfocus="this.removeAttribute('readonly');"
          v-model="form.confirmPwd"
          :type="addPassFlag1 ? 'text' : 'password'"
          :maxlength="20"
          placeholder="输入再次输入密码"
        >
          <template #suffix>
            <span @click="addPassFlag1 = !addPassFlag1" style="cursor: pointer">
              <el-icon v-if="addPassFlag1">
                <View />
              </el-icon>
              <el-icon v-else>
                <Hide />
              </el-icon>
            </span>
          </template>
        </el-input>
      </el-form-item>

      <el-form-item class="panel-form-item">
        <el-button type="primary" class="fill submit" @click="submitClick"
          >注册</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>
<script lang="ts" setup>
import { reactive, ref, unref } from "vue";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";
import { OrganizationTypeDesc } from "@/store/organization";
import { View, Hide } from "@element-plus/icons-vue";
import { registerOrganization } from "@/request/organization";
import { globalPasswordRex } from "@/util/regex";
// import { encodePwd } from "@/util";
import { getMsgAuthCode } from "@/request";

const emit = defineEmits(["done"]);
const baseFormRef = ref<FormInstance>();
const addPassFlag = ref(false); //图标显示标识
const addPassFlag1 = ref(false); //图标显示标识

let checkCodeBtn = reactive<any>({
  text: "获取验证码",
  loading: false,
  disabled: false,
  duration: 60,
  timer: null,
});

const equalToPassword = (_, value: any, callback: any) => {
  if (form.password !== value) {
    callback(new Error("两次输入的密码不一致"));
  } else {
    callback();
  }
};

const rules = reactive<FormRules>({
  orgName: [{ required: true, message: "请选择单位名称", trigger: "select" }],
  msgAuthCode: [{ required: true, message: "请输入验证码", trigger: "change" }],
  contact: [{ required: true, message: "请输入姓名", trigger: "blur" }],
  userName: [
    { required: true, message: "请输入手机号码", trigger: "blur" },
    {
      required: true,
      pattern: /^1[3456789]\d{9}$/,
      message: "请输入手机号码",
      trigger: "blur",
    },
  ],
  password: [
    {
      required: true,
      pattern: globalPasswordRex,
      message: "请输入8-16位数字、字母大小写组合",
      trigger: "blur",
    },
    { required: true, min: 8, message: "密码太短！", trigger: "blur" },
  ],
  confirmPwd: [
    {
      required: true,
      pattern: globalPasswordRex,
      message: "请输入8-16位数字、字母大小写组合",
      trigger: "blur",
    },
    { required: true, min: 8, message: "密码太短！", trigger: "blur" },
    { required: true, validator: equalToPassword, trigger: "blur" },
  ],
});

const form = reactive({
  orgName: "",
  type: "",
  userName: "",
  password: "",
  contact: "",
  confirmPwd: "",
  msgAuthCode: "",
});

const getCheckCode = async () => {
  // 倒计时期间按钮不能单击
  await unref(baseFormRef)?.validateField("userName");

  const phoneNum = form.userName;
  console.log("getMsgCode", phoneNum);
  const res = await getMsgAuthCode("+86", phoneNum);
  if (res.success) {
    ElMessage.success(res.data);
  }
  if (checkCodeBtn.duration == 60) {
    checkCodeBtn.disabled = true;
  }
  // 清除掉定时器
  checkCodeBtn.timer && clearInterval(checkCodeBtn.timer);
  // 开启定时器
  checkCodeBtn.timer = setInterval(() => {
    const tmp = checkCodeBtn.duration--;
    checkCodeBtn.text = `${tmp}秒`;
    if (tmp <= 0) {
      // 清除掉定时器
      clearInterval(checkCodeBtn.timer);
      checkCodeBtn.duration = 60;
      checkCodeBtn.text = "重新获取";
      // 设置按钮可以单击
      checkCodeBtn.disabled = false;
    }
    console.info(checkCodeBtn.duration);
  }, 1000);
};

const submitClick = async () => {
  if (unref(baseFormRef)) {
    const res = await unref(baseFormRef)?.validate();
    if (res) {
      const result = await registerOrganization(form);
      console.log("result", result);
      emit("done");
      // ElMessage.success('新增成功！');
    }
  } else {
    throw "";
  }
};
</script>

<style lang="scss" scoped>
.register {
  padding: 10px 0;

  .panel {
    width: 430px;
  }

  .panel-form-item {
    padding-left: 0;
    padding-right: 0;
  }

  h2 {
    padding-left: 0;
    margin-bottom: 0;
  }

  .desc {
    color: #93795d;
    display: block;
    margin-bottom: 20px;
  }

  :deep(.panel-form-item .el-form-item__label) {
    line-height: 40px;
    font-size: 16px;
    min-width: 90px;
  }

  :deep(.el-form-item__error) {
    font-size: 14px;
  }

  :deep(.el-select) {
    width: 100%;
    height: 42px;
    line-height: 42px;

    .el-select__wrapper {
      height: 100%;
      font-size: 1.14rem;
    }
  }

  .msgcode {
    position: relative;
  }

  .getMsgAuthCode {
    border: 1px solid #93795d;
    background: rgba(147, 121, 93, 0.05);
    font-size: 14px;
    position: absolute;
    right: 5px;
    top: 5px;
    height: 32px;
    line-height: 32px;
  }

  .fill {
    width: 100%;
  }
}
</style>
<style>
.register-select-option {
  font-size: 1.14rem;
  min-height: 50px;
  line-height: 50px;
  /* padding: 5px 0; */
}
.el-form-item__label:before {
  display: none;
}
</style>
