<script setup lang="ts">
defineOptions({
  // name 作为一种规范最好必须写上并且和路由的name保持一致
  name: "users"
});
import { ref, reactive, onMounted } from "vue";
import { ElMessageBox, ElMessage } from "element-plus";
import { Search } from "@element-plus/icons-vue";
import addPerson from "./components/addPerson.vue";
import addUsers from "./components/addUsers.vue";
import editPerson from "./components/editPerson.vue";
import { postPageGroup, postDelUserGroup } from "@/api/userGroup";
import UserPageTable from "@/components/UserPageTable/index.vue";
import pngcaret from "@/assets/icon-png/caret-right-small.svg";
import { getDeleteUserApi, postAssignmentUserApi } from "@/api/userSetting";
// 新增用户组
const addUsersRef = ref();
const addUsersShow = ref(false);
// 新增人员
const addPersonRef = ref();
const addPersonShow = ref(false);
// 编辑
const editPersonRef = ref();
const editPersonShow = ref(false);
const addPersonClick = ref();
// table表格
const UserTable = ref();
const rolesList = reactive({
  data: [],
  rolesName: "",
  params: {
    pageNumber: 1,
    pageSize: 20,
    groupName: ""
  },
  addPerson: {},
  perOne: null,
  perName: null
});
const load = () => {
  rolesList.params.pageSize += 10;
  postPageGroupApi();
};
// 用户组分页

const postPageGroupApi = async () => {
  const { code, data } = await postPageGroup(rolesList.params);
  const res = await postPageGroup({
    pageNumber: 1,
    pageSize: 20
  });
  rolesList.perOne = res.data.records[0].groupCode;
  rolesList.perName = res.data.records[0].groupName;
  if (code === 200) {
    rolesList.data = [];
    // console.log(1231231223,res);
    data.records.forEach((item, index) => {
      rolesList.data.push({
        ...item,
        id: index + 1
      });
    });
  }
};
onMounted(async () => {
  // 低网模式 等待 postPageRoleApi 完成
  await postPageGroupApi();
  if (rolesList.data.length > 0) {
    formLink.targetCodes = [];
    rolesList.rolesName = rolesList.perName;
    bgColor.value = rolesList.perOne;
    Object.assign(rolesList.addPerson, rolesList.data[0]);

    paramsItem.value = rolesList.data[0];
    formLink.targetCodes.push(rolesList.data[0].groupCode);
    await Promise.all([
      UserTable?.value?.handleNodeClick(rolesList.data[0], "group"),
      (addPersonClick.value = UserTable?.value?.handleNodeClick(
        rolesList.data[0],
        "group"
      ))
    ]);
  }
  // setTimeout(() => {

  // }, 500);
});
// 查看角色组
const paramsItem = ref();
const bgColor = ref(null);
const lookRoles = item => {
  bgColor.value = item.groupCode;
  rolesList.rolesName = item.groupName;
  Object.assign(rolesList.addPerson, item);
  UserTable?.value?.handleNodeClick(item, "group");
  addPersonClick.value = UserTable?.value?.handleNodeClick(item, "group");
  paramsItem.value = item;
  // 取消关联动作
  formLink.targetCodes = [];
  formLink.targetCodes.push(item.groupCode);
};
// 标签选择
const activeName = ref("first");

const handleClick = (tab, event) => {
  console.log(tab, event);
};
// 删除用户组
const postDelUserGroupApi = async row => {
  const { code } = await postDelUserGroup(row);
  if (code === 200) {
    postPageGroupApi();
    ElMessage({
      type: "success",
      message: "删除成功"
    });
    setTimeout(() => {
      formLink.targetCodes = [];
      rolesList.rolesName = rolesList.perName;
      bgColor.value = rolesList.perOne;
      Object.assign(rolesList.addPerson, rolesList.data[0]);
      UserTable?.value?.handleNodeClick(rolesList.data[0], "group");
      addPersonClick.value = UserTable?.value?.handleNodeClick(
        rolesList.data[0],
        "group"
      );
      paramsItem.value = rolesList.data[0];
      formLink.targetCodes.push(rolesList.data[0].groupCode);
    }, 500);
  }
};
const deleteUsers = row => {
  console.log(row);
  ElMessageBox.confirm(
    `用户组删除不能恢复，是否确认删除用户组【${row.groupName}】吗`,
    "确定删除该用户组吗？",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    }
  ).then(() => {
    postDelUserGroupApi(row);
  });
};
const AddUsersPerson = () => {
  if (rolesList.rolesName) {
    addPersonRef.value.open(rolesList.addPerson, UserTable.value.tableData);
  } else {
    ElMessage.warning("请选择用户组");
  }
};
const addUsersList = () => {
  addUsersRef.value.open();
};
// 配置角色
const changeUsers = item => {
  addUsersRef.value.open(item);
};
// 编辑
const editUsers = row => {
  editPersonRef.value.open(row);
};
// 取消关联参数
const formLink = reactive({
  sourceCodes: [],
  targetCodes: [],
  linkAction: "unlink",
  correlatedModel: "groupUser"
});
// 删除用户
const deltetePerson = row => {
  formLink.sourceCodes = [];
  ElMessageBox.confirm(
    `是否确认移除用户【${row.realName}】吗`,
    "确定移除该用户吗？",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    }
  )
    .then(() => {
      // getDeleteUserApi(
      //   row.userCode,
      //   UserTable.value.postOrganizationUserPageApi
      // );
      formLink.sourceCodes.push(row.userCode);
      postAssignmentUserApi(
        formLink,
        UserTable.value.postOrganizationUserPageApi
      );
      UserTable?.value?.handleNodeClick(row, "group");
    })
    .catch(() => {
      ElMessage({
        message: "取消删除"
      });
    });
};
const addPersonClickList = () => {
  postPageGroupApi();
  UserTable?.value?.handleNodeClick(paramsItem.value, "group");
};
</script>

<template>
  <div class="flex w-full h-full">
    <!-- 添加人员 -->
    <addPerson
      ref="addPersonRef"
      v-model="addPersonShow"
      @handleClick="addPersonClickList"
    />
    <!-- 添加用户组 -->
    <addUsers
      ref="addUsersRef"
      v-model="addUsersShow"
      @handleClick="postPageGroupApi"
    />
    <!-- 编辑 -->
    <editPerson
      ref="editPersonRef"
      v-model="editPersonShow"
      @handleClick="addPersonClickList"
    />
    <!-- 主体内容 -->
    <div class="box-left">
      <div class="w-[100%]">
        <div>
          <el-input
            v-model="rolesList.params.groupName"
            placeholder="搜索用户组"
            class="mb-2"
            clearable
            style="max-width: 300px"
            :prefix-icon="Search"
            @change="postPageGroupApi"
          />
        </div>
      </div>
      <div
        v-infinite-scroll="load"
        :infinite-scroll-immediate="false"
        class="h-2/3 w-[100%] overflow-auto infinite-list"
      >
        <div
          v-for="item in rolesList.data"
          :key="item.id"
          class="w-[100%] flex justify-between items-center"
        >
          <pngcaret class="mr-1 mt-2" />
          <div
            :class="[
              'w-[100%] flex justify-between items-center mt-2 cursor-pointer',
              { 'roles-bg': bgColor === item.groupCode }
            ]"
          >
            <div
              class="flex justify-between items-center'"
              @click="lookRoles(item)"
            >
              <span class="text-sm">{{ item.groupName }}</span>
            </div>
            <div class="flex justify-between items-center">
              <el-dropdown trigger="click">
                <span>
                  <el-icon>
                    <Operation />
                  </el-icon>
                </span>
                <template #dropdown>
                  <el-dropdown-menu class="setting">
                    <Auth :value="['编辑']">
                      <el-dropdown-item @click="editUsers(item)">
                        编辑
                      </el-dropdown-item>
                    </Auth>
                    <Auth :value="['配置角色']">
                      <el-dropdown-item @click="changeUsers(item)">
                        配置角色
                      </el-dropdown-item>
                    </Auth>
                    <Auth :value="['删除']">
                      <el-dropdown-item @click="deleteUsers(item)">
                        <el-link type="danger">删除</el-link>
                      </el-dropdown-item>
                    </Auth>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </div>
        </div>
      </div>
      <el-divider />
      <Auth :value="['新建用户组']">
        <el-button type="primary" class="addRole" plain @click="addUsersList()"
          >新增用户组</el-button
        >
      </Auth>
    </div>
    <!-- <div v-if="rolesList.rolesName" class="box-right"> -->
    <div class="box-right">
      <h3>{{ rolesList.rolesName }}</h3>
      <UserPageTable ref="UserTable">
        <template #add-button>
          <Auth :value="['添加成员']">
            <el-button type="primary" @click="AddUsersPerson"
              >添加人员</el-button
            >
          </Auth>
        </template>
        <template #actions="{ row }">
          <el-dropdown trigger="click" class="mr-2">
            <Auth :value="['移出成员']">
              <el-text type="danger" @click="deltetePerson(row)">
                移除
              </el-text>
            </Auth>
          </el-dropdown>
        </template>
      </UserPageTable>
    </div>
  </div>
</template>
<style lang="scss" scoped>
.box-left {
  position: relative;
  width: 25%;
  // border: 1px solid red;
  height: 100%;
  padding: 10px 20px;
  border-right: 1px solid #999;
}

.box-right {
  width: 70%;
  height: 100%;
  padding: 10px 20px;
}

.addRole {
  position: absolute;
  bottom: 70px;
  width: calc(100% - 50px);
}

.userName {
  background-color: #022bbd80;
}

.infinite-list {
  overflow-y: auto;
  -ms-overflow-style: none;

  /* IE和Edge */
  scrollbar-width: none;

  /* Firefox */
  // border: 1px solid red;
}

/* 隐藏滚动条 */
.infinite-list::-webkit-scrollbar {
  display: none;

  /* 对于 Webkit 浏览器（Chrome, Safari等） */
}

// ::v-deep .el-dropdown {
//   line-height: 1;
// }
// ::v-deep .el-tree-node__expand-icon {
//   line-height: 10px;
//   border: 1px solid red;
// }
.roles-bg {
  color: #0052d9;
  background-color: #0053d91a;
}

.roles-text {
  font-size: 12px;
  // font-family: PingFangSC-Regular;
  font-weight: 400;
  line-height: 22px;
  color: #000000e6;
  letter-spacing: 0;
}
</style>
