<script setup lang="ts">
import { ref, reactive } from "vue";
import { ElMessageBox, ElMessage } from "element-plus";
const dialogVisibleAdd = ref(false);
import { postPageRole } from "@/api/roles";
import { postAssignmentUser } from "@/api/userSetting";
const formRef = ref();
const form = reactive({
  region: []
});
const handleClose = () => {
  form.region = [];
  dialogVisibleAdd.value = !dialogVisibleAdd.value;
};
const rolesList = reactive({
  list: [],
  assignmentParams: {
    sourceCodes: [],
    targetCodes: [],
    linkAction: "link",
    correlatedModel: "deptRole" // 部门角色关联
  }
});
const postAddUserGroupApi = async () => {
  const { code, msg } = await postAssignmentUser(rolesList.assignmentParams);
  if (code === 200) {
    ElMessage({
      message: "添加成功",
      type: "success"
    });
    handleClose();
  } else {
    ElMessage({
      message: msg,
      type: "error"
    });
  }
};

const rolesData = async () => {
  const { code, data } = await postPageRole({
    pageNumber: 1,
    pageSize: 100
  });
  if (code === 200) {
    rolesList.list = data.records;
  }
};
const changeRoles = (val = []) => {
  rolesList.assignmentParams.targetCodes = [];
  // rolesList.assignmentParams.sourceCodes = [];
  val.forEach(item => {
    rolesList.assignmentParams.targetCodes.push(item);
    // rolesList.assignmentParams.sourceCodes.push(item);
  });
};
// 添加部门保存
const saveDepartment = () => {
  postAddUserGroupApi();
};
const open = (item, user) => {
  dialogVisibleAdd.value = true;
  if (user == "用户") {
    rolesList.assignmentParams.sourceCodes = [];
    rolesList.assignmentParams.sourceCodes.push(item.userCode);
    rolesList.assignmentParams.correlatedModel = "userRole";
  } else {
    rolesList.assignmentParams.sourceCodes = [];
    rolesList.assignmentParams.sourceCodes.push(item.data.deptCode);
  }
  rolesData();
};
defineExpose({
  open
});
</script>

<template>
  <div>
    <el-dialog
      v-model="dialogVisibleAdd"
      title="配置角色"
      width="500"
      :before-close="handleClose"
    >
      <el-form
        ref="formRef"
        :model="form"
        label-width="auto"
        style="max-width: 600px"
      >
        <el-form-item label="配置角色">
          <el-select
            v-model="form.region"
            placeholder="请选择角色"
            multiple
            @change="changeRoles"
          >
            <el-option
              v-for="(item, index) in rolesList.list"
              :key="index"
              :label="item.roleName"
              :value="item.roleCode"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="saveDepartment"> 确认 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
