<template>
	<div class="table-box">
		<ProTable
			ref="proTable"
			title="用户列表"
			:columns="columns"
			:requestApi="getTableList"
			:dataCallback="dataCallback"
			:tool-button="false"
			:pagination="true"
			background
			:isShowSearch="false"
			:onReset="true"
		>
			<template #formButton="scope">
				<el-button class="btnStyle" @click="handleAddItem(1)">新增</el-button>
			</template>
			<template #operation="{ row }">
				<el-button type="primary" link @click="handleEditItem(row)">
					<img src="@/assets/images/tableIcon/配置权限.png" alt="" class="configureIcon" />
					<span>配置权限</span>
				</el-button>
				<el-button type="primary" link @click="handleAddItem(2, row)" v-if="row.sysDefault != 1">
					<img src="@/assets/images/tableIcon/updateIcon.png" alt="" class="configureIcon" />
					<span>编辑</span>
				</el-button>
				<el-button type="danger" link :icon="Delete" @click="deleteAccount(row)" v-if="row.sysDefault != 1">删除</el-button>
			</template>
			<template #state="{ row }">
				<span :class="row.state === 1 ? '' : 'redText'">{{ row.state == 1 ? "启用" : "禁用" }}</span>
			</template>
		</ProTable>
		<el-drawer v-model="drawerVisible" :destroy-on-close="true" :before-close="closeDrawer" size="450px" title="配置权限">
			<span class="title sle">所拥有的权限</span>
			<el-scrollbar :style="{ height: title ? `calc(100% - 95px)` : `calc(100% - 56px)` }">
				<!-- check-strictly 父子不关联 这样数据选择父 子不会默认被勾选  子被选择 父也不会 -->
				<el-tree ref="treeRef" default-expand-all :data="datas" show-checkbox node-key="name" :props="defaultProps"> </el-tree>
			</el-scrollbar>
			<template #footer>
				<div class="flx-center">
					<el-button class="hzCancelStyle" style="margin-right: 60px" @click="cacel">取消</el-button>
					<el-button class="hzStyle" type="primary" @click="confirm">保存并关闭</el-button>
				</div>
			</template>
		</el-drawer>
		<!-- 新增角色 -->
		<el-dialog class="imgDialog" :title="title" width="700px" v-model="visible" show-close>
			<el-form class="diaForm" :rules="rules" :model="formData" ref="ruleFormRef" label-width="160px">
				<el-form-item label="角色名称：" prop="roleName">
					<el-input v-model="formData.roleName" placeholder="请输入" />
				</el-form-item>
				<el-form-item label="角色顺序：" prop="priority">
					<el-input-number v-model="formData.priority" placeholder="请输入" />
				</el-form-item>
				<el-form-item label="状态：" prop="state">
					<el-radio-group v-model="formData.state">
						<el-radio :label="1">启用</el-radio>
						<el-radio :label="0">禁用</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item
					label="角色类型："
					prop="roleType"
					v-if="store.accountType == 2 || (store.accountType == 3 && store.enterpriseType.includes(1))"
				>
					<el-radio-group v-model="formData.roleType" @change="getSelectData">
						<el-radio :label="2">政务</el-radio>
						<el-radio :label="3">企业</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="指定类型：" prop="sn" v-if="formData.roleType != 2">
					<el-select v-model="formData.sn" clearable placeholder="请选择" style="width: 100%">
						<el-option v-for="item in typeList" :key="item.value" :label="item.label" :value="item.value" />
					</el-select>
				</el-form-item>
				<el-form-item label="备注：" prop="roleDesc">
					<el-input v-model="formData.roleDesc" placeholder="请输入" />
				</el-form-item>
			</el-form>
			<template #footer>
				<div>
					<el-button class="hzCancelStyle" @click="visible = false">取消</el-button>
					<el-button type="primary" @click="saveItem(ruleFormRef, formData)"> 保存 </el-button>
				</div>
			</template>
		</el-dialog>
	</div>
</template>

<script setup lang="tsx" name="ProjectSupervisionRecord">
import { ref, reactive, nextTick, onMounted } from "vue";
import { ElMessage, ElMessageBox, ElTree } from "element-plus";
import { useRouter } from "vue-router";
import { ColumnProps } from "@/components/ProTable/interface";
import { useHandleData } from "@/hooks/useHandleData";
import ProTable from "@/components/ProTable/index.vue";
import { jxj_User } from "@/api/types";
import TreeFilter from "@/components/TreeFilter/index.vue";
import {
	getRoleList,
	addRole,
	editRole,
	deleteRole,
	editRolePermissions,
	getSystemRole,
	getTreemRoleList,
	getTreeByIdList
} from "@/api/modules/goverment";
import DialogForm from "@/components/DialogForm/index.vue";
import { getentNamelist } from "@/api/modules/goverment";
import { engineerList } from "@/api/modules/huizhou";
import type { FormRules, FormInstance } from "element-plus";
// import { getProjectRecordPage } from "@/api/modules/project";

import { Delete } from "@element-plus/icons-vue";
import { GlobalStore } from "@/stores";
const engineerProjectList = ref([]); // 项目列表
const enterpriseList = ref([]); // 企业列表
const ruleFormRef = ref();
const typeList = ref([]);
const rules = reactive<FormRules>({
	roleName: [
		{
			required: true,
			message: "请输入角色名称",
			trigger: "blur"
		}
	],
	priority: [
		{
			required: true,
			message: "请输入角色顺序",
			trigger: "blur"
		}
	],
	sn: [
		{
			required: true,
			message: "请选择指定类型",
			trigger: "blur"
		}
	]
});
const treeRef = ref(null);

const datas = reactive([]);

const defaultProps = {
	children: "children",
	label: (data, node) => node.data.meta.title
};
const router = useRouter();
const store = GlobalStore();
const visible = ref(false);
const drawerVisible = ref(false);
const title = ref("");
const formData = ref({
	roleName: "",
	priority: 1,
	state: 1,
	roleType: 2,
	sn: "",
	roleDesc: ""
});
// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref();

const getId = ref<number | undefined>(undefined);

// 表格配置项
const columns: ColumnProps[] = [
	{ type: "index", label: "序号", width: 80 },
	{
		prop: "roleName",
		label: "角色名称",
		search: { el: "input" }
	},
	// 多级 prop
	{ prop: "priority", label: "显示顺序" },
	{ prop: "state", label: "使用状态" },
	{
		prop: "state",
		label: "状态",
		search: { el: "select" },
		isShow: false,
		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", width: 320 }
];

// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 list && total && pageNum && pageSize 这些字段，那么你可以在这里进行处理成这些字段
// 或者直接去 hooks/useTable.ts 文件中把字段改为你后端对应的就行
const dataCallback = (data: any) => {
	// console.log(data);
	return {
		list: data.records,
		total: Number(data.total),
		pageNo: Number(data.current),
		pageSize: Number(data.size)
	};
};

// 获取下拉数据
const getSelectData = async () => {
	typeList.value.length = 0;
	if (formData.value.roleType == 3) {
		typeList.value = [...enterpriseList.value];
	} else if (formData.value.roleType == 4) {
		typeList.value = [...engineerProjectList.value];
	}
	formData.value.sn = "";
};
const closeDrawer = done => {
	datas.length = 0;
	done();
};

const cacel = () => {
	drawerVisible.value = false;
	datas.length = 0;
};

const transfrom = (arr: Array<any>) => {
	const result = [];
	return arr
		.map(item => {
			if (arr.children && Array.isArray(arr.children)) {
				result.concat(transfrom(arr.children));
			}

			return {
				authorityId: item.name,
				roleId: getId.value,
				type: item.type
			};
		})
		.concat(result);
};

const confirm = async () => {
	const checked = treeRef.value.getCheckedNodes();
	const halfChecked = treeRef.value.getHalfCheckedNodes();
	const checkedArr = transfrom(checked);
	const halfCheckedArr = transfrom(halfChecked);
	const concatArr: any = checkedArr.concat(halfCheckedArr);
	if (!concatArr.length) {
		ElMessage.error("请选择");
	} else {
		await editRolePermissions(concatArr);
		drawerVisible.value = false;
		datas.length = 0;
	}
	// const checked = treeRef.value.getCheckedNodes();
	// await editRolePermissions(transfrom(checked));
	// drawerVisible.value = false;
	// datas.length = 0;
};

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：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 getRoleList(newParams);
};

const handleAddItem = (index: number, row: any) => {
	if (index === 1) {
		title.value = "新增角色";
		formData.value = reactive({
			roleName: "",
			priority: 1,
			state: 1,
			roleType: 2,
			sn: "",
			roleDesc: ""
		});
	} else {
		title.value = "编辑角色";
		formData.value = reactive({ ...row });
		typeList.value.length = 0;
		if (formData.value.roleType == 3) {
			typeList.value = [...enterpriseList.value];
		} else if (formData.value.roleType == 4) {
			typeList.value = [...engineerProjectList.value];
		}
	}
	visible.value = true;
};

// 修改数据按钮
const handleEditItem = async (row: any) => {
	getId.value = row.roleId;

	drawerVisible.value = true;
	const { result = [] } = await getTreemRoleList({ roleId: row.roleId });
	// console.log("test", result);
	datas.push(...result);

	const res = await getTreeByIdList({ roleId: row.roleId });
	// 打开弹窗时调用上面的接口勾选
	nextTick(() => {
		// treeRef.value.setCheckedKeys(res.result.map(item => item.authorityId));
		treeRef.value.setCheckedKeys(getRelativeKeys(res.result));
	});
};
// 根据条件获取需要选中的节点keys
const getRelativeKeys = (arr: any) => {
	let keysArr = [] as any;
	arr.map(item => {
		if (item.type == 0 && item.children == 0) {
			keysArr.push(item.authorityId);
		}
		if (item.type == 1 && item.children == 0) {
			keysArr.push(item.authorityId);
		}
		if (item.type != 0 && item.type != 1 && !item.children) {
			keysArr.push(item.authorityId);
		}
	});
	return keysArr;
};

const saveItem = async (formEl: FormInstance | undefined, form: any) => {
	// 标记表单校验
	if (!formEl) return;
	await formEl.validate(async (valid, fields) => {
		if (valid) {
			if (!store.enterpriseType.includes(1)) {
				delete form.roleType;
			}
			if (form.roleId) {
				// console.log(form.dictCode);
				const res = await editRole(form);
				proTable.value.getTableList();
				ElMessage.success("编辑成功");
			} else {
				const res = await addRole(form);
				ElMessage.success("新增成功");
				proTable.value.getTableList();
			}
			visible.value = false;
		} else {
			console.log("error submit!", fields);
			ElMessage({
				showClose: true,
				message: "请完善表单信息！",
				type: "error"
			});
		}
	});
};

// 删除用户信息
const deleteAccount = async (params: jxj_User.ResUserList) => {
	await useHandleData(deleteRole, { roleId: params.roleId }, `删除【${params.roleName}】`);
	proTable.value.getTableList();
};
onMounted(async () => {
	const res1: any = await getentNamelist({});
	enterpriseList.value = res1.result.map(item => {
		return {
			label: item.enterpriseName,
			value: item.enterpriseSn
		};
	});

	const res2: any = await engineerList({});
	engineerProjectList.value = res2.result.map(item => {
		return {
			label: item.engineeringName,
			value: item.engineeringSn
		};
	});
});
</script>
<style scoped lang="scss">
.table-box {
	width: 100%;
	height: 100%;
}
:deep(.el-form .el-form-item__content .el-range-editor) {
	width: 300px;
}
:deep() {
	.el-form-item__label {
		color: var(--el-menu-text-color);
	}
	.el-input__wrapper,
	.el-textarea__inner,
	.el-input.is-disabled .el-input__wrapper {
		background-color: transparent;
		box-shadow: 0 0 0 1px var(--el-color-primary) inset;
	}
	.el-input__inner,
	.el-textarea__inner,
	.el-range-input {
		color: var(--el-menu-text-color);
		font-size: 20px;
	}
	.el-range-separator {
		color: var(--el-menu-text-color);
	}
	.el-pager li.is-active {
		background-color: var(--el-color-primary);
		color: var(--el-color-white);
	}
	.el-table__expand-icon > .el-icon {
		font-size: 18px;
		color: var(--el-menu-text-color);
	}
	.el-input-number__decrease {
		border-right-color: var(--el-color-primary);
		color: var(--el-menu-text-color);
	}
	.el-input-number__increase {
		border-left-color: var(--el-color-primary);
		color: var(--el-menu-text-color);
	}
}
</style>
