<template>
    <el-dialog :title="type === 'add' ? '添加用户' : '修改用户'" :visible.sync="dialogVisible" width="900px" id="userDialog">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
            <el-form-item label="用户名" prop="name">
                <el-input style="width: 350px" v-model="ruleForm.name"></el-input>
            </el-form-item>
            <el-form-item label="角色" prop="roleId">
                <el-select style="width: 350px" v-model="ruleForm.roleId" placeholder="请选择角色">
                    <el-option v-for="role in roleOptions" :key="role.id" :label="role.name" :value="role.id"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="项目权限" prop="projectList">
                <el-transfer
                  v-model="ruleForm.projectList"
                  filterable
                  :titles="['不可使用的项目', '可使用的项目']"
                  :data="allList"
                  :props="{
                      key: 'id',
                      label: 'name'
                    }"
                >
                  <span slot-scope="{ option }">{{ option.label }}</span>
                </el-transfer>
            </el-form-item>
            <el-form-item label="登录密码" prop="password">
                <el-input style="width: 350px" placeholder="请输入密码" v-model="ruleForm.password" show-password></el-input>
                <el-button type="primary" @click="handleResetPass">重置密码</el-button>
            </el-form-item>
        </el-form>
        <div slot="footer">
            <el-button size="small" @click="dialogVisible = false">取 消</el-button>
            <el-button size="small" type="primary" @click="submitForm('ruleForm')">确 定</el-button>
        </div>
    </el-dialog>
</template>

<script>
import {mapGetters} from "vuex";
import {createUsers, queryRole, updateUsers} from "@/api/system/persagy-sso-server";
import {projectQuerys} from "../../../../api/scan/request";

export default {
  components: {},
  props: {
    type: String, // 新增/编辑(add/edit)
  },
  data() {
    var validateName = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入用户名"));
      } else if (value.length > 16) {
        callback(new Error('长度不得超过16个字符'));
      } else if (!/^[A-Za-z\d]+$/.test(value)) {
        callback(new Error('用户名只允许输入数字和英文字符'));
      } else {
        callback();
      }
    };
    return {
      dialogVisible: false,
      ruleForm: {
        name: "",
        roleId: "",
        projectList: [],
        // projectList: [{key:1,name:2}],
        password: "123456",
      },
      allList: [],
      roleOptions: [],
      changeData: null,
      rules: {
        name: [
          {validator: validateName, trigger: "blur"}
        ],
        roleId: [{required: true, message: "请选择角色", trigger: "change"}],
      },
    };
  },
  computed: {
    ...mapGetters("layout", ["projectId", "projects"]),
    projectList() {
      // 右侧数据 已选的
      return this.projects.map((item) => {
        item.key = item.id;
        item.label = item.name;
        return item;
      });
    },
  },
  created() {
    this.allProjects()
  },

  methods: {
    // 显示全部的数据
    allProjects() {

      let params = {
        "pageNumber": 1,
        "pageSize": 50000,
        // "filters": "id not in('','','')"

      }
      projectQuerys(params, res => {
        this.allList = res.content.map((item) => {
          item.key = item.id;
          item.label = item.name;
          return item;
        })
      })
    },
    /**
     * 显示弹窗
     */
    showDialog(type, data) {
      this.getRoleList();
      if (data && type === "edit") {
        this.changeData = data;
        let {name, roleId, password, projectList} = data;
        this.ruleForm.name = name;
        this.ruleForm.roleId = roleId;
        this.ruleForm.password = password;
        this.ruleForm.projectList = projectList;
      } else {
        this.changeData = null;
        this.ruleForm.name = "";
        this.ruleForm.roleId = "";
        this.ruleForm.password = "123456";
        this.ruleForm.projectList = [];
      }
      this.dialogVisible = true;
    },
    /**
     * 查询角色列表
     */
    async getRoleList() {
      const params = {
        pageNumber: 1,
        pageSize: 1000,
      };
      const res = await queryRole(params);
      if (res.code === "Success" && res.data && res.data.length) {
        this.roleOptions = res.data;
      } else {
        res.data = [];
      }
    },
    /**
     * 重置密码(初始密码：123456)
     */
    handleResetPass() {
      this.ruleForm.password = 123456;
    },
    /**
     * 提交用户信息
     */
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          // 修改
          if (this.type === "edit" && this.changeData.id) {
            const params = {data: {content: {...this.ruleForm, id: this.changeData.id}}};
            const res = await updateUsers(params);
            if (res.code === "Success") {
              this.$message.success("用户修改成功！");
              this.dialogVisible = false;
              this.$emit("refresh");
            } else {
              this.$message.error(`用户修改失败，失败原因：${res.message}`);
            }
          } else {
            // 添加
            let params = {data: {...this.ruleForm}};
            const res = await createUsers(params);
            if (res.code === "Success") {
              this.$message.success("用户添加成功！");
              this.dialogVisible = false;
              this.$emit("refresh");
            } else {
              this.$message.error(`用户添加失败，失败原因：${res.message}`);
            }
          }
        } else {
          return false;
        }
      });
    },
  },
};
</script>
<style lang="less" scoped>
#userDialog {
    /deep/ .el-transfer__button:first-child {
        margin-bottom: 0;
    }
}
</style>
