<template>
  <el-dialog
    :visible="dialogVisible"
    width="40%"
    style="height: 98%"
    :before-close="handleClose"
    top="5vh"
    lock-scroll
    v-loading="loading"
    element-loading-background="rgba(0, 0, 0, 0.5)"
  >
    <div class="title" slot="title">
      <div class="divider"></div>
      <div class="label">{{ title }}</div>
    </div>
    <div class="dialog-content">
      <el-form
        :model="dialogForm"
        class="basic-info"
        :rules="rules"
        ref="form"
        size="mini"
      >
        <el-form-item
          label="账号"
          :label-width="formLabelWidth"
          prop="username"
        >
          <el-input
            v-model="dialogForm.username"
            autocomplete="off"
            placeholder="请输入用户名"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item
          label="密码"
          :label-width="formLabelWidth"
          prop="password"
          v-if="!dialogForm.id"
        >
          <el-input
            v-model="dialogForm.password"
            autocomplete="off"
            show-password
            type="password"
            placeholder="请输入密码"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="手机号" :label-width="formLabelWidth">
          <el-input
            v-model="dialogForm.phone"
            autocomplete="off"
            placeholder="请输入手机号"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="昵称" :label-width="formLabelWidth">
          <el-input
            v-model="dialogForm.nickName"
            autocomplete="off"
            placeholder="请输入昵称"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="真实姓名" :label-width="formLabelWidth">
          <el-input
            v-model="dialogForm.realName"
            autocomplete="off"
            placeholder="请输入真实姓名"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item
          label="所属部门"
          :label-width="formLabelWidth"
          prop="deptId"
        >
          <el-cascader
            style="width: 100%"
            v-model="dialogForm.deptId"
            :options="orgTreeData"
            :props="optionProps"
            placeholder="请选择所属部门"
            clearable
          >
          </el-cascader>
        </el-form-item>
        <el-form-item
          label="所属地区"
          :label-width="formLabelWidth"
          prop="regionCode"
        >
          <el-cascader
            style="width: 100%"
            v-model="dialogForm.regionCode"
            :options="regionTree"
            :props="culturalRegionProps"
            placeholder="请选择所属地区"
            filterable
            clearable
          >
          </el-cascader>
        </el-form-item>
        <el-form-item label="是否启用" :label-width="formLabelWidth">
          <el-switch v-model="status"> </el-switch>
        </el-form-item>
      </el-form>
    </div>
    <div class="dialog-footer">
      <el-button size="mini" @click="cancelForm">取 消</el-button>
      <el-button size="mini" type="primary" @click="handleSubmit"
        >确定<i class="el-icon-circle-check" style="margin-left: 5px"></i
      ></el-button>
    </div>
  </el-dialog>
</template>

<script>
import { addUser, upadateUser } from "@/api/user";
import { mapGetters } from "vuex";
import md5 from "js-md5";
export default {
  name: "InfoEditDialog",
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    form: {
      type: Object,
      default: () => ({}),
    },
    orgTreeData: {
      type: Array,
      default: () => [],
    },
  },
  computed: {
    ...mapGetters(["userInfo"]),
    title() {
      if (this.dialogForm.id) {
        return "修改用户信息";
      } else {
        return "添加用户";
      }
    },
  },
  watch: {
    form: {
      handler: function (value) {
        let that = this;
        that.dialogForm = JSON.parse(JSON.stringify(value));

        // 编辑状态
        if (that.dialogForm.id) {
          console.log("that.dialogForm", that.dialogForm);
          // return
          // 回填状态
          that.status = Boolean(Number(that.dialogForm.status));
          // 回填部门
          // that.dialogForm.deptId = [that.dialogForm.deptId];
          // debugger
        } else {
          that.dialogForm.deptId = [];
        }
      },
      immediate: true,
      deep: true,
    },
    visible: {
      handler: function (value) {
        this.dialogVisible = value;
        this.loadRegionTree();
      },
      deep: true,
      immediate: true,
    },
  },
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        var pattern =
          /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\\W_!@#$%^&*`~()-+=]+$)(?![a-z0-9]+$)(?![a-z\\W_!@#$%^&*`~()-+=]+$)(?![0-9\\W_!@#$%^&*`~()-+=]+$)[a-zA-Z0-9\\W_!@#$%^&*`~()-+=]{8,30}$/;
        if (!pattern.test(value)) {
          callback(
            new Error(
              "密码长度至少8位，至少含数字,大写字母,小写字母,特殊符其中三种"
            )
          );
        }
        callback();
      }
    };

    var validateUserName = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入账号"));
      } else {
        var pattern = /^[0-9a-zA-Z|_]{4,20}$/g;
        if (!pattern.test(value)) {
          callback(new Error("账号长度4-20个字符，只能包括字母、数字、下划线"));
        } else {
          callback();
        }
      }
    };

    var validatePhone = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入手机号"));
      } else {
        var pattern = /^((0\d{2,3}-\d{7,8})|(1[3584]\d{9}))$/;
        if (!pattern.test(value)) {
          callback(new Error("请输入合法手机号/电话号"));
        } else {
          callback();
        }
      }
    };
    return {
      dialogForm: {},
      formLabelWidth: "100px",
      status: true,
      files: [], //文献文件
      dialogVisible: false,
      optionProps: {
        value: "id",
        label: "label",
        children: "children",
        checkStrictly: true,
      },
      culturalRegionProps: {
        value: "code",
        label: "name",
        children: "children",
        checkStrictly: true,
      },
      regionTree: [],
      rules: {
        username: [
          { validator: validateUserName, trigger: "blur", required: true },
        ],
        // phone: [{ validator: validatePhone, trigger: "blur", required: true }],
        nickName: [
          { required: true, message: "请输入昵称", trigger: "blur" },
          {
            pattern: /^(?!_)(?!.*?_$)[a-zA-Z0-9_\u4e00-\u9fa5]+$/,
            message:
              "昵称长度2~10位，只能包含中文、英文大小写、数字及下划线，不能以下划线开头或结尾",
            trigger: "blur",
          },
        ],
        password: [
          { validator: validatePass, trigger: "blur", required: true },
        ],
        deptId: [{ required: true, message: "请输入部门", trigger: "change" }],
      },
      value: [],
      loading: false,
    };
  },
  methods: {
    // 取消编辑
    cancelForm() {
      this.$emit("handleClose");
      this.$refs.form.resetFields(); //对表单进行重置且移除校验结果
    },

    handleSubmit() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          this.loading = true;
          let params = JSON.parse(JSON.stringify(this.dialogForm));
          // 修改状态
          params.status = this.status ? 1 : 0;
          // 处理所属部门
          if (params.deptId instanceof Array) {
            params.deptId = params.deptId[params.deptId.length - 1];
          }
          if (params.regionCode instanceof Array) {
            params.regionCode = params.regionCode[params.regionCode.length - 1];
          }

          if (params.id) {
            //修改用户信息时不提交盐和用户密码
            delete params.password;
            delete params.salt;
            let res = await upadateUser(params);
            if (res.code == 0) {
              this.$message.success("修改成功！");
              this.reload();
            }
            this.loading = false;
          } else {
            //加密密码
            params.password = md5(params.password);
            let res = await addUser(params);
            if (res.code == 0) {
              this.$message.success("添加成功！");
              this.reload();
            }
            this.loading = false;
          }
        }
      });
    },
    reload() {
      this.$emit("refresh");
      this.$emit("handleClose");
      this.$refs.form.resetFields(); //对表单进行重置且移除校验结果
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
          this.$emit("handleClose");
          this.$refs.form.resetFields(); //对表单进行重置且移除校验结果
        })
        .catch((_) => {});
    },
    loadRegionTree() {
      let parentId = "";
      this.$store.dispatch("org/getSysRegionTreeData", parentId).then((res) => {
        this.regionTree = res;
        loopTree(this.regionTree);
        function loopTree(arr) {
          if (arr && arr.length > 0) {
            arr.forEach((item) => {
              if (item.children && item.children.length == 0) {
                delete item.children;
              } else {
                loopTree(item.children);
              }
            });
          }
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.title {
  display: flex;
  margin-bottom: 16px;

  .divider {
    width: 8px;
    border-left: 4px solid #409eff;
    margin-right: 8px;
  }

  .label {
    font-weight: bold;
  }
}

.dialog-content {
  padding: 0 32px;
  // display: flex;

  .basic-info {
    flex: 1;
    margin-right: 48px;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>
