<template>
  <el-dialog
    class="modify-user"
    :visible.sync="modalIsShow"
    :title="title"
    top="10vh"
    width="540px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    @open="visibleChange"
  >
    <el-form
      ref="modalFormComp"
      :model="modalForm"
      :rules="rules"
      label-width="100px"
    >
      <el-form-item prop="loginName" label="用户名/工号：">
        <el-input
          v-model.trim="modalForm.loginName"
          placeholder="请输入用户名/工号"
          :disabled="isEdit"
        ></el-input>
      </el-form-item>
      <el-form-item prop="realName" label="姓名：">
        <el-input
          v-model.trim="modalForm.realName"
          placeholder="请输入姓名"
          clearable
        ></el-input>
      </el-form-item>
      <!-- <el-form-item prop="code" label="工号：">
        <el-input
          v-model.trim="modalForm.code"
          placeholder="请输入工号"
          clearable
        ></el-input>
      </el-form-item> -->
      <el-form-item prop="mobileNumber" label="手机号：">
        <el-input
          v-model.trim="modalForm.mobileNumber"
          placeholder="请输入手机号"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item prop="roleIds" label="角色：">
        <el-select
          style="width: 100%"
          v-model="modalForm.roleIds"
          placeholder="请选择角色"
          multiple
          filterable
        >
          <el-option
            v-for="item in roles"
            :key="item.id"
            :value="item.id"
            :label="item.name"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="orgId" label="所属机构：" label-position="top">
        <select-orgs
          ref="SelectOrgs"
          v-model="modalForm.orgId"
          :multiple="false"
          check-strictly
          @change="orgChange"
        ></select-orgs>
      </el-form-item>
      <el-form-item
        prop="allowManualCard"
        label="是否允许新增卡格式："
        label-width="160px"
      >
        <el-radio-group v-model="modalForm.allowManualCard">
          <el-radio
            v-for="(val, key) in BOOLEAN_TYPE"
            :key="key"
            :label="key * 1"
            >{{ val }}</el-radio
          >
        </el-radio-group>
      </el-form-item>
    </el-form>
    <div slot="footer">
      <el-button type="primary" :disabled="isSubmit" @click="submit"
        >确认</el-button
      >
      <el-button @click="cancel">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { updateUser } from "../api";
// import { logout } from "../../login/api";
// import { phone } from "@/plugins/formRules";
import SelectOrgs from "./SelectOrgs";
import { SYS_ADMIN_NAME, BOOLEAN_TYPE } from "@/constants/enumerate";

const initModalForm = {
  id: "",
  loginName: "",
  realName: "",
  //   code: "",
  mobileNumber: "",
  allowManualCard: 0,
  roleIds: [],
  courseIds: [],
  orgId: [],
};

export default {
  name: "modify-user",
  components: { SelectOrgs },
  props: {
    instance: {
      type: Object,
      default() {
        return {};
      },
    },
    roles: {
      type: Array,
      default() {
        return [];
      },
    },
  },
  computed: {
    isEdit() {
      return !!this.instance.id;
    },
    title() {
      return (this.isEdit ? "编辑" : "新增") + "用户";
    },
  },
  data() {
    const roleIdsValidator = (rule, value, callback) => {
      if (!value || !value.length) {
        callback(new Error("请选择角色"));
      } else {
        callback();
      }
    };
    const orgIdValidator = (rule, value, callback) => {
      if (!value || !value.length) {
        callback(new Error("请选择所属机构"));
      } else {
        callback();
      }
    };
    const mobileNumberValidator = (rule, value, callback) => {
      if (!value) {
        return callback();
      }

      if (/^1\d{10}$/.test(value)) {
        return callback();
      } else {
        return callback(new Error("请输入合适的手机号码"));
      }
    };

    const IS_SUPER_ADMIN =
      this.$ls.get("user", { loginName: "" }).loginName === SYS_ADMIN_NAME;

    return {
      modalIsShow: false,
      isSubmit: false,
      modalForm: {},
      rules: {
        mobileNumber: [
          {
            required: false,
            validator: mobileNumberValidator,
            trigger: "change",
          },
        ],
        loginName: [
          {
            required: true,
            message: "请输入用户名",
            trigger: "change",
          },
          {
            max: 50,
            message: "用户名不能超过50",
            trigger: "change",
          },
        ],
        realName: [
          {
            required: true,
            message: "请输入姓名",
            trigger: "change",
          },
          {
            max: 50,
            message: "姓名不能超过50",
            trigger: "change",
          },
        ],
        // code: [
        //   {
        //     required: true,
        //     message: "请输入工号",
        //     trigger: "change",
        //   },
        //   {
        //     max: 50,
        //     message: "工号不能超过50",
        //     trigger: "change",
        //   },
        // ],
        roleIds: [
          {
            required: true,
            validator: roleIdsValidator,
            trigger: "change",
          },
        ],
        orgId: [
          {
            required: true,
            validator: orgIdValidator,
            trigger: "change",
          },
        ],
      },
      user: {},
      courses: [],
      roleList: [],
      IS_SUPER_ADMIN,
      BOOLEAN_TYPE,
    };
  },
  methods: {
    initData(val) {
      if (val.id) {
        this.modalForm = this.$objAssign(initModalForm, val);
        this.modalForm.roleIds = val.roles.map((item) => item.id);
        this.modalForm.orgId = [val.orgId];
        this.modalForm.allowManualCard = val.allowManualCard ? 1 : 0;
      } else {
        this.modalForm = { ...initModalForm };
        this.$nextTick(() => {
          this.$refs.modalFormComp.clearValidate();
        });
      }
    },
    visibleChange() {
      this.initData(this.instance);
    },
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    orgChange() {
      this.$nextTick(() => {
        this.$refs.modalFormComp.validateField("orgId");
      });
    },
    async submit() {
      const valid = await this.$refs.modalFormComp.validate().catch(() => {});
      if (!valid) return;

      if (this.isSubmit) return;
      this.isSubmit = true;

      const datas = { ...this.modalForm };
      datas.allowManualCard = !!datas.allowManualCard;
      datas.orgId = datas.orgId.join();
      const data = await updateUser(datas).catch(() => {});
      this.isSubmit = false;
      if (!data) return;

      this.$message.success("修改成功！");
      this.cancel();
      this.$emit("modified");

      // if (!this.isEdit) {
      //   this.$emit("modified");
      //   return;
      // }

      // // 自己把自己的角色改了之后要重新登录，重新获取权限
      // const oldRoleIds = this.instance.roles
      //   .map(item => item.id)
      //   .sort((a, b) => a - b)
      //   .join();
      // const newRoleIds = datas.roleIds.sort((a, b) => a - b).join();
      // if (
      //   oldRoleIds !== newRoleIds &&
      //   this.$ls.get("user").id === this.instance.id
      // ) {
      //   await logout();
      //   this.$ls.clear();
      //   this.$router.push({ name: "Login" });
      //   this.$message.info("您的权限已经变更，请重新登录系统！");
      // } else {
      //   this.$emit("modified");
      // }
    },
  },
};
</script>
