<template>
  <el-dialog
    :visible="dialogVisible"
    width="40%"
    style="height: 98%"
    :before-close="handleClose"
    top="5vh"
    lock-scroll
  >
    <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">
        <el-form-item label="账号" :label-width="formLabelWidth">
          <el-input
            v-model="dialogForm.username"
            autocomplete="off"
            placeholder="请输入用户名"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" :label-width="formLabelWidth">
          <el-input
            v-model="dialogForm.password"
            autocomplete="off"
            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">
          <el-cascader
            style="width: 100%"
            v-model="dialogForm.deptId"
            :options="orgTreeData"
            :props="optionProps"
            placeholder="请选择所属部门"
          >
          </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 @click="cancelForm">取 消</el-button>
      <el-button type="primary" @click="handleSubmit"
        >确定<i class="el-icon-right" style="margin-left: 5px"></i
      ></el-button>
    </div>
  </el-dialog>
</template>

<script>
import { addUser, upadateUser } from "@/api/user";
import ManualUploader from "@/components/Uploader/ManualUploader.vue";
import { mapGetters } from "vuex";
import { uploadFile } from "@/utils/file";
export default {
  name: "InfoEditDialog",
  components: {
    ManualUploader,
  },
  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) {
          // 回填状态
          that.status = Boolean(Number(that.dialogForm.status));
          // 回填部门
          that.dialogForm.deptId = [that.dialogForm.deptId];
        }
      },
      immediate: true,
      deep: true,
    },
    visible: {
      handler: function (value) {
        this.dialogVisible = value;
      },
      deep: true,
      immediate: true,
    },
    // orgTreeData(value){
    //   console.log(1111,value);
    // }
  },
  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 {
          const formData = new FormData();
          formData.append("userName", value);
          checkUserName(formData)
            .then((res) => {
              if (res.code == "0") {
                callback();
              } else {
                callback(res.msg);
              }
            })
            .catch((err) => {
              console.error(err);
            });
        }
      }
    };

    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 {
          const formData = new FormData();
          formData.append("phone", value);
          checkPhone(formData)
            .then((res) => {
              console.log(res);
              if (res.code == "0") {
                callback();
              } else {
                callback(res.msg);
              }
            })
            .catch((err) => {
              console.error(err);
            });
        }
      }
    };
    return {
      dialogForm: {},
      formLabelWidth: "100px",
      status: true,
      files: [], //文献文件
      dialogVisible: false,
      optionProps: {
        value: "id",
        label: "label",
        children: "children",
        checkStrictly: true, //单选选择任意一级选项
      },
      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 },
        ],
      },
    };
  },
  methods: {
    handlePreview({ type, file }) {
      console.log(type, file);
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    // 取消编辑
    cancelForm() {
      this.$emit("handleClose");
      this.faceImage = [];
    },

    async handleSubmit() {
      let params = JSON.parse(JSON.stringify(this.dialogForm));
      // 修改状态
      params.status = this.status ? 1 : 0;
      // return;
      // 处理馆藏单位
      if (params.deptId instanceof Array) {
        params.deptId = params.deptId[params.deptId.length - 1];
      }
      if (params.id) {
        let res = await upadateUser(params);
        if (res.code == 0) {
          this.$message.success("修改成功！");
          this.reload();
        }
      } else {
        let res = await addUser(params);
        if (res.code == 0) {
          this.$message.success("添加成功！");
          this.reload();
        }
      }
    },
    reload() {
      this.$emit("refresh");
      this.$emit("handleClose");
      this.files = [];
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
          this.$emit("handleClose");
          this.files = [];
        })
        .catch((_) => {});
    },
  },
};
</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>