<template>
    <div class="register-personal-user">
      <el-form ref="form" :model="formData" :rules="formDataRules">
        <el-form-item label="账号类型" prop="account_type">
          <el-select v-model="formData.account_type" placeholder="请选择账号类型">
            <el-option label="企业账号" :value="0" />
            <el-option label="企业子账号" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item
          label="企业名称"
          prop="enterprise_name"
          v-if="formData.account_type === 0"
        >
          <el-input
            v-model="formData.enterprise_name"
            placeholder="不超过50字符"
          />
        </el-form-item>
        <el-form-item
          label="统一社会信用代码"
          prop="social_credit_code"
          v-if="formData.account_type === 0"
        >
          <el-input
            v-model="formData.social_credit_code"
            placeholder="请输入统一社会信用代码"
          />
        </el-form-item>
        <el-form-item
          label="选择企业"
          prop="enterprise_id"
          v-if="formData.account_type === 1"
        >
          <el-select
            v-model="formData.enterprise_id"
            placeholder="搜索并选择"
            filterable
            remote
            :remote-method="getFirmList"
            :laoding="laodingFirmList"
          >
            <el-option
              v-for="(firm, index) in fimList"
              :label="firm.enterprise_name"
              :value="firm.id"
              :key="`firm_${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: "RegisterFrimUser", // 注册企业用户
    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();
          }
        }, 100);
      };
  
      var checkIdentify = (rule, value, callback) => {
        let reg = "";
        let msg = "";
  
        reg = /^([0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{10}|[1-9]\d{14})$/;
        msg = "请输入正确的统一社会信用代码";
  
        if (!reg.test(value)) {
          callback(new Error(msg));
        } else {
          callback();
        }
      };
  
      return {
        formData: {
          is_inside: 1, // 固定1
          user_category: 1, // 企业用户1
          account_type: 0, // 企业用户类型，0-主账号，1-子账号 必填
          enterprise_name: "", // 企业名称 必填（主账号）
          social_credit_code: "", // 统一社会信用代码 必填（主账号）
          enterprise_id: "", // 企业id 必填（子账号）
          user_id: "", // 用户名 必填
          password: "", // 密码 必填
          confirm_password: "",
          phone: "", // 手机号 必填
          code: "", //验证码 必填
          user_name: "", // 联系人姓名 选填
          id_number: "", // 身份证号 选填
        },
        formDataRules: {
          account_type: [
            { required: true, message: "请选择账号类型", trigger: "change" },
          ],
          enterprise_name: [
            { required: true, message: "请输入企业名称", trigger: "blur" },
            { max: 50, message: "长度应小于50个字符", trigger: "blur" },
          ],
          social_credit_code: [
            {
              required: true,
              message: "请输入统一社会信用代码",
              trigger: "blur",
            },
            { validator: checkIdentify, trigger: "blur" },
          ],
          enterprise_id: [
            { required: true, message: "请选择企业", trigger: "change" },
          ],
          user_id: [
            { required: true, message: "请输入用户名", trigger: "blur" },
            { validator: validateUserId, trigger: "blur" },
          ],
          password: [
            { required: true, message: "请输入密码", trigger: "change" },
            { validator: validatePassword, trigger: "blur" },
          ],
          confirm_password: [
            { required: true, message: "请再次输入密码", trigger: "change" },
            { validator: validateConfirmPassword, trigger: "blur" },
          ],
          phone: [
            { required: true, message: "请输入手机号码", trigger: "change" },
            { validator: validatePhone, trigger: "blur" },
          ],
          code: [{ required: true, message: "请输入验证码", trigger: "blur" }],
        },
        identifyCode: "",
        fimList: [],
        fimListAll: [],
        laodingFirmList: false,
        hidePassword: true,
        hideConfirmPassword: true,
        countDown: 0,
        countDownTimer: null,
      };
    },
    watch: {
      step() {
        this.$nextTick(() => {
          this.$refs.step1 && this.$refs.step1.clearValidate();
          this.$refs.step2 && this.$refs.step2.clearValidate();
        });
      },
    },
    methods: {
      getFirmList(queryText) {
        if (queryText) {
          this.laodingFirmList = true;
  
          this.$api.general
            .getFirmList({
              limit: 9999999,
              search: queryText,
            })
            .then(({ data }) => {
              if (data.success === 1) {
                this.fimList = data.data;
              } else {
                this.$message.error(data.errMsg);
                this.fimList = [];
              }
  
              this.laodingFirmList = false;
            });
        } else {
          this.fimList = this.fimListAll;
        }
      },
      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;
  
            if (formData.account_type === 0) {
              delete formData.enterprise_id;
            } else {
              delete formData.enterprise_name;
              delete formData.social_credit_code;
            }
  
            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
        .getFirmList({
          limit: 9999999,
        })
        .then(({ data }) => {
          if (data.success === 1) {
            this.fimList = data.data;
            this.fimListAll = 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>
  