<template>
    <div class="register-personal-user">
      <el-form ref="form" :model="formData" :rules="formDataRules">
        <el-form-item label="用户组织机构" prop="oid">
          <el-select
            v-model="formData.oid"
            placeholder="搜索并选择"
            filterable
            remote
            :remote-method="getOrgList"
            :laoding="laodingOrgList"
          >
            <el-option
              v-for="(org, index) in orgList"
              :label="org.department_name"
              :value="org.department_id"
              :key="`org_${index}`"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="用户名" prop="user_id">
          <el-input
            v-model="formData.user_id"
            placeholder="输入4-20字符。支持字母、数字"
          />
        </el-form-item>
        <el-form-item label="登录密码" prop="password">
          <el-input
            v-model="formData.password"
            placeholder="8--20位字符，必须由字母、数字、特殊符号组成"
            :type="hidePassword ? 'password' : 'text'"
          >
            <span
              slot="suffix"
              :title="hidePassword ? '显示密码' : '隐藏密码'"
              :class="hidePassword ? 'hide-password' : 'show-password'"
              @click="hidePassword = !hidePassword"
              style="cursor:pointer;"
            ></span>
          </el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirm_password">
          <el-input
            v-model="formData.confirm_password"
            placeholder="再次输入密码"
            :type="hideConfirmPassword ? 'password' : 'text'"
          >
            <span
              slot="suffix"
              :title="hideConfirmPassword ? '显示密码' : '隐藏密码'"
              :class="hideConfirmPassword ? 'hide-password' : 'show-password'"
              @click="hideConfirmPassword = !hideConfirmPassword"
              style="cursor:pointer;"
            ></span>
          </el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="formData.phone" placeholder="国内11位数手机号码" />
        </el-form-item>
        <el-form-item label="验证码" prop="code">
          <el-input v-model="formData.code" placeholder="请输入验证码">
            <template slot="append">
              <a class="input-append disabled" v-if="countDown > 0">
                {{ countDown }}秒后再次获取
              </a>
              <a class="input-append" @click="getMsgCode" v-else>
                获取验证码
              </a>
            </template>
          </el-input>
        </el-form-item>
        <div class="switch-to-login">
          <a @click.prevent="$emit('login')">
            已有账号？立即登录
          </a>
        </div>
        <el-form-item style="margin-top: 20px;">
          <el-button type="primary" @click="submitAction">
            注册
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </template>
  
  <script>
  import md5 from "js-md5";
  
  export default {
    name: "RegisterOrgUser", // 注册政府机构用户
    data() {
      const validateUserId = (rule, value, callback) => {
        let reg = new RegExp(/^[a-zA-Z0-9|\-|_|\.]+$/);
        if (value == "") {
          callback(new Error("请输入用户名"));
        } else if (value.length > 16 || value.length < 3) {
          callback(new Error("长度请大于三位且不超过16位"));
        } else if (!reg.test(value)) {
          callback(new Error("只支持字母、数字、-、_、."));
        } else {
          this.$api.general
            .validateUserId({ value })
            .then(({ data }) => {
              if (data.success == 1) {
                callback();
              } else {
                callback(new Error(data.errMsg));
              }
            })
            .catch((error) => {
              console.log(error);
              callback(new Error("用户名验证失败"));
            });
        }
      };
      const validatePassword = (rule, value, callback) => {
        let reg = new RegExp(/^(?=.*\d)(?=.*[a-zA-Z])(?=.*[^a-zA-Z0-9]).{8,20}$/);
  
        setTimeout(() => {
          if (value == "") {
            callback(new Error("请输入密码"));
          } else if (!reg.test(value)) {
            callback(new Error("8--20位字符，必须由字母、数字、特殊符号组成"));
          } else {
            callback();
          }
        }, 100);
      };
      const validateConfirmPassword = (rule, value, callback) => {
        setTimeout(() => {
          if (value !== this.formData.password) {
            callback(new Error("密码和确认密码不一致"));
          } else {
            callback();
          }
        }, 100);
      };
      const validatePhone = (rule, value, callback) => {
        const reg = /^(?:(?:\+|00)86)?1[3-9]\d{9}$/;
  
        setTimeout(() => {
          if (!reg.test(value)) {
            callback(new Error("请输入正确的手机号码"));
          } else {
            callback();
          }
        });
      };
  
      return {
        formData: {
          is_inside: 1, // 固定1
          user_category: 0, // 用户类型0
          oid: "", // 用户组织机构 必填
          user_id: "", // 用户名 必填
          password: "", // 密码 必填
          confirm_password: "",
          phone: "", // 电话 必填
          code: "", // 验证码 必填
          user_name: "", // 姓名 选填
          system_name: "", // 业务系统名称 选填
          domain_name: "", // 域名 选填
          ip_whitelist: "", // ip地址 选填
        },
        formDataRules: {
          oid: [
            { required: true, message: "请选择用户组织机构", trigger: "change" },
          ],
          user_id: [
            { required: true, message: "请输入用户名", trigger: "blur" },
            { validator: validateUserId, trigger: "blur" },
          ],
          password: [
            { required: true, message: "请输入密码", trigger: "blur" },
            { validator: validatePassword, trigger: "blur" },
          ],
          confirm_password: [
            { required: true, message: "请再次输入密码", trigger: "blur" },
            { validator: validateConfirmPassword, trigger: "blur" },
          ],
          phone: [
            { required: true, message: "请输入手机号码", trigger: "change" },
            { validator: validatePhone, trigger: "blur" },
          ],
          code: [{ required: true, message: "请输入验证码", trigger: "blur" }],
        },
        orgList: [],
        orgListAll: [],
        laodingOrgList: false,
        hidePassword: true,
        hideConfirmPassword: true,
        countDown: 0,
        countDownTimer: null,
      };
    },
    methods: {
      getOrgList(queryText) {
        if (queryText) {
          this.laodingOrgList = true;
  
          this.$api.general
            .getOrgList({
              limit: 9999999,
              search: queryText,
            })
            .then(({ data }) => {
              if (data.success === 1) {
                this.orgList = data.data;
              } else {
                this.$message.error(data.errMsg);
                this.orgList = [];
              }
  
              this.laodingOrgList = false;
            });
        } else {
          this.orgList = this.orgListAll;
        }
      },
      getMsgCode() {
        this.$refs.form.validateField("phone", (errMsg) => {
          if (!errMsg) {
            this.$api.general.getCode(this.formData.phone).then(({ data }) => {
              if (data.success == 1) {
                this.countDownAction();
              }
            });
          }
        });
      },
      countDownAction() {
        this.countDown = 60;
  
        if (this.countDownTimer) {
          clearInterval(this.countDownTimer);
        }
  
        this.countDownTimer = setInterval(() => {
          if (this.countDown > 0) {
            this.countDown--;
          } else {
            clearInterval(this.countDownTimer);
          }
        }, 1000);
      },
      submitAction() {
        this.$refs.form.validate((valid) => {
          if (valid) {
            let formData = {
              ...this.formData,
              password: md5(this.formData.password),
            };
  
            delete formData.confirm_password;
  
            this.$api.general.registerlUser(formData).then(({ data }) => {
              if (data.success == 1) {
                this.$message({
                  message: "注册成功",
                  type: "success",
                });
  
                this.$emit("success");
              } else {
                this.$message({
                  message: data.errMsg || "注册失败",
                  type: "error",
                });
              }
            });
          }
        });
      },
    },
    created() {
      this.$api.general
        .getOrgList({
          limit: 9999999,
        })
        .then(({ data }) => {
          if (data.success === 1) {
            this.orgList = data.data;
            this.orgListAll = data.data;
          } else {
            this.$message.error(data.errMsg);
          }
        });
    },
  };
  </script>
  
  <style lang="less" scoped>
  .msg-code {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 25px;
  
    > .bg-identify {
      margin-left: 6px;
      flex-shrink: 0;
    }
  }
  </style>
  