<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 #operation="{ row }">
				<el-button type="primary" link @click="handleAddItem(2, row)">
					<img src="@/assets/images/tableIcon/updateIcon.png" alt="" class="configureIcon" />
					<span>编辑</span>
				</el-button>
			</template>
		</ProTable>
		<changeTheme />
		<!-- 新增分部分项 -->
		<DialogForm
			title="新增分部分项"
			:formConfig="formSubConfig"
			:formData="formSubData"
			v-model:visible="subVisible"
			append-to-body
			width="700px"
			@confirm="saveSubItem"
		>
		</DialogForm>
		<!-- 新增子分部分项 -->
		<el-dialog class="imgDialog" title="新增子分部分项" width="40%" v-model="childrenVisible" show-close>
			<el-form class="diaForm" :rules="rules" :model="childrenFormData" ref="ruleFormRef" label-width="160px">
				<el-form-item label="录像标题：" prop="title">
					<el-input v-model="childrenFormData.name" placeholder="请输入" />
				</el-form-item>
				<el-form-item label="上传时间：" prop="uploadTime">
					<el-date-picker
						style="width: 100%"
						v-model="childrenFormData.name"
						format="YYYY-MM-DD HH:mm:ss"
						value-format="YYYY-MM-DD HH:mm:ss"
						type="datetime"
						placeholder="请选择时间"
					/>
				</el-form-item>
				<el-form-item label="备注：" prop="remark">
					<el-input v-model="childrenFormData.name" type="textarea" :rows="3" placeholder="请输入" />
				</el-form-item>
				<el-form-item label="录像文件：" prop="videoUrl">
					<el-upload
						ref="upload"
						:headers="headers"
						:file-list="fileList"
						class="upload-demo"
						:action="`${baseUrl}` + '/xmgl/file/upload'"
						:on-remove="onRemove"
						multiple
						:limit="1"
						:on-success="uploadSuccess"
						style="width: 100%"
					>
						<el-button class="uploadBtn" type="primary">点击上传</el-button>
					</el-upload>
				</el-form-item>
			</el-form>
			<template #footer>
				<div>
					<el-button class="cancelButtonStyle" @click="visible = false">取消</el-button>
					<el-button type="primary" @click="childrenConfirm(ruleFormRef, childrenFormData)"> 保存 </el-button>
				</div>
			</template>
		</el-dialog>
	</div>
</template>

<script setup lang="tsx" name="ProjectSupervisionRecord">
import { ref, reactive, nextTick, computed } from "vue";
import { ElMessage, ElMessageBox, UploadProps } from "element-plus";
import { useRouter } from "vue-router";
import { ColumnProps } from "@/components/ProTable/interface";
import ProTable from "@/components/ProTable/index.vue";
import changeTheme from "@/components/changeTheme/index.vue";
import { getRoleList, getTreemRoleList, getTreeByIdList } from "@/api/modules/project";
import { GlobalStore } from "@/stores";
import DialogForm from "@/components/DialogForm/index.vue";
import type { FormRules, FormInstance, UploadInstance } from "element-plus";
const globalStore = GlobalStore();
const baseUrl = import.meta.env.VITE_API_URL;
const fileList = ref([]);
const headers = ref({ Authorization: "Bearer " + globalStore.token });
const ruleFormRef = ref<FormInstance>();
const rules = reactive<FormRules>({
	name: {
		required: true,
		message: "请输入",
		trigger: "blur"
	}
});
const childrenVisible = ref(false);
const subVisible = ref(false);
// 弹窗中的配置
const formSubConfig = {
	formItemConfig: [
		{
			label: "分部分项名称",
			prop: "name",
			type: "input"
		}
	],
	rules: {
		name: [
			{
				required: true,
				message: "请输入",
				trigger: "blur"
			}
		]
	}
};
const treeRef = ref(null);

const datas = reactive([]);
const router = useRouter();
const visible = ref(false);
const drawerVisible = ref(false);
const title = ref("");
const formSubData = ref({
	name: ""
});
const childrenFormData = ref({
	name: ""
});
// 获取 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: "时间筛选",
		isShow: false,
		search: {
			el: "date-picker",
			props: {
				type: "daterange",
				format: "YYYY-MM-DD",
				valueFormat: "YYYY-MM-DD"
				// defaultTime: defaultTime2
			}
		}
	},
	{ prop: "operation", label: "操作", fixed: "right" }
];
const childrenConfirm = async (formEl: FormInstance | undefined, form: any) => {
	// 标记表单校验
	if (!formEl) return;
	await formEl.validate(async (valid, fields) => {
		if (valid) {
			// if (formData.value.id) {
			// 	const res = await videoDataEdit(form);
			// 	ElMessage.success("编辑成功");
			// 	visible.value = false;
			// 	getVideoData();
			// } else {
			// 	const res = await videoDataAdd(form);
			// 	ElMessage.success("保存成功");
			// 	visible.value = false;
			// 	getVideoData();
			// }
		} else {
			console.log("error submit!", fields);
			ElMessage({
				showClose: true,
				message: "请完善表单信息！",
				type: "error"
			});
		}
	});
};
const uploadSuccess = (response: any) => {
	ElMessage.success("上传成功");
	// formData.value.videoUrl = response.result.url;
	// fileList.value = [{ name: response.result.originalFilename, url: response.result.downloadPath }];
};
const onRemove: UploadProps["onRemove"] = (file, uploadFiles) => {
	// formData.value.videoUrl = "";
	fileList.value = reactive([]);
};
const saveSubItem = 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;
};
// 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 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);
};

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：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({});
	} 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));
	});
};
</script>
<style scoped lang="scss">
.table-box {
	position: relative;
	.imgDialog {
		.uploadBtn {
			color: white;
			border: 1px solid #087ba4;
			background: #087ba4;
		}
	}
}
</style>
