<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 form = reactive({
  name: "",
  region: "",
  date1: "",
  date2: "",
  delivery: false,
  type: [],
  resource: "",
  desc: ""
});
const handleClose = () => {
  ElMessageBox.confirm("确认关闭弹窗吗？")
    .then(() => {
      dialogVisibleAdd.value = !dialogVisibleAdd.value;
      ElMessage({
        message: "已关闭",
        type: "success"
      });
    })
    .catch(() => {
      // catch error
    });
};
const rolesList = reactive({
  list: [],
  assignmentParams: {
    sourceCodes: [],
    targetCodes: [],
    linkAction: "link",
    correlatedModel: "deptRole"
  },
  rolesName: ""
});
const postAddUserGroupApi = async () => {
  const { code } = await postAssignmentUser(rolesList.assignmentParams);
  if (code === 200) {
    ElMessage({
      message: "添加成功",
      type: "success"
    });
  }
};

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

<template>
  <div>
    <el-dialog
      v-model="dialogVisibleAdd"
      title="配置角色"
      width="500"
      :before-close="handleClose"
    >
      <el-form :model="form" label-width="auto" style="max-width: 600px">
        <el-form-item label="配置角色">
          <el-select
            v-model="form.region"
            placeholder="请选择角色"
            @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>
