<template>
  <div class="login">
    <el-card class="box-card">
      <div slot="header"
           class="clearfix">
        <span>注册</span>
      </div>
      <div>
        <ul class="choose-type">
          <li :class="{ active: form.registerType == '10' }"
              @click="changeType('10')"><i class="el-icon-user-solid"></i>注册课题组成员</li>
          <li :class="{ active: form.registerType == '20' }"
              @click="changeType('20')"><i class="el-icon-notebook-2"></i>注册课题组负责人</li>
        </ul>
        <el-steps :space="200"
                  :active="active"
                  finish-status="success"
                  align-center
                  class="mb20">
          <el-step title="登录信息"></el-step>
          <el-step title="个人信息"></el-step>
          <!-- <el-step title="其它信息"></el-step> -->
        </el-steps>
        <el-form ref="loginInfoRef"
                 size="mini"
                 v-show="active == 0"
                 :model="form"
                 :rules="rules"
                 label-width="80px">
          <el-form-item label="登录账号"
                        prop="userName">
            <el-input name="username"
                      placeholder="请输入登录账号"
                      v-model="form.userName"></el-input>
          </el-form-item>
          <el-form-item label="密码"
                        prop="password">
            <el-input name="password"
                      type="password"
                      placeholder="请输入密码"
                      v-model="form.password"
                      autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="确认密码"
                        prop="confirmPassword">
            <el-input name="confirmPassword"
                      type="password"
                      placeholder="请输入密码"
                      v-model="form.confirmPassword"
                      autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <el-form ref="personInfoRef"
                 size="mini"
                 v-show="active == 1"
                 :model="form"
                 :rules="rules"
                 label-width="80px">
          <el-form-item label="姓名"
                        prop="nickName">
            <el-input placeholder="请输入姓名"
                      v-model="form.nickName"></el-input>
          </el-form-item>
          <el-form-item label="性别"
                        prop="sex">
            <el-radio-group placeholder="请"
                            v-model="form.sex">
              <el-radio v-for="item in userSexList"
                        :key="item.dictValue"
                        :label="item.dictValue">{{ item.dictLabel }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="用户类型"
                        prop="userType">
            <el-radio-group v-model="form.userType"
                            placeholder="请选择用户类型"
                            style="width: 100%"
                            clearable>
              <el-radio v-for="item in userTypeList"
                        :key="item.id"
                        :label="item.dictValue">{{ item.dictLabel }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="组织部门"
                        prop="deptId">
            <el-cascader ref="casc"
                         :options="deptData"
                         @change="deptChange"
                         :props="{ checkStrictly: true, emitPath: false, value: 'id', label: 'deptName' }"
                         placeholder="请选择组织部门"
                         clearable
                         class="w100"
                         v-model="form.deptId">
              <template #default="{ node, data }">
                <span>{{ data.deptName }}</span>
                <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
              </template>
            </el-cascader>
          </el-form-item>
          <el-form-item label="证件号"
                        prop="idCode">
            <el-input placeholder="请输入证件号"
                      v-model="form.idCode"
                      class="w100 input-with-select">
              <el-select slot="prepend"
                         v-model="form.idType"
                         placeholder="请选择证件类型">
                <el-option v-for="item in userCertList"
                           :key="item.dictValue"
                           :label="item.dictLabel"
                           :value="item.dictValue" />
              </el-select>
            </el-input>
          </el-form-item>
          <el-form-item label="课题组"
                        prop="applyPgName"
                        v-if="form.registerType === '20'">
            <el-input v-model="form.applyPgName"></el-input>
          </el-form-item>
          <el-form-item label="课题组"
                        prop="applyPg"
                        v-else>
            <el-select v-model="form.applyPg"
                       placeholder="请选择课题组"
                       value-key="id"
                       class="w100">
              <el-option v-for="item in pjtList"
                         :key="item.id"
                         :label="item.pgName"
                         :value="item"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="所在时间"
                        prop="projectDate"
                        v-show="form.registerType === '10'">
            <el-date-picker v-model="form.projectDate"
                            type="daterange"
                            class="w100"
                            value-format="yyyy-MM-dd"
                            range-separator="至"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期" />
          </el-form-item>
        </el-form>
        <div class="buttons">
          <el-button size="mini"
                     v-if="active > 0"
                     @click="preStep">上一步</el-button>
          <el-button size="mini"
                     v-if="active < 1"
                     type="primary"
                     @click="nextStep">下一步</el-button>
          <el-button size="mini"
                     v-if="active === 1"
                     @click="onRegister"
                     type="primary">注册</el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import crypto from "sm-crypto";
import { setToken } from "@/utils/auth";
import { register } from "@/api/login";
import to from "await-to-js";
import {
  getDictDataByType,
  getDeptTree,
  getProjectGroupList,
} from "@/api/dict";
export default {
  data() {
    const checkPassword = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.form.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    const checkDate = (rule, value, callback) => {
      console.log(value, 'valueeeeee');
      
      if(this.form.registerType === '10' && !value.length) {
        callback(new Error("请选择所在时间"));
      }
      callback()
    };
    return {
      active: 0,
      type: "person",
      labelPosition: "right",
      form: {
        id: 0,
        userName: "", // 账户名称
        nickName: "", // 用户姓名
        userType: "10", // 关联角色
        deptId: null,
        deptName: "", // 单位名称
        postIds: [],
        roleIds: [],
        groupIds: [],
        phone: "", // 手机号
        email: "", // 邮箱
        sex: "30", // 性别
        password: "", // 账户密码
        confirmPassword: "",
        status: "10", // 用户状态
        describe: "", // 用户描述
        avatar: "",
        idType: "10", //证件类型
        idCode: "", // 证件号
        personnelType: "", // 人员类型
        projectId: null,
        projectName: "",
        projectDate: [],
        registerType: '10',
        applyPg: {},
        applyPgName: '',
        applyPgId: null
      },
      rules: {
        userName: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 5,
            max: 20,
            message: "密码长度在 5 到 20 个字符",
            trigger: "blur",
          },
        ],
        confirmPassword: [
          { required: true, validator: checkPassword, trigger: "blur" },
        ],
        nickName: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        userType: [
          { required: true, message: "请选择用户类型", trigger: "change" },
        ],
        deptId: [
          { required: true, message: "请选择组织部门", trigger: "change" },
        ],
        idCode: [{ required: true, message: "请输入证件号", trigger: "blur" }],
        applyPg: [
          { required: true, message: "请选择课题组", trigger: "change" },
        ],
        applyPgName: [
          { required: true, message: "请输入课题组", trigger: "blur" },
        ],
        projectDate: [
          { required: true, validator: checkDate, trigger: "change" },
        ]
      },
      loading: false,
      userTypeList: [],
      userSexList: [],
      userCertList: [],
      deptData: [],
      pjtList: [],
    };
  },
  mounted() {
    this.getDicts();
  },
  methods: {
    getDicts() {
      Promise.all([
        getDictDataByType("sys_user_type"),
        getDictDataByType("sys_com_sex"),
        getDictDataByType("sys_user_certificate"),
        getDeptTree(),
        getProjectGroupList(),
      ]).then(([type, sex, cert, dept, pjt]) => {
        this.userTypeList = type.data.values || [];
        this.userSexList = sex.data.values || [];
        this.userCertList = cert.data.values || [];
        this.deptData = dept.data || [];
        this.pjtList = pjt.data.list || [];
      });
    },
    changeType(val) {
      this.form.registerType = val;
    },
    // 部门选择
    deptChange() {
      if (this.form.userType === "20") return;
      const nodes = this.$refs.casc.getCheckedNodes();
      this.form.deptName = nodes[0].label;
    },
    preStep() {
      this.active--;
    },
    nextStep() {
      if (this.active < 2) {
        let form = "loginInfoRef";
        if (this.active == 1) {
          form = "personInfoRef";
        }
        this.$refs[form].validate(async (valid) => {
          if (valid) {
            this.active++;
          }
        });
      }
    },
    onRegister() {
      this.$refs.personInfoRef.validate(async valid => {
        if(valid) {
          const params = JSON.parse(JSON.stringify(this.form))
          params.password = crypto.sm3(params.password);
          delete params.confirmPassword
          if(params.projectDate.length) {
            params.startDate = params.projectDate[0]
            params.endDate = params.projectDate[1]
          }
          delete params.projectDate
          if(params.registerType === '10') {
            params.applyPgId = params.applyPg.id
            params.applyPgName = params.applyPg.padName
          }
          delete params.applyPg
          const [err] = await to(register(params));
          if(err) {
            this.$message.warning('操作失败')
            return
          }
          this.$message.success({
            message: '注册成功，即将跳转登录页',
            onClose: () => {
              this.$router.push('/login')
            }
          })
        }
      })
    },
    login() {
      if (this.active < 3) {
        this.active++;
      } else {
      }
      this.$refs.lform.validate(async (valid) => {});
    },
  },
};
</script>

<style lang="scss" scoped>
a {
  text-decoration: none;
  color: #409eff;
}

.login {
  width: 100%;
  height: calc(100vh - 116px);
  display: flex;
  align-items: center;
  justify-content: center;
  background: url("../assets/img/login-bg.png") center no-repeat;
  background-size: 100% 100%;
}

.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}

.box-card {
  width: 500px;
  margin: 0 auto;
}
.el-form-item__content {
  text-align: start;
}
.choose-type {
  display: flex;
  list-style: none;
  margin-bottom: 12px;
  li {
    height: 80px;
    width: 270px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    border-radius: 8px;
    border: 1px solid #ebeef5;
    cursor: pointer;
    transition: all 0.3s;
    color: #8c8888;
    & + li {
      margin-left: 12px;
    }
    &:hover,
    &.active {
      border-color: #409eff;
      color: #409eff;
    }
    i {
      font-size: 30px;
      margin-bottom: 12px;
    }
  }
}
.buttons {
  display: flex;
  justify-content: flex-end;
}
::v-deep .input-with-select .el-input-group__prepend {
  background-color: #fff;
  width: 40%;
}
.el-steps {
  justify-content: center;
}
</style>
