<template>
  <div class="system-dept-container layout-padding">
    <el-card shadow="hover" class="layout-padding-auto">
      <div class="system-dept-search mb15">
        <el-input clearable size="default" v-model="state.formQuery.name" placeholder="请输入部门名称" style="width: 150px"></el-input>
        <ext-d-select type="Department.status" v-model="state.formQuery.status" placeholder="部门状态"  style="width: 150px;margin-left: 10px;"/>

        <ext-button name="查询" icon="ele-Search" size="default" type="primary" class="ml10" @click="loadListData(true)" />
<!--        <ext-button name="新增" auth="'department.add'" icon="ele-FolderAdd" size="default" type="success" class="ml10" @click="handleOpenDialog(0,false)" />-->
<!--        <el-button size="default" type="primary" class="ml10" @click="loadListData(true)">
          <el-icon>
            <ele-Search/>
          </el-icon>
          查询
        </el-button>
        <el-button :auth="['department.add']" size="default" type="success" class="ml10" @click="handleOpenDialog(0,false)">
          <el-icon>
            <ele-FolderAdd/>
          </el-icon>
          新增部门
        </el-button>-->
      </div>

      <el-row :gutter="20">
        <el-col :span="6">
          <el-input size="default" v-model="state.filterText" placeholder="搜索上级部门"/>
          <el-tree-v2
              ref="treeRef"
              class="filter-tree"
              :data="state.treeData"
              :props="{  children: 'children',  label: 'name'}"
              highlight-current
              default-expand-all
              :filter-node-method="filterNode"
              @node-click="handleNodeClick"
          />
        </el-col>
        <el-col :span="18">
          <el-table
              :header-cell-style="{'background':'#f4f4f4'}"
              :data="state.tableData.data"
              v-loading="state.tableData.loading"
              style="width: 100%"
              border
              row-key="id"
              :tree-props="{ children: 'children' }">
            <el-table-column prop="name" label="部门名称" show-overflow-tooltip width="160" fixed="left"></el-table-column>
            <el-table-column prop="parentName" label="上级部门" show-overflow-tooltip width="160" ></el-table-column>
            <el-table-column prop="fullName" label="部门全称" show-overflow-tooltip width="160" ></el-table-column>
            <el-table-column prop="leaderList" label="负责人" show-overflow-tooltip width="200">
              <template #default="scope">
                <el-tag v-for="(item,idx) in scope.row.leaderList" :key="idx">{{item.name}}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="disLeaderList" label="分管负责人" show-overflow-tooltip width="200">
              <template #default="scope">
                <el-tag v-for="(item,idx) in scope.row.disLeaderList" :key="idx">{{item.name}}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="部门状态" show-overflow-tooltip>
              <template #default="scope">
                <ExtDLabel v-model="scope.row.status" type="Department.status"/>
              </template>
            </el-table-column>
            <el-table-column prop="describe" label="部门层级" show-overflow-tooltip>
              <template #default="scope">
                <ExtDLabel v-model="scope.row.level" type="Level.value"/>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="更新时间" width="160" >
              <template #default="scope">
                {{ u.fmt.fmtDateTime(scope.row.updateAt) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" show-overflow-tooltip width="220" fixed="right">
              <template #default="scope">
                <el-button plain size="small" type="success" :auth="['department.add']" @click="handleOpenDialog(0,false,scope.row)">新增</el-button>
                <el-button plain size="small" type="warning" :auth="['department.modify']" @click="handleOpenDialog(scope.row.id,false)">修改</el-button>
                <el-button plain size="small" :disabled="scope.row.parent===0" :auth="['department.remove']" type="danger" @click="onTabelRowDel(scope.row)">删除</el-button>
              </template>
            </el-table-column>

            <template #empty>
              <el-empty/>
            </template>

          </el-table>

          <ext-page class="page-pager" v-model:value="state.pageQuery" @change="loadData(false)"/>
        </el-col>
      </el-row>

    </el-card>
    <DeptDialog ref="deptDialogRef" @refresh="loadData()"/>
  </div>
</template>

<script setup lang="ts" name="adminDepartment">
import {defineAsyncComponent, ref, reactive, onMounted, watch} from 'vue';
import {ElMessageBox, ElMessage, ElTree} from 'element-plus';
import {$body} from '/@/utils/request'
import u from '/@/utils/u'
import ExtDLabel from "/@/components/form/ExtDLabel.vue";
import ExtPage from "/@/components/form/ExtPage.vue"
import ExtDSelect from "/@/components/form/ExtDSelect.vue";
import ExtButton from "/@/components/form/ExtButton.vue";

// 引入组件
const DeptDialog = defineAsyncComponent(() => import('/@/views/admin/department/dialog.vue'));

// 定义变量内容
const deptDialogRef = ref();
const treeRef = ref<InstanceType<typeof ElTree>>()
const state = reactive({
  tableData: {
    data: [] as Array<any>,

    loading: false,
  },
  pageQuery: {
    pageIndex: 1,
    pageSize: 20,
    total: 0,
  },
  treeData: [],
  filterText: null,
  formQuery: {
    parent: null,
  }
});

interface Tree {
  [key: string]: any
}

watch(() => state.filterText, (val) => {
  treeRef.value!.filter(val)
})


// 初始化表格数据
const loadTreeData = () => {
  state.tableData.loading = true;
  state.tableData.data = [];
  $body(`/department/tree`).then((res: any) => {
    state.treeData = res;
  })
  setTimeout(() => {
    state.tableData.loading = false;
  }, 500);
};

const loadListData = () => {
  $body(`/department/list`, {...state.formQuery, ...state.pageQuery}).then((res: any) => {
    let {list, count} = res;
    state.tableData.data = list;
    state.pageQuery.total = count;
  })
}

const handleNodeClick = (data: any) => {
  console.log(data)
  if (data) {
    if (state.formQuery.parent === data.id) {
      state.formQuery.parent = null;
      treeRef.value?.setCurrentKey(null)
    } else {
      state.formQuery.parent = data.id;
    }
  }
  loadListData();
}

const filterNode = (value: string, data: Tree) => {
  if (!value) return true
  return data.name.includes(value)
}

// 打开新增菜单弹窗
const handleOpenDialog = (id: number, readonly: boolean, obj?: any) => {
  deptDialogRef.value.openDialog(id, readonly, obj);
};
// 删除当前行
const onTabelRowDel = (row: DeptTreeType) => {
  ElMessageBox.confirm(`此操作将永久删除部门：${row.deptName}, 是否继续?`, '提示', {
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    type: 'warning',
  })
      .then(() => {
        loadTreeData();
        ElMessage.success('删除成功');
      })
      .catch(() => {
      });
};

const loadData = () => {
  loadListData();
  loadTreeData();
}
// 页面加载时
onMounted(() => {
  loadData()
});
</script>
