<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="handleEditItem(1)">新增</el-button>
			</template>
			<template #operation="{ row }">
				<!-- <el-button type="primary" link @click="onAuthority(row)">
					<img src="@/assets/images/tableIcon/配置权限.png" alt="" class="configureIcon" />
					<span>配置工程</span>
				</el-button> -->
				<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>

		<el-dialog title="配置工程" width="30%" show-close v-model="authorityVisible">
			<el-table ref="authorityTable" :data="authorityColumns" style="width: 100%" @selection-change="handleSelectionChange">
				<el-table-column type="selection" width="55" />
				<el-table-column label="工程名称" property="engineeringName"> </el-table-column>
			</el-table>
			<template #footer>
				<span class="dialog-footer">
					<el-button class="cancelButtonStyle" @click="authorityVisible = false">取消</el-button>
					<el-button type="primary" @click="onSubmit">保存</el-button>
				</span>
			</template>
		</el-dialog>

		<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="govermentUseruserManage">
import { ref, reactive, onMounted, nextTick } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Delete } from "@element-plus/icons-vue";
import { useRouter } from "vue-router";
import { User } from "@/api/interface";
import { jxj_User } from "@/api/types";
import { ColumnProps } from "@/components/ProTable/interface";
import { useHandleData } from "@/hooks/useHandleData";
import ProTable from "@/components/ProTable/index.vue";
import { getUserPage, addUser, editUser, deleteUser, getRoleNamelist, getTreeList } from "@/api/modules/goverment";
import { GlobalStore } from "@/stores";
import DialogForm from "@/components/DialogForm/index.vue";
import { getuserDataScope, editUserDataScope } from "@/api/modules/auth";
import { getengineeringList } from "@/api/modules/project";

interface authorityColumns {
	relevanceId: string;
	userId: string;
	engineeringSn?: string;
}

const router = useRouter();
const store = GlobalStore();
const visible = ref(false);
const authorityVisible = ref(false);
const title = ref("");
const formData = ref({
	realName: "",
	userTel: "",
	account: "",
	password: "",
	email: "",
	state: 1,
	sex: "",
	department: "",
	jobName: "",
	roleId: "",
	remark: ""
});
// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref();
const authorityTable = ref();

const multipleSelection = ref<authorityColumns[]>([]);

// 表格配置项
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 authorityColumns = ref([
	{ type: "selection", fixed: "left", width: 80 },
	{ prop: "engineeringName", label: "项目名称" }
]);

// 弹窗中的配置
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 initParam = reactive({
	// type: 1
});

// 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)
	};
};

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

// 弹窗的表格多选框选择后的数据处理
const handleSelectionChange = (val: authorityColumns[]) => {
	multipleSelection.value = val.map(item => {
		return {
			relevanceId: item.engineeringSn,
			userId: UserId.value
		};
	});
};

const onSubmit = async () => {
	await editUserDataScope({ userId: UserId.value, systemUserDataScopes: multipleSelection.value });
	ElMessage.success("编辑成功");
	authorityVisible.value = false;
};

// 修改数据按钮
const handleEditItem = async (index: number, row: any) => {
	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 handleDeleteItem = async (params: jxj_User.ResUserList) => {
	await useHandleData(deleteUser, { userId: params.userId }, `删除【${params.account}】`);
	proTable.value.getTableList();
};

// 页面新增，编辑数据
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;
};

onMounted(async () => {
	const res = await getRoleNamelist({ state: 1 });
	const res1 = await getTreeList({ deptId: "", status: 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
		};
	});
	// treeDeptList.value = res.result;
});
</script>
