<template>
	<div class="warning-page">
		<LeftMenu
			v-model="active"
			:tabs="[]"
			:records="records"
			@change-page="onCurChange"
			@search="onSearchInput"
			:pageable="pages"
			class="leftMenu"
		>
			<template #default="{ data }">
				<div class="leftProject" @click="onSearch(data)">
					<span class="projectName">{{
						(data as ResAiProjectPage).projectName || (data as ResAiEngineerPage).engineeringName
					}}</span>
					<div class="leftMenu_item">
						<div class="video">
							<img src="@/assets/images/leftTab/设备列表.png" alt="" />
							<span class="middleSize">影像视频数：{{ data.videoNum }}</span>
						</div>
					</div>
				</div>
			</template>
		</LeftMenu>
		<div class="right_container">
			<!-- <div class="form_div"> -->
			<el-form :model="form" :inline="true" @submit.prevent class="form" ref="FormRef">
				<el-form-item label="标题">
					<el-input v-model="form.title" placeholder="请输入" clearable />
				</el-form-item>
				<el-form-item label="上传时间">
					<el-date-picker
						v-model="form.createTime"
						type="daterange"
						range-separator="至"
						start-placeholder="开始日期"
						end-placeholder="结束日期"
						format="YYYY-MM-DD"
						value-format="YYYY-MM-DD"
					/>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleSearch">查询</el-button>
					<el-button style="background-color: #ffb750; color: #fff" @click="refresh">刷新</el-button>
					<el-button class="addButtonStyle" @click="addVideoData">新增</el-button>
				</el-form-item>
			</el-form>
			<!-- </div> -->

			<div class="imgPage">
				<div class="imgTable" v-if="videoData.records.length">
					<div class="img_item" v-for="item in videoData.records" :key="item.id">
						<!-- <el-image style="width: 100%; height: 182px" :src="item.videoUrl" fit="fill" /> -->
						<video style="width: 100%; height: 182px; object-fit: fill" controls :src="item.videoUrl"></video>
						<div class="page_text flx-justify-column">
							<div class="img_title">
								<span>{{ item.title }}</span>
								<el-button type="primary" link @click="handleEditItem(2, item)">
									<img src="@/assets/images/tableIcon/updateIcon.png" alt="" class="configureIcon" />
									<span>编辑</span>
								</el-button>
								<el-button style="margin-right: 12px" type="danger" link :icon="Delete" @click="deleteAccount(item)"
									>删除</el-button
								>
							</div>
							<div class="img_bottom">
								<!-- <div class="position" style="font-size: 12px">位置：{{ item.deviceName }}</div> -->
								<div style="font-size: 12px">时间：{{ item.uploadTime }}</div>
							</div>
						</div>
					</div>
				</div>
				<div v-else class="table-empty">
					<img src="@/assets/images/notData.png" alt="notData" />
					<div>暂无数据</div>
				</div>
				<!-- :handleSizeChange="handleSizeChange" -->
				<Pagination
					:pageable="pageable"
					:total="pageable.total"
					:page-size="pageable.pageSize"
					layout="prev, pager, next, jumper"
					:handleCurrentChange="handleCurrentChange"
					:background="background"
					class="pagination"
				/>
			</div>
		</div>
	</div>
	<el-dialog class="imgDialog" :title="title" width="40%" v-model="visible" show-close>
		<el-form class="diaForm" :rules="rules" :model="formData" ref="ruleFormRef" label-width="160px">
			<el-form-item label="录像标题：" prop="title">
				<el-input v-model="formData.title" placeholder="请输入" />
			</el-form-item>
			<el-form-item label="上传时间：" prop="uploadTime">
				<el-date-picker
					style="width: 100%"
					v-model="formData.uploadTime"
					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="formData.remark" 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"
					:before-upload="beforeUpload"
					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="confirm(ruleFormRef, formData)"> 保存 </el-button>
			</div>
		</template>
	</el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, watch } from "vue";
import { getAIprojectPage, getAIQuestionPage, addAIrecords, getAiMonitorDev } from "@/api/modules/goverment";
import { videoList, videoDataAdd, videoDataEdit, videoDataDelete, getengineeringPage } from "@/api/modules/enterpriseApi";
import Pagination from "@/components/ProTable/components/Pagination.vue";
import { ElMessage, UploadProps } from "element-plus";
import type { FormRules, FormInstance, UploadInstance } from "element-plus";
import { GlobalStore } from "@/stores";
import { Delete } from "@element-plus/icons-vue";
import { jxj_User } from "@/api/types";
import { useHandleData } from "@/hooks/useHandleData";
import LeftMenu from "@/components/LeftMenu/LeftMenu.vue";
import type { ResAiProjectPage, ResAiEngineerPage } from "@/api/types/government/AIwaring";
function parse(val) {
	return val.trim() ? JSON.parse(val) : {};
}
const pages = ref({
	pageNo: 1,
	pageSize: 7,
	total: 0
});
const records = ref<ResAiProjectPage[] | ResAiEngineerPage[]>([]);
const active = ref(1);
const upload = ref<UploadInstance>();
const fileList = ref([]);
const store = GlobalStore();
const headers = ref({ Authorization: "Bearer " + store.token });
const ruleFormRef = ref<FormInstance>();
const baseUrl = import.meta.env.VITE_API_URL;
interface formData {
	title: string;
	uploadTime: string;
	remark: string;
	videoUrl: string;
}
const formData = ref<formData>({
	title: "",
	uploadTime: "",
	remark: "",
	videoUrl: ""
});
const background = ref(true);
const visible = ref(false);
const title = ref("新增录像");

const rules = reactive<FormRules>({
	title: {
		required: true,
		message: "请输入",
		trigger: "blur"
	},
	uploadTime: {
		required: true,
		message: "请选择",
		trigger: "change"
	},
	remark: {
		required: true,
		message: "请输入",
		trigger: "blur"
	},
	videoUrl: {
		required: true,
		message: "请选择",
		trigger: "change"
	}
});
const pageable = ref({
	pageNo: 1,
	pageSize: 12,
	total: 0
});

const videoData = ref({
	records: []
});
const form = ref({
	title: "",
	createTime: "",
	startTime: "",
	endTime: ""
});
// 搜索用的项目sn或者工程sn
const searchSn = ref("");

// 项目或者工程名字
const searchName = ref<string>("");
// 文件上传之前的钩子函数
const beforeUpload = file => {
	console.log(file);
	const type = file.type;
	if (type != "video/mp4") {
		ElMessage.error("请上传视频文件");
		return false;
	}
};
// 页面的项目名称和工程名称的div点击事件
const onSearch = async (params: ResAiProjectPage | ResAiEngineerPage) => {
	// const { result } = await getAIQuestionPage(
	// 	active.value === 0
	// 		? { projectSn: (params as ResAiProjectPage).projectSn, pageNo: pageable.value.pageNo, pageSize: pageable.value.pageSize }
	// 		: {
	// 				engineeringSn: (params as ResAiEngineerPage).engineeringSn,
	// 				pageNo: pageable.value.pageNo,
	// 				pageSize: pageable.value.pageSize
	// 		  }
	// );
	// pageable.value.total = Number(result.total);
	active.value === 0
		? (searchSn.value = (params as ResAiProjectPage).projectSn)
		: (searchSn.value = (params as ResAiEngineerPage).engineeringSn);
	active.value === 0
		? (searchName.value = (params as ResAiProjectPage).projectName)
		: (searchName.value = (params as ResAiEngineerPage).engineeringName);
	getVideoData();
};
// leftMenu页面的搜索按钮
const onSearchInput = async (params: string) => {
	console.log(params);
	if (active.value === 0) {
		const { result } = await getAIprojectPage({ projectName: params, ...pages.value });
		records.value = result.records;
	} else {
		const { result } = await getengineeringPage({ engineeringName: params, ...pages.value });
		records.value = result.records;
	}
};
// leftMenu页面的分页
const onCurChange = async (params: number) => {
	if (active.value === 0) {
		const { result } = await getAIprojectPage({ ...pages.value, pageNo: params });
		records.value = result.records;
	} else {
		const { result } = await getengineeringPage({ ...pages.value, pageNo: params });
		records.value = result.records;
		pages.value.total = +result.total;
	}
	pages.value.total = +res.result.total;
};
// 删除用户信息
const deleteAccount = async (params: jxj_User.ResUserList) => {
	await useHandleData(videoDataDelete, { id: params.id }, `删除`);
	getVideoData();
	getAIengPage();
};
// 刷新
const refresh = () => {
	form.value = {
		title: "",
		createTime: "",
		startTime: "",
		endTime: ""
	};
	getVideoData();
};
// 查询
const handleSearch = () => {
	console.log(666);
	getVideoData();
};
const handleEditItem = (index: number, row: any) => {
	title.value = "编辑录像";
	formData.value = { ...row };
	console.log(formData.value);
	fileList.value = reactive([{ name: "文件", url: row.videoUrl }]);
	visible.value = true;
};
const getVideoData = async () => {
	let requestData = {
		...pageable.value,
		...form.value,
		startTime: form.value.createTime ? form.value.createTime[0] : "",
		endTime: form.value.createTime ? form.value.createTime[1] : "",
		engineeringSn: searchSn.value ? searchSn.value : ""
	};
	delete requestData.createTime;
	const res = await videoList(requestData);
	videoData.value.records = res.result.records;
	console.log(videoData.value);
	console.log(res);
};

const uploadSuccess = (response: any) => {
	ElMessage.success("上传成功");
	formData.value.videoUrl = response.result.url;
	fileList.value = [{ name: response.result.originalFilename, url: response.result.downloadPath }];
	ruleFormRef.value.validateField("videoUrl");
};
const onRemove: UploadProps["onRemove"] = (file, uploadFiles) => {
	formData.value.videoUrl = "";
	fileList.value = reactive([]);
};
// 新增影像
const addVideoData = () => {
	title.value = "新增录像";
	formData.value = reactive<formData>({
		title: "",
		uploadTime: "",
		remark: "",
		videoUrl: ""
	});
	fileList.value = reactive([]);
	visible.value = true;
};
const confirm = async (formEl: FormInstance | undefined, form: any) => {
	// 标记表单校验
	if (!formEl) return;
	await formEl.validate(async (valid, fields) => {
		if (valid) {
			console.log(666);
			console.log(searchSn.value);
			formData.value.engineeringSn = searchSn.value;
			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();
				getAIengPage();
			}
		} else {
			console.log("error submit!", fields);
			ElMessage({
				showClose: true,
				message: "请完善表单信息！",
				type: "error"
			});
		}
	});
};
// 页面的分页
const handleCurrentChange = async (page: number) => {};
// 获取工程名称分页
const getAIengPage = async () => {
	const { result } = await getengineeringPage(pages.value);
	records.value = result.records;
	pages.value.total = +result.total;
};
onMounted(async () => {
	await getAIengPage();
	searchSn.value = (records.value as ResAiProjectPage[])[0].engineeringSn;
	searchName.value = (records.value as ResAiProjectPage[])[0].engineeringName;
	onSearch(records.value[0]);
});
</script>

<style lang="scss" scoped>
@import "./index.scss";
</style>
