<template>
	<el-container class="aminui-main-container">
		<el-aside v-loading="aside.loading" width="310px">
			<el-container>
				<el-header class="aminui-main-container__query-header">
					<scTitle>组织结构</scTitle>
					<el-form @submit.prevent>
						<el-form-item>
							<el-input v-model="aside.filterText" clearable placeholder="输入要检索的组织机构"></el-input>
						</el-form-item>
					</el-form>
				</el-header>
				<el-main class="nopadding">
					<el-scrollbar>
						<el-tree ref="aside" node-key="deptId" :data="aside.list" :props="aside.props" lazy :load="loadNode" highlight-current :default-expanded-keys="aside.expandedKeys" :expand-on-click-node="false" check-strictly :filter-node-method="asideFilterNode" @node-click="data => asideNodeClick(data)">
							<template #default="{ node, data }">
								<el-icon class="folder-icon"><sc-icon-folder /></el-icon>
								<span :id="data.id" class="custom-tree-node">
									<scTooltip :content="node.label"></scTooltip>
									<el-dropdown @command="asideCommand($event, data)">
										<el-icon class="el-dropdown-link"><el-icon-more-filled /></el-icon>
										<template #dropdown>
											<el-dropdown-menu>
												<el-dropdown-item command="aside_add">
													<el-icon><sc-icon-add /></el-icon>新增
												</el-dropdown-item>
												<el-dropdown-item command="aside_edit" divided>
													<el-icon><el-icon-edit /></el-icon>编辑
												</el-dropdown-item>
												<el-dropdown-item command="aside_del" divided>
													<el-icon><el-icon-delete /></el-icon>删除
												</el-dropdown-item>
											</el-dropdown-menu>
										</template>
									</el-dropdown>
								</span>
							</template>
						</el-tree>
					</el-scrollbar>
				</el-main>
				<el-footer>
					<el-button type="primary" @click="aside_add(null)">新增</el-button>
				</el-footer>
			</el-container>
		</el-aside>

		<el-container>
			<el-header class="aminui-main-container__query-header">
				<scTitle>{{ table.deptName || "组织人员列表" }}</scTitle>
				<el-form :model="table.params" @submit.prevent>
					<el-row :gutter="15">
						<el-col :lg="10" :md="14" :xs="24">
							<el-form-item>
								<el-input v-model="table.params.blurry" clearable placeholder="输入姓名、账号、手机"></el-input>
							</el-form-item>
						</el-col>
						<el-col :md="10" :xs="24">
							<el-form-item>
            					<el-button-group>
									<el-button type="primary" icon="el-icon-search" @click="reloadTable">查询</el-button>
									<el-button icon="el-icon-refresh" @click="reset">重置</el-button>
            					</el-button-group>
							</el-form-item>
						</el-col>
					</el-row>
				</el-form>
			</el-header>
			<el-container class="aminui-main-container__table-main">
				<el-header>
					<div class="left-panel">
						<el-button type="primary" @click="table_add">新增成员</el-button>
					</div>
				</el-header>
				<el-main class="nopadding">
					<scTable class="scTable" ref="table" row-key="id" :apiObj="table.api" :params="table.params" :data="table.list" :column="table.column" tableName="userTable">
						<el-table-column label="序号" type="index" align="center" width="60"></el-table-column>
						<template #deptName="scope">{{ scope.row.dept && scope.row.dept.name }}</template>
						<template #jobNames="scope">{{ formatJobs(scope.row.jobs) }}</template>
						<el-table-column label="操作" fixed="right" align="center" width="180">
							<template #default="scope">
								<el-button text @click="table_edit(scope.row)">编辑</el-button>
								<el-divider direction="vertical" />
								<el-button text @click="table_del(scope.row)">删除</el-button>
								<el-divider direction="vertical" />
								<el-button text @click="table_project(scope.row)">授权项目</el-button>
							</template>
						</el-table-column>
					</scTable>
				</el-main>
			</el-container>
		</el-container>
	</el-container>

    <dept-dialog v-if="dialog.dept" ref="deptDialog" @success="getAsideNode" @closed="dialog.dept = false"></dept-dialog>
    <user-dialog v-if="dialog.user" ref="userDialog" @success="reloadTable" @closed="dialog.user = false"></user-dialog>
    <user-project v-if="dialog.project" ref="userProject" @success="reloadTable" @closed="dialog.project = false"></user-project>
</template>

<script>
	import config from "@/config/treeSelect";
	import deptDialog from "./dept";
	import userDialog from "./user";
	import userProject from "./userPro";

	export default {
		components: {
			deptDialog,
			userDialog,
            userProject
		},

		data() {
			return {
				aside: {
					loading: false,
					list: [],
					props: {
						...config.deptProps
					},
					filterText: null,
					expandedKeys: [],
					currentKey: null
				},

				table: {
					column: [
						{ label: "姓名", prop: "nickName", width: "140", align: "center" },
						{ label: "账号", prop: "username", width: "140", align: "center" },
						{ label: "所属组织", prop: "deptName", width: "200", align: "center", showOverflowTooltip: true },
						{ label: "岗位", prop: "jobNames", width: "140", align: "center", showOverflowTooltip: true },
						{ label: "手机", prop: "phone", width: "140", align: "center" }
					],
					api: this.$API.system.user,
					params: {
						sort: "id,desc",
						deptId: null,
						blurry: null
					},
					list: [],
					deptName: null
				},

				dialog: {
					dept: false,
					user: false,
                    project: false
				}
			}
		},

		watch: {
			"aside.filterText"(val) {
				this.$refs.aside.filter(val);
			}
		},

		mounted() {
			this.getAsideNode();
		},

		methods: {
			formatJobs(value) {
				if (!value || !value.length) return "";
				return value.map(v => v.name).join();
			},

			async getAsideNode(data) {
				try {
					this.aside.loading = true;
					const res = await this.$API.system.dept.get({ pid: "0" });
					this.aside.loading = false;
					this.aside.list = res.slice();
					
					if (data) {
						if (data.pid == -1) this.aside.expandedKeys = [data.pid, data.deptId];
						else this.aside.expandedKeys = [-1, data.pid, data.deptId];
						this.asideNodeClick(data, true);
						this.aside.currentKey = data.deptId;
					} else this.aside.currentKey = null;
				} catch (error) {
					this.aside.loading = false;
					this.aside.list = [];
				}
			},
				
			async loadNode({ level, data }, resolve) {
				if (level > 0) {
					try {
						const res = await this.$API.system.dept.get({ pid: data.deptId });
						resolve(res);
						this.aside.currentKey && this.$refs.aside.setCurrentKey(this.aside.currentKey);
					} catch (error) {
						resolve([]);
					}
				}
			},

			asideFilterNode(value, data) {
				if (!value) return true;
				return data.name.indexOf(value) !== -1;
			},

			asideNodeClick(data, scroll = false) {
				this.table.deptName = data.name;
				this.table.params.deptId = data.deptId;
				this.$refs.aside.setCurrentKey(data.deptId);
				scroll && document.getElementById(data.deptId) && document.getElementById(data.deptId).scrollIntoView({ block: "center" });
				this.reloadTable();
			},

			// 本地更新数据
			reloadTable() {
				this.$refs.table.reload(this.table.params, 1);
			},

			reset() {
				this.table.params.blurry = null;
				this.reloadTable();
			},

			asideCommand(fun, data) {
				const params = fun == "aside_add" && data.deptId || data;
				this[fun](params);
			},

			aside_add(pid) {
				this.dialog.dept = true;
				this.$nextTick(() => this.$refs.deptDialog.open().setData({ pid }));
			},

			aside_edit(data) {
				this.dialog.dept = true;
				this.$nextTick(() => this.$refs.deptDialog.open("edit").setData(data));
			},

			aside_del({ deptId }) {
				this.$confirm("确认删除当前组织吗？", "提示", {
					type: "warning",
					confirmButtonText: "删除"
				}).then(() => {
					this.$API.system.dept.del({ deptId }).then(() => {
						this.$message.success("操作成功");
						this.getAsideNode();
						if (this.table.params.deptId == deptId) {
							this.table.params.deptId = null;
							this.table.deptName = null;
						}
					}).catch(() => {});
				}).catch(() => {});
			},

			// 添加成员
			table_add() {
				this.dialog.user = true;
				this.$nextTick(() => this.$refs.userDialog.open());
			},

			// 编辑成员
			table_edit(row) {
				this.dialog.user = true;
				this.$nextTick(() => this.$refs.userDialog.open("edit").setData(row));
			},

            // 配置用户项目
            table_project(row) {
				this.dialog.project = true;
				this.$nextTick(() => this.$refs.userProject.open().setData(row));
			},

			// 删除成员
			table_del({ id }) {
				this.$confirm("确认删除此成员吗？", "提示", {
					type: "warning",
					confirmButtonText: "删除"
				}).then(() => {
					this.$API.system.user.del([id]).then(() => {
						this.$message.success("操作成功");
						this.reloadTable();
					}).catch(() => {});
				}).catch(() => {});
			}
		}
	}
</script>

<style lang="scss" scoped>
.aminui-main-container {
  .aminui-main-container__query-header {
    flex-direction: column;

    .sc-title {
      margin-bottom: 15px;
      padding-left: 0;

      &::before {
        display: none;
      }
    }
  }

  .el-aside {
    margin-right: 15px;

    .aminui-main-container__query-header {
      margin-bottom: 0;
    }

    .el-main {
      padding-left: 10px;
      padding-bottom: 20px;

      .el-tree .el-tree-node .el-tree-node__content {
        .folder-icon {
          font-size: 16px;
          color: var(--el-color-blue);
        }

        .custom-tree-node {
          justify-content: space-between;
          width: calc(100% - 58px);
          margin-left: 6px;
          padding-right: 2px;

          .el-dropdown-link {
            top: 3px;
            margin-bottom: 6px;
            transform: rotate(90deg);
          }
        }
      }
    }
  }
}

@media (max-width: 992px) {
  .aminui-main-container {
    .el-aside {
      margin-right: 0;

      .aminui-main-container__query-header {
        margin-bottom: 0;
      }

      .el-main {
        padding-left: 15px;
        padding-right: 15px;
      }
    }
  }
}
</style>