<script setup>
import { apiSystemDepart } from '@/api/system'
import { InfoFilled, Plus } from '@element-plus/icons-vue'
import { ElMessageBox } from 'element-plus'

const emits = defineEmits(['change'])

const departTreeKeys = {
  label: 'SysDepartmentName',
  children: 'Child'
}
const departOpts = ref([])
const departActive = defineModel('departActive')//当前选中的分类
async function getDepartList() {
  const res = await apiSystemDepart.departList()
  if (res.Ret !== 200) return
  const list = res.Data.List || []
  departOpts.value = list
}
getDepartList()
function initDepart() {
  departOpts.value = []
  departActive.value = ''
  emits('change')
  getDepartList()
}


function handleDepartActiveChange(data, node) {
  departActive.value = data.SysDepartmentId
  emits('change')
}
// 控制分类操作按钮显示
function showClassifyOpt(node, data) {
  return (departActive.value === data.SysDepartmentId)
}
function allowDrag() {

  return true
}
function allowDrop(draggingNode, dropNode, type) {
  // 仅支持同部门下,同级节点相互排序
  let canDrop = false
  if (draggingNode.level === dropNode.level && draggingNode.data.ParentId === dropNode.data.ParentId && type !== 'inner') {
    canDrop = true
  }
  return canDrop
}
function handleDropOver(b, a, i, e) {
  // 被拖拽节点对应的 Node、结束拖拽时最后进入的节点、被拖拽节点的放置位置
  const treeData = departOpts.value || []
  const params = {
    DepartmentIds1: [],
    DepartmentIds2: [],
    DepartmentIds3: []
  }
  if (b.level === 1) {
    params.DepartmentIds1 = treeData.map(i => i.SysDepartmentId)
  } else {
    const arr = a.parent.data.Child || []
    const ids = arr.map(i => i.SysDepartmentId)
    params.DepartmentIds2 = b.level === 2 ? ids : []
    params.DepartmentIds3 = b.level === 3 ? ids : []
  }

  console.log(params);
  apiSystemDepart.departSort(params).then(res => {
    if (res.Ret === 200) {
      ElMessage.success('移动排序成功')
    }
  })
}

function handleDepartDel(data) {
  console.log(data);
  apiSystemDepart.departDel({
    SysDepartmentId: data.SysDepartmentId,
    Level: data.Level,
  }).then(res => {
    if (res.Ret === 200) {
      ElMessage.success('删除成功')
      initDepart()
    }
  })
}

const showEditDepart = ref(false)
const formRules = {
  departName: [{ required: true, message: '请输入名称', trigger: 'blur' }]
}
const formRef = ref(null)
const formState = reactive({
  type: 1,//1 新建部门，2编辑部门，3编辑分组名，4新增分组
  departId: 0,
  level: 1,
  departName: '',
  groupArr: [],
})
let saveTagInput = ref(null)
let inputVisible = ref(false)
let inputValue = ref('')
function showInput() {
  inputVisible.value = true;
  nextTick(() => {
    saveTagInput.value?.input.focus();
  });
}
function InputConfirm() {
  if (inputValue.value) {
    formState.groupArr.push({
      SysDepartmentName: inputValue.value
    })
  }
  inputVisible.value = false
  inputValue.value = '';
}

async function handleSave() {
  await formRef.value.validate()
  if (formState.type == 1) {
    handleAddDepart()
    return
  } else if ([2, 3].includes(formState.type)) {
    handleEditDepart()
    return
  } else {
    handleAddGroup()
  }
}
function handleAddDepart() {
  apiSystemDepart.departAdd({
    SysDepartmentId: 0,
    SysDepartmentNames: [formState.departName],
    level: 1
  }).then(res => {
    if (res.Ret === 200) {
      ElMessage.success('新建成功')
      initDepart()
      showEditDepart.value = false
    }
  })
}
function handleEditDepart() {
  apiSystemDepart.departEdit({
    SysDepartmentId: formState.departId,
    SysDepartmentName: formState.departName,
  }).then(res => {
    if (res.Ret === 200) {
      ElMessage.success('编辑成功')
      initDepart()
      showEditDepart.value = false
    }
  })
}
function handleAddGroup() {
  const arr = formState.groupArr?.map(i => i.SysDepartmentName) || []
  if (arr.length === 0) {
    ElMessage.warning('请填写分组')
    return
  }
  apiSystemDepart.departAdd({
    SysDepartmentId: formState.departId,
    SysDepartmentNames: arr,
    level: formState.level + 1
  }).then(res => {
    if (res.Ret === 200) {
      ElMessage.success('新建成功')
      initDepart()
      showEditDepart.value = false
    }
  })
}


function handleDepartOpt(node, data, type) {
  if (type === 'del') {
    ElMessageBox.confirm(
      '确定要删除该部门分组吗？',
      '提示'
    ).then(() => {
      handleDepartDel(data)
    }).catch(() => { })

    return
  }
  if (type === 'add') {
    formState.departId = data.SysDepartmentId
    formState.level = data.Level
    formState.departName = data.SysDepartmentName
    if (data.SysDepartmentId === 0) {
      formState.type = 1
    } else {
      formState.type = 4
      const arr = data.Child || []
      formState.groupArr = arr.map(i => {
        return {
          SysDepartmentName: i.SysDepartmentName
        }
      })
    }
    showEditDepart.value = true
    return
  }
  if (type === 'edit') {
    formState.departId = data.SysDepartmentId
    formState.level = data.Level
    formState.departName = data.SysDepartmentName
    if (data.Level === 1) {
      formState.type = 2
    } else {
      formState.type = 3
    }
    showEditDepart.value = true
    return
  }
}
function getFormTitle(e) {
  const map = new Map([
    [1, '新建部门'],
    [2, '编辑部门'],
    [3, '编辑分组'],
    [4, '添加分组']
  ])
  return map.get(e)
}


</script>

<template>
  <div class="depart-tree-wrap">
    <div class="company_top" @click="initDepart">
      <span>部门管理</span>
    </div>
    <el-button
      v-permission="'department:add'"
      type="primary"
      block
      :icon="Plus"
      @click="
        handleDepartOpt(
          {},
          { Level: 1, SysDepartmentId: 0, SysDepartmentName: '' },
          'add'
        )
      "
      >添加部门</el-button
    >
    <div class="tree-wrap">
      <el-tree
        class="depart_tree"
        :data="departOpts"
        :props="departTreeKeys"
        :current-node-key="departActive"
        draggable
        check-on-click-node
        :expand-on-click-node="false"
        node-key="SysDepartmentId"
        check-strictly
        highlight-current
        empty-text="暂无部门"
        @current-change="handleDepartActiveChange"
        :allow-drop="allowDrop"
        :allow-drag="allowDrag"
        @node-drop="handleDropOver"
      >
        <template #default="{ node, data }">
          <div class="depart-item-box">
            <div class="label">{{ node.label }}</div>
            <div class="opt-box" v-show="showClassifyOpt(node, data)">
              <svg-icon
                name="edit2"
                size="16px"
                v-if="hasPermission('department:edit')"
                @click.stop="handleDepartOpt(node, data, 'edit')"
              ></svg-icon>
              <el-dropdown>
                <svg-icon
                  name="menu"
                  size="16px"
                  style="margin-right: 10px"
                ></svg-icon>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item
                      v-if="hasPermission('department:delete')"
                      @click.stop="handleDepartOpt(node, data, 'del')"
                      >删除部门</el-dropdown-item
                    >
                    <el-dropdown-item
                      v-if="node.level < 3&&hasPermission('department:add')"
                      @click.stop="handleDepartOpt(node, data, 'add')"
                      >添加部门分组</el-dropdown-item
                    >
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </div>
        </template>
      </el-tree>
    </div>
  </div>
  <!-- 新增一级部分弹窗 -->
  <el-dialog v-model="showEditDepart" width="500" draggable>
    <template #header>
      <div style="display: flex; align-items: center">
        <el-icon size="20px">
          <i-ep-CirclePlus v-if="[1, 4].includes(formState.type)" />
          <i-ep-Edit v-else />
        </el-icon>
        <span>{{ getFormTitle(formState.type) }}</span>
      </div>
    </template>
    <el-form :model="formState" :rules="formRules" ref="formRef">
      <el-form-item
        :label="formState.type == 3 ? '分组' : '部门'"
        prop="departName"
        v-if="formState.type != 4"
      >
        <el-input
          v-model="formState.departName"
          placeholder="请填写名称"
        ></el-input>
      </el-form-item>
      <!-- 添加分组 -->
      <el-form-item label="部门" v-if="formState.type == 4">
        <span>{{ formState.departName }}</span>
      </el-form-item>
      <el-form-item label="分组" prop="group" v-if="formState.type == 4">
        <el-tag
          :key="index"
          v-for="(tag, index) in formState.groupArr"
          closable
          :disable-transitions="false"
          @close="formState.groupArr.splice(index, 1)"
          style="margin-right: 5px; margin-bottom: 5px"
        >
          {{ tag.SysDepartmentName }}
        </el-tag>
        <el-input
          class="input-new-tag"
          v-if="inputVisible"
          v-model="inputValue"
          placeholder="分组名"
          ref="saveTagInput"
          size="small"
          style="width: 120px; margin-right: 5px; margin-bottom: 5px"
          @keyup.enter="InputConfirm"
          @blur="InputConfirm"
        >
        </el-input>
        <el-button
          v-else
          style="margin-right: 5px; margin-bottom: 5px"
          size="small"
          @click="showInput"
          >+添加分组</el-button
        >
      </el-form-item>

      <div style="text-align: center">
        <el-button type="primary" @click="handleSave">保存</el-button>
        <el-button type="primary" plain @click="showEditDepart = false"
          >取消</el-button
        >
      </div>
    </el-form>
  </el-dialog>
</template>

<style lang="scss" scoped>
.depart-tree-wrap {
  background-color: #fff;
  min-width: 200px;
  width: 16%;
  padding: 20px;
  border-radius: 4px;
  height: calc(100vh - 120px);
  display: flex;
  flex-direction: column;
  .company_top {
    font-weight: bold;
    font-size: 18px;
    margin-bottom: 10px;
  }
  .tree-wrap {
    padding-top: 30px;
    flex: 1;
    overflow-y: auto;
    .depart-item-box {
      flex: 1;
      display: flex;
      align-items: center;
      gap: 0 10px;
      overflow: hidden;
      .label {
        flex: 1;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      .opt-box {
        display: flex;
        gap: 0 10px;
        flex-shrink: 0;
      }
    }
  }
}
</style>