<template>
  <el-dialog
    :visible.sync="dialog"
    :title="title"
    append-to-body
    width="500px"
    :close-on-click-modal="false"
    @close="close"
  >
    <el-form
      ref="form"
      :model="ruleForm"
      :rules="rules"
      label-position="left"
      size="small"
      label-width="100px"
    >
      <el-form-item label="用户类型" prop="userType">
        <el-radio-group
          v-model="ruleForm.userType"
          :disabled="title === '编辑'"
        >
          <el-radio :label="1">投顾</el-radio>
          <el-radio :label="2">非投顾</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="登录账号" prop="staffNo">
        <el-input
          v-model.trim="ruleForm.staffNo"
          style="width:300px;"
          :disabled="title === '编辑'"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item label="员工号">
        <el-input
          v-model.trim="ruleForm.upId"
          style="width:300px;"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item label="用户姓名" prop="name">
        <el-input
          v-model="ruleForm.name"
          style="width:300px;"
          autocomplete="off"
        ></el-input>
      </el-form-item>

      <el-form-item label="手机号">
        <el-input
          v-model="ruleForm.mobile"
          style="width:300px;"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <div v-if="ruleForm.userType === 1">
        <el-form-item label="部门" prop="deptId">
          <el-select
            v-model="ruleForm.deptId"
            filterable
            placeholder="请选择"
            style="width:300px;"
          >
            <el-option
              v-for="item in depts"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="title === '编辑'" label="用户角色">
          <treeselect
            v-model="ruleForm.roleIds"
            :style="style"
            :multiple="true"
            :normalizer="normalizer"
            :options="roles"
            placeholder="选择用户角色"
          />
        </el-form-item>
      </div>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="doSubmit">确认</el-button>
      <el-button type="text" @click="close">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getDepts } from "@/api/channel";
import { getAll } from "@/api/role";
import { add, updateUserInfo } from "@/api/user";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { mapGetters } from "vuex";
import { COMPOSITION_TYPE } from "@/utils/options";
export default {
  components: { Treeselect },
  created() {},
  computed: {
    ...mapGetters(["user"])
  },
  data() {
    const validateMobile = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("请输入手机号"));
      }
      let reg = /^1[3|4|5|6|7|8|9][0-9]\d{8}$/;
      if (!reg.test(value)) {
        return callback(new Error("请输入正确的手机号"));
      }
      callback();
    };
    return {
      normalizer(node) {
        return {
          id: node.id,
          label: node.name,
          children:
            node.children && node.children.length > 0 ? node.children : 0
        };
      },
      dialog: false,
      depts: [],
      roles: [],
      style: "width: 300px",
      title: "新增",

      ruleForm: {
        loginId: null,
        userType: null,
        staffNo: "",
        upId: "",
        name: "",
        mobile: "",
        deptId: "",
        roleIds: []
      },
      rules: {
        userType: [
          { required: true, message: "请选择用户类型", trigger: "blur" }
        ],
        name: [{ required: true, message: "请输入用户姓名", trigger: "blur" }],
        staffNo: [
          { required: true, message: "请输入登录账号", trigger: "blur" }
        ],
        upId: [{ required: true, message: "请输员工号", trigger: "blur" }],
        mobile: [
          { required: true, validator: validateMobile, trigger: "blur" }
        ],
        deptId: [{ required: true, message: "请选择部门", trigger: "blur" }],
        roleIds: [
          { required: true, message: "请选择用户角色", trigger: "blur" }
        ]
      }
    };
  },
  methods: {
    close() {
      this.depts = [];
      this.roles = [];
      this.ruleForm = {
        loginId: null,
        userType: null,
        staffNo: "",
        name: "",
        mobile: "",
        upId: "",
        deptId: "",
        roleIds: []
      };
      this.$refs.form.resetFields();
      this.dialog = false;
    },
    async doSubmit() {
      this.$refs.form.validate(async valid => {
        if (valid) {
          const fn = this.title === "新增" ? add : updateUserInfo;
          const data = await fn(this.ruleForm);

          if (data.code === 0) {
            this.$message({
              message: this.title === "新增" ? "添加成功" : "编辑成功",
              type: "success"
            });
            // 关闭
            this.$parent.formQuery();
            this.close();
          } else {
            this.$message({
              message: data.message,
              type: "error"
            });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    getIndex(values) {
      const indexs = [];
      this.roles.forEach((item, index) => {
        if (values.includes(item.id)) {
          indexs.push(index);
        }
      });
      console.log("getIndex=>" + indexs);
      return indexs;
    },
    getRoles() {
      getAll({ current: 1, size: 10000 })
        .then(res => {
          this.roles = res.data.list.filter(item => item.id !== 2);
        })
        .catch(err => {
          console.log(err.response.data.message);
        });
    },
    getDepts() {
      getDepts().then(res => {
        this.depts = res.data;
      });
    },
    getComposition() {
      const composition = this.$store.state.user.systemSafety.passwordComposition.split(
        ","
      );
      const arr = composition.map(item => {
        return COMPOSITION_TYPE[Number(item)];
      });
      return arr.join("、");
    }
  }
};
</script>

<style>
.none {
  display: none;
}
</style>
