<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.projectName || data.engineeringName }}</span>
					<div class="leftMenu_item">
						<div class="leftMenu_item flx-justify-between">
							<div style="margin-top: 5px" class="flx-justify-between">
								<img style="margin-right: 5px" src="@/assets/images/AIwaring/dustMap.png" alt="" />
								<span class="middleSize">{{ data.projectAddress || data.address }}</span>
							</div>
							<!-- <div>
							<img src="@/assets/images/AIwaring/报警.png" alt="" />
							<span class="middleSize">今日报警次数：{{ data.todayAlarm }}</span>
						</div> -->
						</div>
					</div>
				</div>
			</template>
		</LeftMenu>
		<div class="table-box">
			<div class="search-select">
				<el-card shadow="never" class="topCard">
					<span style="margin: 0 10px 2px 20px">工程名称</span>
					<el-input style="width: 200px" v-model="searchForm.name" clearable placeholder="请输入" />
					<span style="margin: 0 10px 2px 10px">状态</span>
					<el-select style="width: 200px" v-model="searchForm.state" clearable placeholder="请选择">
						<el-option v-for="item in statusList" :key="item.value" :label="item.label" :value="item.value" />
					</el-select>
					<span style="margin: 0 10px 2px 20px">提交时间</span>
					<el-date-picker
						v-model="searchForm.timeRange"
						style="width: 300px"
						type="daterange"
						range-separator="至"
						format="YYYY-MM-DD"
						value-format="YYYY-MM-DD"
						start-placeholder="开始日期"
						end-placeholder="结束日期"
					>
					</el-date-picker>
					<el-button type="primary" style="margin-left: 20px" @click="getDataList()">查询</el-button>
				</el-card>
			</div>
			<div class="statistics-table">
				<el-table
					:data="tableData"
					style="width: 100%; flex: 1"
					row-key="id"
					:tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
				>
					<el-table-column align="center" prop="name" width="200" label="分部分项工程名称"></el-table-column>
					<el-table-column align="center" prop="planStartTime" label="计划开始日期"></el-table-column>
					<el-table-column align="center" prop="planEndTime" label="截止完成日期"></el-table-column>
					<el-table-column align="center" prop="realEndTime" label="实际完成日期"></el-table-column>
					<el-table-column align="center" prop="commander" label="负责人"></el-table-column>
					<el-table-column align="center" prop="completeRatio" label="完成比率(%)"></el-table-column>
					<el-table-column align="center" label="状态">
						<template #default="scope">
							<span>{{
								scope.row.state == 1
									? "未开始"
									: scope.row.state == 2
									? "进行中"
									: scope.row.state == 3
									? "已完成"
									: scope.row.state == 4
									? "逾期未开始"
									: scope.row.state == 5
									? "逾期进行中"
									: scope.row.state == 6
									? "逾期已完成"
									: ""
							}}</span>
						</template>
					</el-table-column>
					<el-table-column align="center" width="100" label="操作">
						<template #default="scope">
							<el-button type="primary" link @click="handleEditItem(scope.row)">
								<img src="@/assets/images/tableIcon/updateIcon.png" alt="" class="configureIcon" />
								<span>查看</span>
							</el-button>
						</template>
					</el-table-column>
					<template #empty>
						<div class="table-empty">
							<slot name="empty">
								<img src="@/assets/images/notData.png" alt="notData" />
								<div>暂无数据</div>
							</slot>
						</div>
					</template>
				</el-table>
				<Pagination :pageable="pageable" :handleSizeChange="handleSizeChange" :handleCurrentChange="handleCurrentChange" />
			</div>
			<!-- 新增子分部分项 -->
			<el-dialog class="imgDialog" :title="newTitle" width="40%" v-model="childrenVisible" show-close>
				<el-form class="diaForm" :model="childrenFormData" ref="ruleFormRef" label-width="160px">
					<el-form-item v-if="newTitle == '新增子项'" label="父部分项名称：">
						<el-input disabled :value="parentObj.name" placeholder="请输入" />
					</el-form-item>
					<el-form-item label="分部分项名称：" prop="name">
						<el-input disabled v-model="childrenFormData.name" placeholder="请输入" />
					</el-form-item>
					<el-form-item label="施工位置：" prop="buildAddress">
						<el-input disabled v-model="childrenFormData.buildAddress" placeholder="请输入" />
					</el-form-item>
					<el-form-item label="单位：" prop="unit">
						<el-input disabled v-model="childrenFormData.unit" placeholder="请输入" />
					</el-form-item>
					<el-form-item label="工作量：" prop="workload">
						<el-input disabled v-model="childrenFormData.workload" placeholder="请输入" />
					</el-form-item>
					<el-form-item label="完成比率：" prop="completeRatio">
						<el-input disabled v-model="childrenFormData.completeRatio" placeholder="请输入" />
					</el-form-item>
					<el-form-item label="任务描述：" prop="taskDesc">
						<el-input disabled v-model="childrenFormData.taskDesc" type="textarea" :rows="3" placeholder="请输入" />
					</el-form-item>
					<el-form-item label="状态：" prop="state">
						<el-select disabled style="width: 100%" v-model="childrenFormData.state" clearable placeholder="请选择">
							<el-option v-for="item in statusList" :key="item.value" :label="item.label" :value="item.value" />
						</el-select>
					</el-form-item>
					<el-form-item label="预计开始日期：" prop="planStartTime">
						<el-date-picker
							style="width: 100%"
							v-model="childrenFormData.planStartTime"
							format="YYYY-MM-DD"
							value-format="YYYY-MM-DD"
							type="datetime"
							disabled
							placeholder="请选择时间"
						/>
					</el-form-item>
					<el-form-item label="预计完成日期：" prop="planEndTime">
						<el-date-picker
							style="width: 100%"
							v-model="childrenFormData.planEndTime"
							format="YYYY-MM-DD"
							value-format="YYYY-MM-DD"
							type="datetime"
							disabled
							placeholder="请选择时间"
						/>
					</el-form-item>
					<el-form-item label="重要程度：" prop="importance">
						<el-input disabled v-model="childrenFormData.importance" placeholder="请输入" />
					</el-form-item>
					<el-form-item label="负责人：" prop="commander">
						<el-input disabled v-model="childrenFormData.commander" placeholder="请输入" />
					</el-form-item>
					<el-form-item label="逾期问题描述：" prop="overdueIssueDesc">
						<el-input v-model="childrenFormData.overdueIssueDesc" placeholder="请输入" />
					</el-form-item>
					<el-form-item label="整改期限：" prop="deadline">
						<el-date-picker
							style="width: 100%"
							v-model="childrenFormData.deadline"
							format="YYYY-MM-DD"
							value-format="YYYY-MM-DD"
							type="datetime"
							placeholder="请选择时间"
						/>
					</el-form-item>
					<el-form-item label="逾期文件说明：" prop="overdueIssueFile">
						<el-upload
							ref="upload"
							:headers="headers"
							:file-list="fileList1"
							class="upload-demo"
							:action="`${baseUrl}` + '/xmgl/file/upload'"
							:on-remove="onRemove"
							disabled
							multiple
							:limit="1"
							:on-success="uploadSuccess"
							style="width: 100%"
						>
							<el-button class="uploadBtn" type="primary" @click="onDowmload('overdueIssueFile')">点击下载</el-button>
						</el-upload>
					</el-form-item>
					<el-form-item label="附件：" prop="annexFile">
						<el-upload
							ref="upload"
							:headers="headers"
							:file-list="fileList"
							class="upload-demo"
							:action="`${baseUrl}` + '/xmgl/file/upload'"
							:on-remove="onRemove"
							disabled
							multiple
							:limit="1"
							:on-success="uploadSuccess"
							style="width: 100%"
						>
							<el-button class="uploadBtn" type="primary" @click="onDowmload('annexFile')">点击下载</el-button>
						</el-upload>
					</el-form-item>
				</el-form>
			</el-dialog>
		</div>
	</div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, watch } from "vue";
import { getDustprojectPage, getDustengineeringPage, bigItemGovermentList } from "@/api/modules/goverment";
import Pagination from "@/components/ProTable/components/Pagination.vue";
import { ElMessage, UploadProps, ElMessageBox } from "element-plus";
import { GlobalStore } from "@/stores";
import LeftMenu from "@/components/LeftMenu/LeftMenu.vue";
import { useDownload } from "@/hooks/useDownload";
import { exportApp } from "@/api/modules/jxjview";
const statusList = ref([
	{ label: "未开始", value: 1 },
	{ label: "进行中", value: 2 },
	{ label: "已完成", value: 3 },
	{ label: "逾期未开始", value: 4 },
	{ label: "逾期进行中", value: 5 },
	{ label: "逾期已完成", value: 6 }
]);
const tableData = ref([]);
const pages = ref({
	pageNo: 1,
	pageSize: 7,
	total: 0
});
const records = ref([]);
const active = ref(0);
const baseUrl = import.meta.env.VITE_API_URL;
const globalStore = GlobalStore();
const fileList = ref([]);
const fileList1 = ref([]);
const headers = ref({ Authorization: "Bearer " + globalStore.token });
const childrenFormData = ref({
	name: "",
	buildAddress: "",
	workload: "",
	unit: "",
	taskDesc: "",
	planStartTime: "",
	planEndTime: "",
	importance: "",
	commander: "",
	overdueIssueDesc: "",
	deadline: "",
	overdueIssueFile: "",
	annexFile: "",
	completeRatio: "",
	state: null
});
interface formData {
	title: string;
	uploadTime: string;
	remark: string;
	videoUrl: string;
}
const formData = ref<formData>({
	title: "",
	uploadTime: "",
	remark: "",
	videoUrl: ""
});
const visible = ref(false);
const title = ref("新增录像");
const newTitle = ref("新增");
const parentObj = ref({
	name: ""
});
const childrenVisible = ref(false);
const pageable = ref({
	pageNo: 1,
	pageSize: 12,
	total: 0
});
const searchForm = ref({
	name: "",
	state: null,
	realEndTime_begin: "",
	realEndTime_end: "",
	timeRange: []
});
const onDowmload = (key: string) => {
	if (childrenFormData.value[key]) {
		ElMessageBox.confirm("确认下载数据?", "温馨提示", { type: "warning" }).then(() =>
			useDownload(exportApp, "附件文件", { fileUrl: childrenFormData.value[key] })
		);
	} else {
		ElMessage.error("暂无可下载文件");
	}
};
const handleSizeChange = (val: any) => {
	pageable.value.pageNo = 1;
	pageable.value.pageSize = val;
	getDataList();
};
const handleCurrentChange = (val: any) => {
	pageable.value.pageNo = val;
	getDataList();
};
const uploadSuccess = (response: any) => {
	ElMessage.success("上传成功");
	childrenFormData.value.annexFile = response.result.url;
	fileList.value = [{ name: response.result.originalFilename, url: response.result.downloadPath }];
};
const onRemove: UploadProps["onRemove"] = (file, uploadFiles) => {
	childrenFormData.value.annexFile = "";
	fileList.value = reactive([]);
};
// 修改数据按钮
const handleEditItem = async (row: any) => {
	console.log(row);
	parentObj.value = row;
	newTitle.value = "查看";
	childrenFormData.value = { ...row };
	if (row.annexFile) {
		fileList.value = [{ name: "文件", url: row.annexFile }];
	}
	if (row.overdueIssueFile) {
		fileList1.value = [{ name: "文件", url: row.overdueIssueFile }];
	}
	childrenVisible.value = true;
};
const getDataList = async () => {
	console.log(searchForm.value);
	let requestData = {
		...searchForm.value,
		realEndTime_begin: searchForm.value.timeRange && searchForm.value.timeRange.length > 0 ? searchForm.value.timeRange[0] : "",
		realEndTime_end: searchForm.value.timeRange && searchForm.value.timeRange.length > 0 ? searchForm.value.timeRange[1] : "",
		pageNo: pageable.value.pageNo,
		pageSize: pageable.value.pageSize
	};
	delete requestData.timeRange;
	if (active.value === 0) {
		requestData.projectSn = searchSn.value;
	} else {
		requestData.engineeringSn = searchSn.value;
	}
	const res = await bigItemGovermentList(requestData);
	if (res) {
		tableData.value = res.result.records;
		pageable.value = reactive({
			pageNo: +res.result.current,
			pageSize: +res.result.size,
			total: +res.result.total
		});
	}
	console.log(res);
};
// 搜索用的项目sn或者工程sn
const searchSn = ref("");

// 项目或者工程名字
const searchName = ref<string>("");
// 页面的项目名称和工程名称的div点击事件
const onSearch = async (params: any) => {
	// 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.projectSn) : (searchSn.value = params.engineeringSn);
	active.value === 0 ? (searchName.value = params.projectName) : (searchName.value = params.engineeringName);
	getDataList();
};
// leftMenu页面的搜索按钮
const onSearchInput = async (params: string) => {
	console.log(params);
	if (active.value === 0) {
		const { result } = await getDustprojectPage({ projectName: params, ...pages.value });
		records.value = result.records;
	} else {
		const { result } = await getDustengineeringPage({ engineeringName: params, ...pages.value });
		records.value = result.records;
	}
};
// leftMenu页面的分页
const onCurChange = async (params: number) => {
	if (active.value === 0) {
		const { result } = await getDustprojectPage({ ...pages.value, pageNo: params });
		records.value = result.records;
	} else {
		const { result } = await getDustengineeringPage({ ...pages.value, pageNo: params });
		records.value = result.records;
		pages.value.total = +result.total;
	}
	pages.value.total = +res.result.total;
};
// 获取项目名称分页
const getProPage = async () => {
	const { result } = await getDustprojectPage(pages.value);
	records.value = result.records;
	records.value.map(item => {
		let showGif = false;
		item.showGif = showGif;
	});
	pages.value.total = Number(result.total);
};
// 获取工程名称分页
const getEngPage = async () => {
	const { result } = await getDustengineeringPage(pages.value);
	records.value = result.records;
	records.value.map(item => {
		let showGif = false;
		item.showGif = showGif;
	});
	pages.value.total = +result.total;
};
watch(
	() => active.value,
	async (value: number) => {
		pages.value.pageNo = 1;
		pages.value.total = 0;
		// console.log(value);

		if (value === 0) {
			await getProPage();
			onSearch(records.value[0]);
		} else {
			await getEngPage();
			onSearch(records.value[0]);
		}
	},
	{
		deep: true
	}
);
onMounted(async () => {
	await getProPage();
	onSearch(records.value[0]);
	searchSn.value = (records.value as any)[0].projectSn;
	searchName.value = (records.value as any)[0].projectName;
});
</script>

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