<template>
	<div class="main-box">
		<TreeFilter ref="proTree" :checkStrictly="true" label="deptName" :requestApi="getTreeDeptList" @change="changeTreeFilter">
			<template #addButton>
				<el-button type="primary" @click="onAddDept">新增部门</el-button>
			</template>
			<template #editButton="{ row }">
				<el-button style="font-size: 12px" type="danger" link :icon="Delete" @click="onDelDept(row)">删除</el-button>
				<!-- {{ row.showEdit ? "true" : "false" }} -->
			</template>
		</TreeFilter>
		<div class="table-box">
			<el-card shadow="never">
				<el-button :class="{ blueText: !showPage }" @click="showPage = false" link>基本信息</el-button>
				<el-button :class="{ blueText: showPage }" @click="showPage = true" link>用户管理</el-button>
			</el-card>
			<div class="base-box" v-show="!showPage">
				<el-form style="padding: 10% 30%" :model="baseFrom" ref="ruleFormRef" label-width="150px">
					<el-form-item label="上级部门:" prop="parentId">
						<el-select style="width: 100%" v-model="baseFrom.parentId" placeholder="请选择">
							<el-option v-for="item in treeDeptList" :key="item.deptId" :label="item.deptName" :value="item.deptId" />
						</el-select>
					</el-form-item>
					<el-form-item label="部门名称:" prop="deptName">
						<el-input v-model="baseFrom.deptName" placeholder="请输入" />
					</el-form-item>
					<el-form-item label="显示排序:" prop="priority">
						<el-input-number v-model="baseFrom.priority" :min="1" :max="9999" />
					</el-form-item>
					<el-form-item label="负责人:" prop="leader">
						<el-input v-model="baseFrom.leader" placeholder="请输入" />
					</el-form-item>
					<el-form-item label="联系电话:" prop="phone">
						<el-input v-model.number="baseFrom.phone" placeholder="请输入" />
					</el-form-item>
					<el-form-item label="邮箱:" prop="email">
						<el-input v-model="baseFrom.email" placeholder="请输入" />
					</el-form-item>
					<el-form-item label="部门状态:" prop="status">
						<el-radio-group v-model="baseFrom.status">
							<el-radio :label="1">启用</el-radio>
							<el-radio :label="0">禁用</el-radio>
						</el-radio-group>
					</el-form-item>
				</el-form>
				<div class="form-btn">
					<!-- <el-button style="margin-right: 60px" @click="onReset" class="cancelButtonStyle">重置</el-button> -->
					<el-button type="primary" @click="onSubmit">保存</el-button>
				</div>
			</div>
			<div class="protable" v-show="showPage">
				<ProTable
					ref="proTable"
					title="用户列表"
					:columns="columns"
					:requestApi="getTableList"
					:dataCallback="dataCallback"
					:tool-button="false"
					:pagination="true"
					background
					:isShowSearch="false"
					:onReset="true"
					:initParam="initParam"
				>
					<template #formButton="scope">
						<el-button class="addButtonStyle" @click="handleEditItem(1)">新增</el-button>
					</template>
					<template #operation="{ row }">
						<el-button type="primary" link @click="handleEditItem(2, row)">
							<img src="@/assets/images/tableIcon/updateIcon.png" alt="" class="configureIcon" />
							<span>编辑</span>
						</el-button>
						<el-button type="danger" link :icon="Delete" @click="handleDeleteItem(row)">删除</el-button>
					</template>

					<template #state="{ row }">
						<span :class="row.state === 1 ? '' : 'redText'">{{ row.state == 1 ? "启用" : "禁用" }}</span>
					</template>
				</ProTable>
			</div>
			<!-- 用户管理的 -->
			<DialogForm
				:title="title"
				:formConfig="formConfig"
				:formData="formData"
				v-model:visible="visible"
				append-to-body
				width="700px"
				@confirm="saveItem"
			>
			</DialogForm>
			<!-- 树形增加部门 -->
			<DialogForm
				:title="title"
				:formConfig="formConfigDept"
				:formData="formDataDept"
				v-model:visible="Deptvisible"
				append-to-body
				width="700px"
				@confirm="handleSubmit"
			>
			</DialogForm>
		</div>
	</div>
</template>
<script setup lang="ts" name="govermentUserdepartManage">
import { ref, reactive, onMounted, nextTick, watch } from "vue";
import { User } from "@/api/interface";
import { Delete } from "@element-plus/icons-vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { ColumnProps } from "@/components/ProTable/interface";
import { useHandleData } from "@/hooks/useHandleData";
import ProTable from "@/components/ProTable/index.vue";
import TreeFilter from "@/components/TreeFilter/index.vue";
import {
	getTreeDeptList,
	getUserPage,
	deleteUser,
	getTreeList,
	addTreeDeptMent,
	editUser,
	addUser,
	getRoleNamelist,
	delTreeDeptMent,
	editTreeDeptMent
} from "@/api/modules/enterpriseApi";
import DialogForm from "@/components/DialogForm/index.vue";
import { jxj_User } from "@/api/types";

const router = useRouter();
const title = ref("");
const visible = ref(false);
const Deptvisible = ref(false);
const showPage = ref(false);
const formData = ref({
	realName: "",
	userTel: "",
	account: "",
	password: "",
	email: "",
	state: 1,
	sex: "",
	department: "",
	jobName: "",
	roleId: "",
	remark: ""
});
const formDataDept = ref({
	parentId: "",
	deptName: "",
	account: 1,
	leader: "",
	phone: "",
	email: "",
	status: 1
});
const treeDeptList = ref([]);
// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref();
const proTree = ref();

const baseFrom = ref({ parentId: undefined, deptName: "", priority: 1, leader: "", phone: "", email: "", status: 1 });

// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({
	deptId: ""
});

// 树形筛选切换
const changeTreeFilter = async (val: string) => {
	// const { result } = await getTableList({ deptId: val.data.deptId });
	// proTable.value.tableData = result.records;
	// proTable.value.pageable.total = +result.total;
	initParam.deptId = val.data.deptId;
	baseFrom.value = { ...val.data };
};

// 表格配置项
const columns: ColumnProps[] = [
	{ type: "index", label: "序号", width: 80 },
	{
		prop: "account",
		label: "账号名称",
		search: { el: "input" }
	},

	// 多级 prop
	{ prop: "realName", label: "用户姓名" },
	{ prop: "deptName", label: "部门" },
	{ prop: "userTel", label: "手机号码", search: { el: "input" } },
	{ prop: "state", label: "使用状态" },
	{
		prop: "state",
		label: "状态",
		isShow: false,
		search: { el: "select", props: { filterable: true } },
		enum: [
			{ label: "启用", value: 1 },
			{ label: "禁用", value: 0 }
		]
	},
	{
		prop: "createTime",
		label: "创建时间",
		search: {
			el: "date-picker",

			props: {
				type: "daterange",
				format: "YYYY-MM-DD",
				valueFormat: "YYYY-MM-DD"
				// defaultTime: defaultTime2
			}
		}
	},
	{ prop: "operation", label: "操作", fixed: "right" }
];

// 弹窗中的配置
const formConfig = reactive({
	formItemConfig: [
		{
			label: "用户姓名",
			prop: "realName",
			type: "input"
		},
		{
			label: "手机号码",
			prop: "userTel",
			type: "input"
		},
		{
			label: "账号名称",
			prop: "account",
			type: "input"
		},
		{
			label: "密码",
			prop: "password",
			type: "input"
		},
		{
			label: "邮箱",
			prop: "email",
			type: "input"
		},

		{
			label: "状态",
			prop: "state",
			type: "radio",
			data: [
				{ label: "启用", value: 1 },
				{ label: "禁用", value: 0 }
			]
		},
		{
			label: "用户性别",
			prop: "sex",
			type: "select",
			data: [
				{ label: "男", value: 1 },
				{ label: "女", value: 0 }
			]
		},
		{
			label: "归属部门",
			prop: "department",
			type: "select",
			data: [],
			fieldNames: { label: "roleName", value: "roleId" }
			// 树形接口i
		},

		{
			label: "岗位",
			prop: "jobName",
			type: "input"
		},
		{
			label: "角色",
			prop: "roleId",
			type: "select",
			data: []

			// 接口获取角色管理
		},
		{
			label: "备注",
			prop: "remark",
			type: "input"
		}
	],
	rules: {
		realName: [
			{
				required: true,
				message: "请输入用户姓名",
				trigger: "blur"
			}
		],
		userTel: [
			{
				required: true,
				message: "请输入手机号码",
				trigger: "blur"
			}
		],
		password: [
			{
				required: true,
				message: "请输入密码",
				trigger: "blur"
			}
		],
		account: [
			{
				required: true,
				message: "请输入名称",
				trigger: "blur"
			}
		],
		roleId: [
			{
				required: true,
				message: "请选择角色",
				trigger: "blur"
			}
		]
	}
});

const formConfigDept = reactive({
	formItemConfig: [
		{
			label: "上级部门",
			prop: "parentId",
			type: "select",
			data: []
		},
		{
			label: "部门名称",
			prop: "deptName",
			type: "input"
		},
		{
			label: "显示排序",
			prop: "account",
			type: "number"
		},
		{
			label: "负责人",
			prop: "leader",
			type: "input"

			// 树形接口i
		},
		{
			label: "联系电话",
			prop: "phone",
			type: "input"
		},
		{
			label: "邮箱",
			prop: "email",
			type: "input"
		},

		{
			label: "部门状态",
			prop: "status",
			type: "radio",
			data: [
				{ label: "启用", value: 1 },
				{ label: "禁用", value: 0 }
			]
		}
	],
	rules: {
		deptName: [
			{
				required: true,
				message: "请输入类型名",
				trigger: "blur"
			}
		]
	}
});

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getUserList"
const getTableList = (params: any) => {
	let newParams = JSON.parse(JSON.stringify(params));
	if (newParams.createTime) {
		newParams.createTime_begin = newParams.createTime[0];
		newParams.createTime_end = newParams.createTime[1];
		delete newParams.createTime;
	}
	return getUserPage(newParams);
};

const dataCallback = (data: any) => {
	// console.log(data);
	return {
		list: data.records,
		total: Number(data.total),
		pageNo: Number(data.current),
		pageSize: Number(data.size)
	};
};

const onReset = () => {
	baseFrom.value = reactive({
		parentId: undefined,
		deptName: "",
		priority: 1,
		leader: "",
		phone: "",
		email: "",
		status: 1
	});

	ElMessage.success("重置成功");
};

const onSubmit = async () => {
	await editTreeDeptMent(baseFrom.value);
	ElMessage.success("编辑成功");
	const res = await getTreeDeptList();
	proTree.value.treeAllData = res.result;
};

// 修改数据按钮
const handleEditItem = async (index: number, row: any) => {
	const res1 = await getTreeList({ deptId: "", status: 1 });
	formConfig.formItemConfig[7].data = res1.result.map(i => {
		return {
			label: i.deptName,
			value: i.deptId
		};
	});
	if (index === 1) {
		title.value = "新增用户";
		formData.value = reactive({
			realName: "",
			userTel: "",
			account: "",
			password: "",
			email: "",
			state: 1,
			sex: "",
			department: "",
			jobName: "",
			roleId: "",
			remark: ""
		});
	} else {
		title.value = "编辑用户";
		formData.value = reactive({ ...row });
	}
	visible.value = true;
};

//新增部门的弹窗
const onAddDept = async () => {
	// 获取最新的部门列表信息
	const res1 = await getTreeList({ deptId: "", status: 1 });
	formConfigDept.formItemConfig[0].data = res1.result.map(i => {
		return {
			label: i.deptName,
			value: i.deptId
		};
	});
	Deptvisible.value = true;
	title.value = "新增部门";
	formDataDept.value = reactive({
		parentId: "",
		deptName: "",
		account: 1,
		leader: "",
		phone: "",
		email: "",
		status: 1
	});
};

const onDelDept = async row => {
	await useHandleData(delTreeDeptMent, { deptId: row.data.deptId }, `删除【${row.data.deptName}】`);
	const res = await getTreeDeptList();
	const res1 = await getTreeList({ deptId: "", status: 1 });
	treeDeptList.value = res1.result;
	proTree.value.treeAllData = res.result;
};

// 页面新增，编辑数据
const saveItem = async (form: any) => {
	if (form.userId) {
		const res = await editUser(form);
		proTable.value.getTableList();
		ElMessage.success("编辑成功");
	} else {
		const res = await addUser(form);
		ElMessage.success("新增成功");
		proTable.value.getTableList();
	}
	visible.value = false;
};

const handleSubmit = async form => {
	await addTreeDeptMent(form);
	ElMessage.success("新增成功");
	Deptvisible.value = false;
	const res = await getTreeDeptList();
	proTree.value.treeAllData = res.result;
	// 新增成功后刷新基本信息的上级部门的下拉框数据
	const res1 = await getTreeList({ deptId: "", status: 1 });
	treeDeptList.value = res1.result;
};

// 删除用户信息
const handleDeleteItem = async (params: jxj_User.ResUserList) => {
	await useHandleData(deleteUser, { userId: params.userId }, `删除【${params.account}】`);
	proTable.value.getTableList();
};

onMounted(async () => {
	const res1 = await getTreeList({ deptId: "", status: 1 });
	treeDeptList.value = res1.result;
	const res = await getRoleNamelist({ state: 1 });
	formConfig.formItemConfig[7].data = res1.result.map(i => {
		return {
			label: i.deptName,
			value: i.deptId
		};
	});
	formConfig.formItemConfig[9].data = res.result.map(i => {
		return {
			label: i.roleName,
			value: i.roleId
		};
	});
	formConfigDept.formItemConfig[0].data = res1.result.map(i => {
		return {
			label: i.deptName,
			value: i.deptId
		};
	});
});
</script>

<style lang="scss" scoped>
@import "./index.scss";
.blueText {
	color: #008bff;
}
</style>
