<template lang="">
  <div>
    <div class="common-layout">
      <div class="showIcon2" v-if="!show">
        <!-- <el-icon :size="20" @click="isShow" class="location_icon"
          ><Expand
        /></el-icon> -->
        <img src="@/assets/icons/zkdh.svg" alt=""  @click="isShow" class="location_icon_1">

      </div>
      <div class="showIcon" v-if="show">
        <!-- <el-icon :size="20" @click="isShow" class="location_icon_1"
          ><Fold
        /></el-icon> -->
        <img src="@/assets/icons/sqdh.svg" alt=""  @click="isShow" class="location_icon_1">
        
      </div>
      <el-container>
        <transition name="el-fade-in">
          <el-aside width="240px" v-show="show">
            <div class="el-aside_div">
              <el-input
                v-model="searchDepartmentName"
                style="width: 200px"
                placeholder="搜索"
              >
                <template #suffix>
                  <el-icon class="el-input__icon" @click="getDepName"
                    ><search
                  /></el-icon>
                </template>
              </el-input>
              <el-button
                class="el-button_one"
                :icon="Plus"
                @click="addDepHandle"
                >新建部门</el-button
              >
              <el-tree
                style="max-width: 240px"
                :data="treeData"
                :props="defaultProps"
                @node-click="handleNodeClick"
                @node-contextmenu="handleContextMenu"
              >
                <template #default="{ node, treeData }">
                  <span class="custom-tree-node">
                    <span>{{ node.label }}</span>
                    <span>
                      <el-icon @click="showMore(treeData)"
                        ><MoreFilled
                      /></el-icon>
                    </span>
                  </span>
                </template>
              </el-tree>
<div
  v-if="contextMenuVisible"
  class="custom-context-menu"
  :style="{
    left: contextMenuPosition.x + 'px',
    top: contextMenuPosition.y + 'px'
  }"
>
<div class="menu-item" @click="handleCommand('edit')">编辑部门</div>
<div class="menu-item" @click="handleCommand('add')">添加子部门</div>
<div class="menu-item divided" @click="handleCommand('delete')">删除部门</div>
</div>
            </div>
          </el-aside>
        </transition>
        <el-main style="border-left: solid 1px #dee0e3;padding-left:10px">
          <text style="font-weight: bolder">{{ title }}</text>
          <span
            style="margin-left: 10px; font-size: 16px; display: inline-block"
            >总人数 {{ title_number }}</span
          >
          <div class="el-main_div" style="margin-top: 10px">
            <div>
              <el-select
                v-model="searchState"
                placeholder="选择搜索状态"
                style="width: 140px"
                clearable
              >
                <template #label="{ value }">
                  <span>状态 : </span>
                  <span style="font-weight: bold">{{ value }}</span>
                </template>
                <el-option
                  v-for="item in searchOptions"
                  :key="item.label"
                  :label="item.label"
                  :value="item.label"
                />
              </el-select>
              <el-input
                v-model="searchUserName"
                style="width: 200px"
                placeholder="请搜索姓名/编号"
              >
                <template #suffix>
                  <el-icon class="el-input__icon" @click="getUserName"
                    ><search
                  /></el-icon>
                </template>
              </el-input>
              <!-- <el-button style="margin-left: 10px" :icon="Edit" /> -->
            </div>
            <div style="margin-right: 10px">
              <el-button plain type="warning" @click="firedMemberHandle"
                >操作离职</el-button
              >
              <el-button plain @click="updateDepartmentHandle"
                >变更部门</el-button
              >
              <el-button plain>批量导入/导出</el-button>
              <el-button :icon="Plus" type="primary" @click="addMemberHandle"
                >添加</el-button
              >
            </div>
          </div>
          <div class="el-main_table">
            <el-table
              ref="multipleTableRef"
              :data="tableData"
              style="width: 100%"
              @selection-change="handleSelectionChange"
            >
              <el-table-column type="selection" width="55" />
              <el-table-column property="userNo" label="用户ID" width="120" />
              <el-table-column property="name" label="姓名" />
              <el-table-column property="userTel" label="联系手机号" />
              <el-table-column property="departmentName" label="部门" />
              <el-table-column label="用户角色">
                <template #default="scope">
                  <el-tag
                    :type="
                      scope.row.roleNames.includes('admin') ? 'success' : 'info'
                    "
                    >{{
                      scope.row.roleNames.includes('admin')
                        ? '管理员'
                        : '普通用户'
                    }}</el-tag
                  >
                </template>
              </el-table-column>
              <el-table-column label="状态">
                <template #default="scope">
                  <el-tag :type="scope.row.state == 1 ? 'success' : 'info'">{{
                    scope.row.state == 1 ? '在职' : '离职'
                  }}</el-tag>
                </template>
              </el-table-column>

              <el-table-column label="操作" fixed="right">
                <template #default="scope">
                  <el-button
                    plain
                    type="primary"
                    size="small"
                    text
                    @click="detailHandle(scope.row)"
                    >详情</el-button
                  >
                  <el-button plain type="primary" size="small" text
                    ><el-icon><MoreFilled /></el-icon
                  ></el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div style="display: flex; justify-content: flex-end">
            <myPagination
              v-model:currentPage="currentPage"
              v-model:total="total"
              v-model:pageSize="pageSize"
              :pageSizes="[10, 20, 30, 50]"
              @change="getList"
            />
          </div>
        </el-main>
      </el-container>
      <el-drawer v-model="detailVisible" :show-close="false">
        <template #header>
          <div class="header-title">
            <div>成员详情</div>
            <el-icon @click="closeDetailDrawer"><Close /></el-icon>
          </div>
        </template>
        <template #default>

        <div >
          <div class="depart">
            <img
              :src="detailInfo.headImg"
              alt=""
              class="depart-img"
            />
            <div class="detail_item" >
              <div class="depart_name">{{ detailInfo.name }}</div>
              <div class="username2">{{ '用户id：'+ detailInfo.userId }}</div>
            </div>
<!--            <span class="depart_name">{{ detailInfo.name }}</span><br/>
            <span>{{ '用户id：'+ detailInfo.userId }}</span>-->
          </div>
          <el-tabs
            v-model="activeName"
            @tab-click="handleClick"
          >
            <el-tab-pane label="资源转移记录" name="first"></el-tab-pane>
            <el-tab-pane label="成员信息" name="second"></el-tab-pane>
          </el-tabs>
          <div v-if="activeName==='first'">转移记录</div>
          <div v-if="activeName==='second'">
            <el-row>
              <el-col :span="12">
                <div class="detail_item" >
                  <div class="name">姓名</div>
                  <div class="username">{{ detailInfo.name }}</div>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="detail_item">
                  <div class="name">别名</div>
                  <div class="username">{{ detailInfo.nickName !=undefined? detailInfo.nickName : '-'}}</div>
                </div>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <div class="detail_item">
                  <div class="name">用户id</div>
                  <div class="username">{{ detailInfo.userId }}</div>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="detail_item">
                  <div class="name">手机号码</div>
                  <div class="username">{{ detailInfo.userTel }}</div>
                </div>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <div class="detail_item">
                  <div class="name">联系邮箱</div>
                  <div class="username">{{ detailInfo.email }}</div>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="detail_item">
                  <div class="name">部门</div>
                  <div class="username">{{ detailInfo.departmentName }}</div>
                </div>
              </el-col>
            </el-row>
            <div class="detail_item">
              <div class="name">性别</div>
              <div class="username">{{ detailInfo.sex==1 ? '男':'女'}}</div>
            </div>
          </div>
        </div>
        </template>
        <template #footer>
          <div style="text-align: left">
            <el-button type="primary" @click="editInfo" size="small"
              >编辑基本信息</el-button
            >
            <el-button @click="changeDepHandle" size="small"
              >变更部门</el-button
            >
            <el-button @click="transferHandle" size="small">权限转移</el-button>
            <el-button type="warning" plain @click="deleteInfo" size="small"
              >操作离职</el-button
            >
          </div>
        </template>
      </el-drawer>
      <AddDepartment ref="addDepRef" @getList="getList" />
      <AddMember ref="addMemberRef" @getList="getList" />
      <!-- 变更部门 -->
      <el-dialog
        v-model="updateDepVisible"
        title="批量编辑"
        width="500"
        align-center
      >
        <span style="display: inline-block; margin-bottom: 10px"
          >当前部门：</span
        >
        <el-input v-model="currentDepName" disabled />
        <span style="display: inline-block; margin: 10px 0"
          >请重新选择部门：</span
        >
        <el-select
          v-model="selectedDepId"
          clearable
          filterable
          placeholder="请选择部门"
        >
          <el-option
            v-for="item in depList"
            :key="item.departmentId"
            :label="item.departmentName"
            :value="item.departmentId"
          />
        </el-select>

        <template #footer>
          <div class="dialog-footer">
            <el-button @click="canUpdateDep">取消</el-button>
            <el-button type="info" @click="conUpdateDep"> 确认 </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>
<script setup>
import { ref, onMounted, reactive } from 'vue'
import { Search, Plus, Edit } from '@element-plus/icons-vue'
import { getMemberList, firedMember,updateUserDepartment } from '@/api/member'
import myPagination from '@/components/Paginations.vue'
import AddDepartment from '@/components/orgChart/addDepartment.vue'
import AddMember from '@/components/orgChart/addMember.vue'
import { ElMessageBox ,ElMessage} from 'element-plus'
import { getDepartmentNameBottom  } from '@/api/department'
import { useUserStore } from '@/store/modules/user'
const userStore = useUserStore()
onMounted(() => {
  getList()
})
//分页
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(10)

const show = ref(true)
function isShow() {
  if (show.value) {
    show.value = false
  } else {
    show.value = true
  }
}

const tableData = ref([])
const responseData = ref([])

const treeData = reactive([])
const getList = data => {
  getMemberList({
    state: 1,
    departmentName: data,
    pageNum: currentPage.value,
    pageSize: pageSize.value,
  }).then(res => {
    if (res.data.code == 200) {
      responseData.value = res.data.data
      treeData.splice(0, treeData.length, res.data.data.department)
      title.value = treeData[0].departmentName
      title_number.value = treeData[0].personNum
      total.value = res.data.data.user.total
      tableData.value = res.data.data.user.records
    }
  })
}
const showMore = data => {
  console.log(data)
}

const title = ref('')
const title_number = ref('')
const defaultProps = {
  children: 'children',
  label: 'departmentName',
}

const searchUserName = ref('')
const totalNum = ref('')
const handleNodeClick = event => {
  title.value = event.departmentName
  title_number.value = event.personNum
  getMemberList({ departmentName: event.departmentName }).then(res => {
    if (res.data.code == 200) {
      console.log(res.data.data)
      totalNum.value = res.data.data.user
      tableData.value = res.data.data.user.records
      // tableData.value = res.data.data.user.records
    }
  })
  console.log(event)
}
const selectedRowKeys = ref(null)
const handleSelectionChange = val => {
  console.log(val)
  //取到val最后一个元素
  selectedRowKeys.value = val[val.length - 1]
  console.log(selectedRowKeys.value)
}
const firedParams = ref({
  userId: '',
  operType: 1,
  fireSourceOpVos: [
    {
      type: 1,
      fromUserId: 10002,
      toUserId: 10000,
    },
  ],
})
//操作离职按钮
const firedMemberHandle = () => {
  firedParams.value.userId = selectedRowKeys.value.userId
  firedParams.value.fireSourceOpVos[0].fromUserId = selectedRowKeys.value.userId
  ElMessageBox.confirm('确定移除成员？', 'Warning', {
    title: '提示',
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      firedMember(firedParams.value).then(res => {
        if (res.data.code == 200) {
          selectedRowKeys.value = null
          getList()
        }
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: 'Delete canceled',
      })
    })
}

//操作离职
const deleteInfo = () => {
  firedParams.value.userId = detailInfo.value.userId
  firedParams.value.fireSourceOpVos[0].fromUserId = detailInfo.value.userId
  ElMessageBox.confirm('确定移除成员？', 'Warning', {
    title: '提示',
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      firedMember(firedParams.value).then(res => {
        if (res.data.code == 200) {
          detailVisible.value = false
          getList()
        }
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: 'Delete canceled',
      })
    })
}
//变更部门
const updateDepVisible = ref(false)
const selectedDepId = ref('')
const currentDepName = ref('')
const updateDepartmentHandle = () => {
  if (selectedRowKeys.value) {
    updateDepVisible.value = true
    currentDepName.value = selectedRowKeys.value.departmentName
    getSelectableDepName()
  } else {
    ElMessage({
      type: 'warning',
      message: '请选择要操作的成员',
    })
  }
}
const getSelectableDepName = () => {
  getDepartmentNameBottom().then(res => {
    depList.value = res.data.data
  })
}

const conUpdateDep = () => {
  updateUserDepartment({userId:selectedRowKeys.value.userId, departmentId:selectedDepId.value}).then(
    res => {
      // console.log(res)
      if (res.data.code == 200) {
        updateDepVisible.value = false
        selectedDepId.value = ''
        currentDepName.value = ''
        detailVisible.value = false
        getList()
      }
    }
  )
}
const canUpdateDep = () => {
  updateDepVisible.value = false
  selectedDepId.value = ''
}
//详情里面变更部门
const changeDepHandle=() =>{
  updateDepVisible.value = true
  currentDepName.value = detailInfo.value.departmentName
  selectedRowKeys.value = detailInfo.value
  getSelectableDepName()
  console.log(selectedRowKeys.value)
}

//新建部门
const depList = ref([])
const addDepRef = ref(null)
const addDepHandle = () => {
  if (addDepRef.value) {
    addDepRef.value.addChildHandle()
  }
}
//搜索部门
const searchDepartmentName = ref('')
const getDepName = () => {
  getList(searchDepartmentName.value)
}

//搜索人员名称
const searchState = ref('')
const searchOptions = ref([
  {
    value: 'name',
    label: '姓名',
  },
  {
    value: 'userNo',
    label: '编号',
  },
])

const searchUser = data => {
  getMemberList(data).then(res => {
    if (res.data.code == 200) {
      responseData.value = res.data.data.user
      tableData.value = res.data.data.user.records
    }
  })
}

const getUserName = () => {
  console.log(searchState.value)
  if (searchState.value == '姓名') {
    searchUser({ userName: searchUserName.value })
  } else {
    searchUser({ userNo: searchUserName.value })
  }
}
//添加人员
const addMemberRef = ref(null)
const addMemberHandle = () => {
  console.log(111)
  if (addMemberRef.value) {
    addMemberRef.value.addChildHandle('add')
  }
}

//详情查看
const activeName=ref('first')
const detailVisible = ref(false)
const detailInfo = ref(null)
const detailHandle = row => {
  console.log('Row clicked:', row)
  detailInfo.value = row
  userStore.selectedMember=row;
  detailVisible.value = true
}
const closeDetailDrawer = () => {
  detailVisible.value = false
}
const contextMenuVisible = ref(false)
const contextMenuPosition = reactive({
  x: 0,
  y: 0
})
const currentNode = ref(null)

const handleContextMenu = (event, data, node) => {
  event.preventDefault()
  contextMenuVisible.value = true
  contextMenuPosition.x = event.clientX
  contextMenuPosition.y = event.clientY
  currentNode.value = { data, node }
}

// 统一的命令处理函数
const handleCommand = (command) => {
  switch (command) {
    case 'edit':
      console.log('编辑部门', currentNode.value)
      break
    case 'add':
      console.log('添加子部门', currentNode.value)
      break
    case 'delete':
      console.log('删除部门', currentNode.value)
      break
  }
  contextMenuVisible.value = false
}

// 点击其他地方关闭菜单
onMounted(() => {
  document.addEventListener('click', () => {
    contextMenuVisible.value = false
  })
})

function editInfo(){
  if (addMemberRef.value) {
    addMemberRef.value.addChildHandle('update')
  }
}
</script>
<style lang="scss" scoped>
.demo-pagination-block + .demo-pagination-block {
  margin-top: 10px;
}
.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}
.common-layout {
  .el-aside {
    height: 100%;
    .el-aside_div {
      display: flex;
      flex-direction: column;
      .el-button_one {
        width: 240px;
        margin-top: 10px;
        height: 30px;
        color: black;
        line-height: 40px;
        margin-bottom: 10px;
      }
      .custom-tree-node {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 14px;
        padding-right: 8px;
      }
    }
  }
  .el-main {
    padding: 0;
    height: 700px;
    overflow: hidden;
    .el-main_div {
      display: flex;
      justify-content: space-between;
    }
    .el-main_table {
      height: 600px;
    }
  }
}
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin: 16px 0;
  .header-left {
    display: flex;
    align-items: center;
  }
  .header-right {
    display: flex;
    align-items: center;
  }
}
.header-title {
  font-family:
    PingFang SC,
    PingFang SC;
  font-weight: bold;
  font-size: 18px;
  color: #1f2329;
  display: flex;
  align-items: self-start;
  justify-content: space-between;
  border-bottom: 1px solid #ebeef5;
  height: 40px;
}
:deep(.el-drawer__header) {
  margin-bottom: 0 !important;
}
.depart {
  display: flex;
  align-items: center;
}
.depart-img {
  width: 54px;
  height: 54px;
  margin-right: 10px;
  border-radius: 50%;
}
.depart_name {
  font-size: 18px;
  color: #202328;
  font-weight: bold;
}
.detail_item {
  height: 48px;
  margin: 30px 0 20px 0;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  .name {
    font-size: 14px;
    color: #656b73;
  }
  .username {
    font-size: 14px;
    color: #1f2329;
    font-weight: 500;
  }
}
.label {
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  align-items: center;
  gap: 4px;
  margin-bottom: 8px;
  font-size: 14px;
  color: #1f2329;
  .red {
    color: #ff3535;
  }
}
.showIcon {
  width: 20px;
  height: 40px;
  line-height: 50px;
  position: absolute;
  top: 140px;
  left: 343px;
  z-index: 2;
  border-left: solid 1px #dee0e3;
  border-top: solid 1px #dee0e3;
  border-bottom: solid 1px #dee0e3;
  border-radius: 2px;
}
.showIcon2 {
  width: 20px;
  height: 40px;
  line-height: 50px;
  position: absolute;
  top: 140px;
  left: 85px;
  z-index: 2;
  border-top: solid 1px #dee0e3;
  border-bottom: solid 1px #dee0e3;
  border-radius: 2px;
}
.location_icon {
  color: #4e5969;
  font-size: 20px;
  font-weight: lighter;
}
.location_icon_1 {
  color: #4e5969;
  font-size: 20px;
  font-weight: lighter;
}
.custom-context-menu {
  position: fixed;
  background: white;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
  padding: 5px 0;
  z-index: 3000;
  min-width: 120px;

  .menu-item {
    padding: 8px 20px;
    font-size: 14px;
    color: #606266;
    cursor: pointer;

    &:hover {
      background-color: #f5f7fa;
      color: #409eff;
    }

    &.divided {
      border-top: 1px solid #dcdfe6;
      margin-top: 5px;
      padding-top: 5px;
    }
  }
}
</style>
