<template>
  <MOSTY.PageTree :pageCurrentTitle="'分配用户'" :isShowLeftTree="false">
    <template #serach>
      <el-divider />
      <MOSTY.Search :searchArr="searchArr" @submit="onSearch" />
      <el-divider />
      <div class="btnBox">
        <el-button type="primary" @click="addUser">
          <el-icon>
            <CirclePlus />
          </el-icon>
          <span>添加用户</span>
        </el-button>
        <router-link to="/systemConfig/role-list" style="margin-left: 10px;">
          <el-button type="primary" @click="CloseEvent">
            <el-icon>
              <ArrowLeft />
            </el-icon>
            <span>返回</span>
          </el-button>
        </router-link>
      </div>
    </template>
    <template #table>
      <div style="height:calc(100vh - 342px);">
        <MOSTY.Table :table-columns="tableColumns" :tableData="tableData" :isSelect="false" :isSort="true"
          :actionsW='"350"'>
          <template #actions="{ row }">
            <el-popconfirm confirm-button-text="确定" cancel-button-text="取消" icon-color="red" title="确定要删除?"
              @confirm="unbundleRole(row)">
              <template #reference>
                <el-button type="danger" pageCurrentSize="small">取消授权</el-button>
              </template>
            </el-popconfirm>
          </template>
        </MOSTY.Table>

      </div>
      <div class="fenye">
        <MOSTY.Pages :pageConfiger="listQuery" @changeNo="handleCurrentChange" @changeSize="handleSizeChange" />
      </div>
    </template>

  </MOSTY.PageTree>
  <ChooseUser v-model="chooseUserVisible" :roleId="route.query.id" :Single="false" :data="tableData"
    :deptId="ChooseUserdeptId" @choosedUsers="saveUsers"></ChooseUser>
</template>

<script setup>
import * as MOSTY from "@/components/MyComponents/index";
import ChooseUser from "@/components/MyComponents/ChooseUser";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { onMounted, ref, watch, reactive } from "vue";
import { useStore } from "vuex"
import { getItem } from "@/utils/storage";
import { batchUnboundUserRole, getRoleUserList, grantUserToRole } from "@/api/user-manage";
const router = useRouter()
const route = useRoute();
const store = useStore()
const searchArr = reactive([
  {
    showType: "input",
    prop: "userName",
    lable: '用户名',
    width: '250px',
    placeholder: "请输入角色名称"
  }
]);
const total = ref(0);
const listQuery = ref({
  pageCurrent: 1,
  pageCurrentSize: 20,
  total: 0,
  userName: "",
  phone: ""
});
const ChooseUserdeptId = ref(getItem("deptId").ssbmid);
const currentUserId = ref("");
const roleDialogVisible = ref(false);
const chooseUserVisible = ref(false);
// 数据相关
const tableData = ref([]);
const tableColumns = reactive([
  {
    title: "用户名",
    prop: "userName",
  },
  {
    title: "账号",
    prop: "loginName",
  },
  {
    title: "部门",
    prop: "deptName",
  },
  {
    title: "操作",
    prop: "actions",
    slot: true
  }
])
//watch监听路由变化
watch(roleDialogVisible, (val) => {
  if (!val) currentUserId.value = "";
});
onMounted(() => {
  getListData();
});
// 获取数据的方法
const getListData = async () => {

  const params = listQuery.value;
  params.current = params.pageCurrent;
  params.roleId = route.query.id;
  const res = await getRoleUserList(params);
  tableData.value = res?.records;
  listQuery.value.total = Number(res.total);
};
const onSearch = (obj) => {
  listQuery.value.userName = obj.userName
  listQuery.value.pageCurrent = 1;
  getListData();
};

// pageCurrentSize 分页相关 改变触发
const handleSizeChange = (currentSize) => {
  listQuery.value.pageCurrentSize = currentSize;
  getListData();
};

// 页码改变触发
const handleCurrentChange = (currentPage) => {
  listQuery.value.pageCurrent = currentPage;
  getListData();
};

const unbundleRole = (row) => {
  let params = {
    ids: [row.id]
  };
  batchUnboundUserRole(params).then(() => {
    ElMessage.success("操作成功");
    getListData();
  });
};
const addUser = () => {
  chooseUserVisible.value = true;
};

//批量添加用户
const saveUsers = (users) => {
  if (users.length > 0) {
    let userIds = users.map((item) => item.id);
    let params = {
      roleId: route.query.id,
      userIds: userIds
    };
    grantUserToRole(params).then((res) => {
      ElMessage.success("操作成功");
      getListData();
    });
  }
};
function CloseEvent() {
  let arr = store.getters.tagsViewList;
  for (let i = 0; i < arr.length; i++) {
    const e = arr[i];
    if (e.path == '/user/allocationUser') {
      arr.splice(i, 1);
    }
  }
  router.push("/systemConfig/role-list");
}
</script>

<style lang="scss" scoped>
.btnBox {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  margin-bottom: 12px;
}

.el-dialog {
  height: 450px !important;
}
</style>
