<template>
  <div>
    <MOSTY.PageTree :pageTitle="'部门管理'" :isShowLeftTree="false">
      <el-divider />
      <!-- <template #serach>
        <div class="btnBox">
          <el-button type="primary" @click="addItemMenu">
            <el-icon>
              <CirclePlus />
            </el-icon>
            <span>新增</span>
          </el-button>
        </div>
      </template> -->
      <template #table>
        <div class="tabBox">
          <el-table ref="tableRef" stripe :data="tableData" border row-key="id"
            :tree-props="{ children: 'childDeptList', hasChildren: 'hasChildren' }" style="width: 100%" :key="keyCount"
            v-loading="isLoading" :load="depLoad" lazy @row-click="rowClick">
            <el-table-column prop="orgName" label="部门名称" show-overflow-tooltip align="left" width="320">
            </el-table-column>
            <el-table-column prop="orgCode" label="部门编码" show-overflow-tooltip align="left">
            </el-table-column>
            <el-table-column prop="orgType" label="部门类型" show-overflow-tooltip align="center">
              <template #default="{ row }">
                <dict-tag :options="D_ORG_ORGTYPE" :value="row.orgType" :tag="false" />
              </template>
            </el-table-column>
            <el-table-column prop="orgLevel" label="部门等级" show-overflow-tooltip align="center">
              <template #default="{ row }">
                <dict-tag :options="D_ORG_ORGLEVEL" :value="row.orgLevel" :tag="false" />
              </template>
            </el-table-column>
            <el-table-column prop="orgJc" label="部门简称" show-overflow-tooltip align="center">
            </el-table-column>

            <el-table-column label="部门业务类型" show-overflow-tooltip align="center">
              <template #default="{ row }">
                <dict-tag :options="D_ORG_ORGBIZTYPE" :value="row.orgBizType" :tag="false" />
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" fixed="right" width="350">
              <template #default="{ row }">
                <el-button @click="update(row)" size="small">修改</el-button>
                <el-button @click="addItemMenu(row)"
                  v-if="row.orgLevel.substring(row.orgLevel.length - 1) == '0' && row.orgLevel != '40'"
                  size="small">添加下级</el-button>
                <!-- ovger 0结尾 -->
                <el-button v-if="row.orgLevel.substring(row.orgLevel.length - 1) != '0'&&getItem('USERID') == '000000'" @click="assignRoles(row)"
                  size="small">绑定角色</el-button>
                <el-popconfirm v-if="getItem('USERID') == '000000'" confirm-button-text="是" cancel-button-text="否"
                  icon-color="red" title="确定要删除?" @confirm="delDeptItem(row)">
                  <template #reference>
                    <el-button type="danger" size="small">删除</el-button>
                  </template>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </template>
    </MOSTY.PageTree>
    <RolesDialog v-model="roleDialogVisible" :deptId="currentDeptId" @updateRole="handleFilter"></RolesDialog>
    <!-- 新增弹出框 -->
    <Addsts v-model="addDiaShow" :editObj="editObj" @changeAddVi="changeAddVi" />
  </div>

</template>

<script setup>
import Addsts from "./components/addsts.vue";
import RolesDialog from "./components/roles.vue";
import * as MOSTY from "@/components/MyComponents/index";
import { ElMessage } from "element-plus";
import { ref, onMounted, getCurrentInstance, onUnmounted } from "vue";
import { deleteSysDept, getDept } from "@/api/user-manage";
import { getItem } from "@/utils/storage";
const { proxy } = getCurrentInstance();
const { D_ORG_ORGBIZTYPE, D_ORG_ORGLEVEL, D_ORG_ORGTYPE } = proxy.$dict("D_ORG_ORGBIZTYPE", "D_ORG_ORGLEVEL", "D_ORG_ORGTYPE");
const keyCount = ref(0); //tabel组件刷新值
const isLoading = ref(false); // 是否加载
const tableRef = ref()
const listQuery = ref({
  parentid: "",//部门编码
  searchType: '01',
});
//新增修改弹窗相关
const addDiaShow = ref(false);
const editObj = ref({});
// 数据相关
const tableData = ref([]);
const currentDeptId = ref("");
const roleDialogVisible = ref(false);

//动态加载部门数据
function depLoad(row, treeNode, resolve) {
  listQuery.value.parentid = row.id;
  getDept(listQuery.value).then((res) => {
    resolve(res);
  });
};
// 获取数据的方法
const getListData = () => {
  isLoading.value = true;
  tableData.value = [];
  const params = listQuery.value;
  getDept(params).then((res) => {
    tableData.value = res;
  })
    .finally(() => {
      isLoading.value = false;
    });
};
//搜索查询
const handleFilter = () => {
  listQuery.value.parentid = ''
  getListData();
};
// 新增编辑表单关闭回调
const changeAddVi = (val) => {
  listQuery.value.parentid = ''
  addDiaShow.value = false;
  if (val) getListData();
};
//新增或添加下级
const addItemMenu = (row) => {
  editObj.value = { orgNo: 1, parentId: row ? row?.id : "" };
  addDiaShow.value = true;
};
//修改
const update = (row) => {
  editObj.value = row;
  addDiaShow.value = true;
};
//删除
const delDeptItem = (row) => {
  deleteSysDept({ id: row.id }).then(() => {
    ElMessage.success("删除成功");
    tableData.value = [];
    listQuery.value = {
      deptname: "",
      deptcode: "",
      parentid: ""
    };
    getListData();
  });
};
//绑定角色
const assignRoles = (row) => {
  roleDialogVisible.value = true;
  currentDeptId.value = row.id;
};
onMounted(() => {
  getListData();
  proxy.mittBus.on("mittFn", (data) => {
    keyCount.value = data;
  });
});
onUnmounted(() => {
  proxy.mittBus.off("mittFn");
});
function rowClick(row, column, event) {

  if (column.label != '操作') {
    function getRowIdentity(row, rowKey) {
      if (!row) return undefined
      if (typeof rowKey === 'string') {
        if (rowKey.indexOf('.') < 0) {
          return row[rowKey];
        }
        let key = rowKey.split('.');
        let current = row;
        for (let i = 0; i < key.length; i++) {
          current = current[key[i]];
        }
        return current;
      } else if (typeof rowKey === 'function') {
        return rowKey.call(null, row);
      }
    }
    const store = tableRef.value.store;
    const { states: { lazy, treeData, rowKey }, assertRowKey, loadOrToggle } = store
    const id = getRowIdentity(row, rowKey.value)
    if (!id) return
    const data = treeData.value[id]
    // 懒加载则调用懒加载
    if (lazy && data && 'loaded' in data && !data.loaded) {
      return loadOrToggle(row, id, data)
    }
    tableRef.value.toggleRowExpansion(row);
  }

};
</script>

<style lang="scss" scoped>
@import "~@/assets/css/layout.scss";
@import "@/assets/css/element-plus.scss";

.pageRight {
  height: 84vh;
}

.tabBox {
  height: calc(100vh - 254px);
  overflow-y: scroll;
}

::v-deep .el-table .cell {
  text-align: left;
}

::v-deep .el-form {
  flex-wrap: wrap
}

.btnBox {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  margin-bottom: 12px;
}
</style>
