<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="addButtonStyle" @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)">
					<img src="@/assets/images/tableIcon/updateIcon.png" alt="" class="configureIcon" />
					<span>编辑</span>
				</el-button>
				<el-button type="danger" link :icon="Delete" @click="deleteAccount(row)">删除</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 style="flex: auto">
					<el-button @click="cacel">取消</el-button>
					<el-button type="primary" @click="confirm">保存并关闭</el-button>
				</div>
			</template>
		</el-drawer>

		<DialogForm
			:title="title"
			:formConfig="formConfig"
			:formData="formData"
			v-model:visible="visible"
			append-to-body
			width="700px"
			@confirm="saveItem"
		>
		</DialogForm>
	</div>
</template>

<script setup lang="tsx" name="ProjectSupervisionRecord">
import { ref, reactive, nextTick } 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 { getProjectRecordPage } from "@/api/modules/project";

import { Delete } from "@element-plus/icons-vue";
import { GlobalStore } from "@/stores";

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: 0,
	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" }
];

// 弹窗中的配置
const formConfig = {
	formItemConfig: [
		{
			label: "角色名称",
			prop: "roleName",
			type: "input"
		},
		{
			label: "角色顺序",
			prop: "priority",
			type: "number"
		},
		{
			label: "状态",
			prop: "state",
			type: "radio",
			data: [
				{ label: "启用", value: 1 },
				{ label: "禁用", value: 0 }
			]
		},
		{
			label: "备注",
			prop: "roleDesc",
			type: "input",
			mapIcon: true
			// 标记dialog
		}
	],
	rules: {
		roleName: [
			{
				required: true,
				message: "请输入角色名称",
				trigger: "blur"
			}
		],
		priority: [
			{
				required: true,
				message: "请输入角色顺序",
				trigger: "blur"
			}
		]
	}
};

// 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 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();
	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,
			roleDesc: ""
		});
	} else {
		title.value = "编辑角色";
		formData.value = reactive({ ...row });
	}
	visible.value = true;
};

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

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

	const res = await getTreeByIdList({ roleId: row.roleId });
	// 打开弹窗时调用上面的接口勾选
	nextTick(() => {
		treeRef.value.setCheckedKeys(res.result.map(item => item.authorityId));
	});
};

const saveItem = async (form: any) => {
	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;
};

// 删除用户信息
const deleteAccount = async (params: jxj_User.ResUserList) => {
	await useHandleData(deleteRole, { roleId: params.roleId }, `删除【${params.roleName}】`);
	proTable.value.getTableList();
};

const changeTreeFilter = () => {
	console.log(11);
};
</script>
