<template>
  <div>
    <div class="header">
      <div class="header-left">
        <el-input
          v-model="searchName"
          style="width: 240px"
          placeholder="搜索111"
          :prefix-icon="Search"
        />
        <el-button type="primary" class="search">搜索1</el-button>
      </div>

      <div class="header-right">
        <!-- <el-button type="warning" plain>批量删除</el-button> -->
        <el-button >批量编辑22</el-button>
        <el-button>批量导入/导出</el-button>
        <el-button type="primary" @click="addDep">+新建</el-button>
      </div>
    </div>
    <el-table
      :data="tableData"
      style="width: 100%"
      height="100%"
      :default-expand-all="true"
      row-key="departmentId"
      :border="false"
      :tree-props="{ children: 'children', hasChildren: 'true' }"
      :header-cell-style="{ background: '#f5f7fa', color: '#595F68' }"
      :default-sort="{ prop: 'sort', order: 'descending' }"
    >
      <el-table-column width="100">
        <template #default="scope">
          <el-checkbox
            v-if="scope.row.children.length == 0"
            size="large"
            @change="checkedChange(scope.row)"
          />
        </template>
      </el-table-column>
      <!-- <el-table-column prop="departmentId" label="部门Id" width="180" /> -->
      <el-table-column prop="departmentName" label="部门名称" width="180" />
      <el-table-column prop="personNum" label="部门人数" />
      <el-table-column prop="describeStr" label="部门描述" />
      <el-table-column fixed="right" label="操作" min-width="120">
        <template #default="scope">
          <el-button
          v-if="scope.row.level != 0"
            text
            size="small"
            type="primary"
            @click="detailHandle(scope.row)"
          >
            详情
          </el-button>
          <el-button
            text
            type="primary"
            size="small"
            @click="addChildHandle(scope.row)"
            >添加子部门</el-button
          >

          <el-popover placement="top-start" :width="200" trigger="hover">
            <div style="margin: 0">
              <el-button size="small" text type="primary" v-if="scope.row.sort != 1&scope.row.sort!=0" @click="upHandle(scope.row)">上移</el-button>
              <el-button size="small" type="primary"  v-if="scope.row.sort" @click="downHandle(scope.row)"> 下移 </el-button>
              <el-button size="small" type="warning" @click="deleteHandle(scope.row)"> 删除 </el-button>
            </div>
            <template #reference>
              <el-button text type="primary" size="small">
                <el-icon><MoreFilled /></el-icon
              ></el-button>
            </template>
          </el-popover>
        </template>
      </el-table-column>
    </el-table>

    <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="@/assets/images/config_depart_large.png"
              alt=""
              class="depart-img"
            />
            <span class="depart_name">{{ detailInfo.departmentName }}</span>
          </div>
          <div class="detail_item">
            <div class="name">部门名称</div>
            <div class="username">{{ detailInfo.departmentName }}</div>
          </div>
          <div class="detail_item">
            <div class="name">部门ID</div>
            <div class="username">{{ detailInfo.departmentNo }}</div>
          </div>
          <div class="detail_item">
            <div class="name">上级部门</div>
            <div class="username">{{ detailInfo.departmentName }}</div>
          </div>
        </div>
      </template>
      <template #footer>
        <div style="text-align: left">
          <el-button type="primary" @click="editInfo" size="small"
            >编辑基本信息</el-button
          >
          <el-button @click="addChildHandle" size="small">添加子部门</el-button>
          <el-button type="warning" plain @click="deleteInfo" size="small"
            >删除</el-button
          >
        </div>
      </template>
    </el-drawer>
    <AddDepartment ref="addDepRef" :parentValue="currentDep" />
  </div>
</template>

<script setup>
import { Search } from '@element-plus/icons-vue'
import { onMounted, reactive, ref,computed } from 'vue'
import { getDepartmentList, addDepartment,deleteDepartment,updateDepartmentSort } from '@/api/department'
import {ElMessageBox} from 'element-plus';
import { useUserStore } from '@/store/modules/user'
const userStore = useUserStore()
import AddDepartment from '@/components/orgChart/addDepartment.vue'
onMounted(() => {
  getList()
})
const tableData = ref([])
// const maxSort = computed(() => {
//   return Math.max(...tableData.value.map(item => item.sort));
// });

// const maxSort = () => {
//   if (tableData.value.length === 0) return 0;
//   return Math.max(...tableData.value.map(item => item.sort));
// };
// console.log(maxSort)

const getList = () => {
  // console.log('getList',tableData)
  tableData.value=[]
  getDepartmentList()
    .then(res => {
      if (res.data.code == 200) {
        // tableData.value.splice(0, tableData.value.length, res.data.data)
        tableData.value.push(res.data.data)
        console.log('123123s')
        console.log(tableData)
      }
    })
    .catch(err => {
      console.log(err)
    })
}
// const customSortMethod = (a, b) => {
//   return b.sort - a.sort;
// };
const checkedChange = row => {
  console.log(row)
}
//新建部门
const addDep = () => {
  userStore.addDepartmentId=null;
  if (addDepRef.value) {
    addDepRef.value.addChildHandle()
  }
}
//查询部门
const searchName = ref('')

//添加子部门
const currentDep = ref(null)
const addDepRef = ref(null)
const addChildHandle = row => {
  console.log('添加子部门')
  console.log(row)
  //currentDep.value = row.departmentId
  userStore.addDepartmentId=row.departmentId;
  if (addDepRef.value) {
    addDepRef.value.addChildHandle()
  }
}

//详情查看
const detailVisible = ref(false)
const detailInfo = ref(null)
const detailHandle = row => {
  console.log('Row clicked:', row)
  detailInfo.value = row
  detailVisible.value = true
}
const closeDetailDrawer = () => {
  detailVisible.value = false
}

//更多操作


//删除
const deleteHandle = row => {
  console.log(row)
  if(row.hasChildren){
    ElMessageBox.alert('该部门有子部门，无法删除', '', {
      confirmButtonText: '确定',
      type: 'warning',
    })
  }else{
    ElMessageBox.confirm('确定删除该部门？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(() => {

      deleteDepartment(row.departmentId)
        .then(res => {
          if (res.data.code == 200) {
            ElMessageBox.alert('删除成功', '提示', {})
            getList()
          }
        })

      })
  }
  }
//上移
const upHandle = row => {
  console.log(row)
  updateDepartmentSort(row.departmentId,row.sort)
    .then(res => {
      if (res.data.code == 200) {
        ElMessageBox.alert('上移成功', '提示', {})
        getList()
      }
    })

}
//下移
const downHandle = row => {
  console.log(row)
  updateDepartmentSort(row.departmentId,row.sort)
    .then(res => {
      if (res.data.code == 200) {
        ElMessageBox.alert('下移成功', '提示', {})
        getList()
      }
    })
}

const editInfo = () => {}
const deleteInfo = () => {
  deleteHandle(detailInfo.value)
}
</script>
<style scoped lang="scss">
.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;
}
.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;
  }
}
.search {
  margin-left: 10px;
}
</style>
