<template>
  <div>
    <!---lxh-修改密码-->
    <div class="dig_update">
      <el-dialog
        :visible.sync="dialogVisible"
        :close-on-click-modal="false"
        width="40%"
        style="border-radius: 40px"
      >
        <div slot="title">
          <el-form
            :model="ruleForm"
            :rules="rules"
            :inline="true"
            ref="ruleForm"
            label-width="150px"
            class="demo-ruleForm"
          >
            <p v-if="isView" class="dig_title">单独注册</p>
            <p v-if="!isView" class="dig_title">编辑</p>
            <div slot=""></div>
            <div slot="footer"></div>
            <!-- :show-all-levels="false" -->
            <el-form-item label="所属组织架构" prop="group">
              <el-cascader
                placeholder="请选择组织架构"
                v-model="ruleForm.group"
                :options="groupData"
                :props="{ checkStrictly: true }"
                clearable
              ></el-cascader>
            </el-form-item>
            <el-form-item label="账号" prop="studentNumber">
              <el-input v-model="ruleForm.studentNumber"></el-input>
            </el-form-item>
            <el-row>
              <el-col :span="12">
                <el-form-item label="姓名" prop="name">
                  <el-input v-model="ruleForm.name" autocomplete="off"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="性别" prop="sex">
                  <el-radio-group v-model="ruleForm.sex" style="margin-left: 20px">
                    <el-radio label="1">男</el-radio>
                    <el-radio label="0">女</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item v-if="isView" label="密码" prop="password">
              <el-input
                type="password"
                v-model="ruleForm.password"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item v-if="isView" label="确认密码" prop="comPassword">
              <el-input
                type="password"
                v-model="ruleForm.comPassword"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <div class="dig_button">
              <el-button type="info" round @click="resetData()">重置</el-button>
              <!-- <el-button type="success" round @click="submitForm('ruleForm')"
                >提交</el-button
              > -->
              <el-button type="success" round @click="submitCom()">提交</el-button>
            </div>
          </el-form>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script>
// import { oSessionStorage } from "../../utils/utils";
import { oSessionStorage } from "../utils/utils";
import md5 from "md5";
export default {
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else if (value.length < 6) {
        callback(new Error("密码至少6位"));
      } else {
        callback();
      }
    };
    var validateComPass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else if (value.length < 6) {
        callback(new Error("密码至少6位"));
      } else if (value !== this.ruleForm.password) {
        callback(new Error("两次密码不一致"));
        // callback();
      } else {
        callback();
      }
    };
    var validatePhone = (rule, value, callback) => {
      let myreg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
      if (value === "") {
        callback(new Error("请输入手机号"));
      } else if (!myreg.test(value)) {
        callback(new Error("请输入正确格式"));
      } else {
        callback();
      }
    };
    return {
      //编辑返回的值
      userDetailData: {},
      //组织架构名字
      groupName: "",
      ppData: [],
      groupData: [],
      options: [
        {
          value: "1",
          label: "选项1",
          children: [
            {
              value: "11",
              label: "选项11",
              children: [{ value: "111", label: "选项111" }],
            },
          ],
        },
      ],
      disableFlag: false,
      phoneFlag: false,
      flag: 3,
      dialogVisible: false,
      //渠道列表
      channelList: [{ name: "渠道天成", id: "1" }],
      ruleForm: {
        //所属组织架构
        group: "",
        //学号
        studentNumber: "",
        //姓名
        name: "",
        //性别
        sex: "",
        //密码
        password: "",
        comPassword: "",
      },
      isView: true,
      rules: {
        group: [{ required: true, message: "请选择组织架构", trigger: "blur" }],
        studentNumber: [{ required: true, message: "请输入账号", trigger: "blur" }],
        name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        sex: [{ required: true, message: "请选择性别", trigger: "blur" }],
        // password: [{ required: true, message: "请输密码", trigger: "blur" }],
        password: [{ required: true, validator: validatePass, trigger: "blur" }],
        comPassword: [{ required: true, validator: validateComPass, trigger: "blur" }],
      },
    };
  },
  mounted() {
    let userInfo = JSON.parse(oSessionStorage.getItem("userInfo"));
    this.ruleForm.parentCode = userInfo.invitationCode;

    //获取渠道信息

    // this.ruleForm.type = "3";
  },
  methods: {
    resetData() {
      this.$refs["ruleForm"].clearValidate();
      //清空表单
      this.ruleForm.group = "";
      this.ruleForm.name = "";
      this.ruleForm.studentNumber = "";
      this.ruleForm.password = "";
      this.ruleForm.comPassword = "";
      this.ruleForm.sex = "";
    },
    //获取组织架构方法--------------------开始-----------------------
    getChannel() {
      this.$http.get(`/org/findAllOrgByPOrgNo`, {}, (res) => {
        //  this.$toast.success({message:'成功'});
        if (res && res.code == 200) {
          //将值赋值给list
          if (res.data.length > 0) {
            let resAdd = this.addPro(res.data);
            this.ppData = JSON.parse(JSON.stringify(resAdd));
            let forRes = this.arrToTree(resAdd);
            // console.log('格式化的结构')
            // console.log(forRes)
            let resultRes = this.deleteChildren(forRes);
            console.log("格式化的结构且去掉children");
            console.log(resultRes);
            this.groupData = resultRes;
          } else {
            this.groupData = [];
          }
          // this.channelList = res.data;
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    //z增加
    addPro(val) {
      let data = JSON.parse(JSON.stringify(val));
      for (let i = 0; i < val.length; i++) {
        data[i].value = val[i].orgNo;
        data[i].label = val[i].orgName;
      }
      return data;
    },
    //非递归方式：将平铺数据转换为树形结构数据
    arrToTree(arr) {
      let data = arr.filter((item) => {
        item.children = arr.filter((e) => {
          return item.orgNo === e.parentOrgNo;
        });
        return !item.parentOrgNo;
      });
      return data;
    },
    //去除转换树形结构数据后存在的空children
    deleteChildren(arr) {
      let childs = arr;
      for (let i = childs.length; i--; i > 0) {
        if (childs[i].children) {
          if (childs[i].children.length) {
            this.deleteChildren(childs[i].children);
          } else {
            delete childs[i].children;
          }
        }
      }
      return arr;
    },
    queryOrgName() {
      for (let i = 0; i < this.ppData.length; i++) {
        if (this.ruleForm.group[this.ruleForm.group.length - 1] == this.ppData[i].orgNo) {
          this.groupName = this.ppData[i].orgName;
        }
      }
    },
    //获取组织架构方法--------------------结束-----------------------
    timeChange(val) {
      if (val !== null) {
        //根据时间得到格式化的数据
        this.ruleForm.birthDate = this.formatterTime(val);
      }
    },
    formatterTime(val) {
      let date = new Date(val);
      let year = date.getFullYear();
      let month = date.getMonth() + 1;
      month = this.formatterMon(month);
      let day = date.getDate();
      day = this.formatterMon(day);
      return year + "-" + month + "-" + day;
    },
    formatterMon(val) {
      if (val < 10) {
        return "0" + val;
      } else {
        return val;
      }
    },
    open(val) {
      this.cancle();
      this.getChannel();

      this.dialogVisible = true;
      this.isView = val;

      this.$nextTick(() => {
        this.$refs.ruleForm.clearValidate();
      });
    },
    edit(val) {
      this.getChannel();
      this.dialogVisible = true;
      this.isView = false;
      this.queryUserDetail(val.id);
      //调用查询详情的接口
    },
    //调用查询详情的接口
    queryUserDetail(val) {
      let url = `/user/findUserById?id=${val}`;

      this.$http.get(url, {}, (res) => {
        console.log(res);
        if (res && res.code == 200) {
          //获取返回值
          //根据将数据存储
          this.userDetailData = res.data;
          let a = [];
          for (let i = res.data.orgList.length; i > 0; i--) {
            //
            a.push(res.data.orgList[i - 1].orgNo);
          }
          //回显学号
          this.ruleForm.studentNumber = res.data.userNo;
          //回显姓名
          this.ruleForm.name = res.data.userName;
          //回显性别
          this.ruleForm.sex = res.data.gender;
          this.ruleForm.group = a;
        } else {
          // this.$toast.fail(res.msg);
          this.$message.error(res.msg);
        }
      });
    },
    cancle() {
      this.$refs["ruleForm"].clearValidate();
      //清空表单
      this.ruleForm.group = "";
      this.ruleForm.name = "";
      this.ruleForm.studentNumber = "";
      this.ruleForm.password = "";
      this.ruleForm.comPassword = "";
      this.ruleForm.sex = "";
      this.dialogVisible = false;
    },
    disableFlagStatus() {
      setTimeout(() => {
        this.disableFlag = false;
      }, 1500);
    },
    submitCom() {
      if (this.disableFlag) {
        return;
      }
      this.disableFlag = true;
      let validSp = [];
      if (this.isView) {
        validSp = ["group", "studentNumber", "name", "sex", "password", "comPassword"];
      } else {
        validSp = ["group", "studentNumber", "name", "sex"];
      }
      let aa = [];
      this.$refs["ruleForm"].validateField(validSp, (valid) => {
        if (!valid) {
          aa.push(valid);
          //判断是编辑还是新增
          if (this.isView) {
            if (aa.length == 6) {
              this.register();
            } else {
              this.disableFlagStatus();
            }
          } else {
            if (aa.length == 4) {
              this.editUserFun();
            } else {
              this.disableFlagStatus();
            }
          }

          //都校验通过后可以触发注册接口了
          //调用方法进行入参
        } else {
          this.disableFlagStatus();
        }
      });
    },
    register() {
      this.queryOrgName();
      if (this.ruleForm.group.length != 2) {
        this.$message({
          message: "院管理员请选择二级组织架构",
          type: "error",
        });
        return;
      }
      console.log(this.ruleForm.group);
      let that = this;
      // this.ruleForm.password = md5(this.ruleForm.password);
      this.$http.post(
        `/user/addOrUpdateUser`,
        {
          orgNo: this.ruleForm.group[this.ruleForm.group.length - 1],
          orgName: this.groupName,
          userNo: this.ruleForm.studentNumber,
          userName: this.ruleForm.name,
          gender: this.ruleForm.sex,
          password: md5(this.ruleForm.password),
          //roleType     1普通用户    roleType   管理员
          roleType: "2",
        },
        (res) => {
          this.disableFlagStatus();
          // this.disableFlag = false;
          if (res && res.code == 200) {
            this.dialogVisible = false;

            // this.$toast.success({ message: "成功" });
            //调用父组件的查询方法
            that.$emit("search");
          } else {
            // this.$toast.fail({ message: res.msg });
            this.$message.error(res.msg);
          }
          //清空缓存
          this.cancle();
        }
      );
    },
    editUserFun() {
      let that = this;
      this.queryOrgName();
      if (this.ruleForm.group.length != 2) {
        this.$message({
          message: "院管理员请选择二级组织架构",
          type: "error",
        });
        return;
      }
      this.userDetailData.orgNo = this.ruleForm.group[this.ruleForm.group.length - 1];
      this.userDetailData.orgName = this.groupName;
      this.userDetailData.userName = this.ruleForm.name;
      this.userDetailData.gender = this.ruleForm.sex;
      this.userDetailData.userNo = this.ruleForm.studentNumber;
      this.$http.post(
        `/user/addOrUpdateUser`,
        {
          ...this.userDetailData,
        },
        (res) => {
          this.disableFlagStatus();
          if (res && res.code == 200) {
            this.dialogVisible = false;
            // this.$toast.success({ message: "成功" });
            //调用父组件的查询方法
            that.$emit("search");
            this.$message.success("修改成功");
          } else {
            // this.$toast.fail({ message: res.msg });
            this.$message.error(res.msg);
          }

          //清空缓存

          //清空缓存
        }
      );
    },
  },
};
</script>
<style lang="less" scoped>
.dig_update /deep/.el-cascader {
  position: relative;
  font-size: 14px;
  line-height: 40px;
  width: 100%;
}
.dig_update /deep/.el-dialog {
  box-shadow: none !important;
  background: transparent !important;
}
.demo-ruleForm /deep/ .el-form-item {
  margin-right: 10px;
  vertical-align: top;
  display: flex !important;
  flex-direction: column;
}
.demo-ruleForm /deep/.el-form-item__label {
  text-align: left;
  vertical-align: middle;
  float: left;
  font-size: 14px;
  color: #606266;
  line-height: 40px;
  padding: 0 12px 0 0;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
}

.demo-ruleForm /deep/.el-input {
  width: 100% !important;
}

.demo-ruleForm /deep/.el-input__inner {
  width: 100% !important;
  background-color: #f7f7f7;
  border: 0px;
}

.dig_button {
  display: flex;
  width: 100%;
  justify-content: space-around;
}

.demo-ruleForm {
  background-color: #ffffff;
  // border-radius: 20px;
  margin-right: -10px;
  margin-top: -10px;
  padding-right: 100px;
  padding-left: 100px;
  border-radius: 20px;
  padding-top: 20px;
  padding-bottom: 40px;
  .dig_title {
    margin-bottom: 30px;
    text-align: center;
    font-weight: 700;
  }
}
</style>
