<template>
	<div class="warning-page">
		<LeftMenu
			v-model="active"
			:tabs="['项目名称', '工程名称']"
			:records="records"
			:activeIndex="modelActive"
			@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>
					</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-button v-auth="'sub_item_add'" type="primary" style="margin-left: 20px" @click="handleAddItem()">新增</el-button>
					<el-upload
						v-auth="'sub_item_import'"
						accept=".mpp"
						:headers="headers"
						:action="`${baseUrl}` + '/project/projectSubItem/importMpp'"
						:on-success="uploadFileSuccess"
						:data="{
							engineeringSn: searchSn
						}"
						style="margin-left: 20px"
						:show-file-list="false"
					>
						<el-button type="primary">导入</el-button>
					</el-upload>
				</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="计划开始日期" width="200"></el-table-column>
					<el-table-column align="center" prop="planEndTime" label="截止完成日期" width="200"></el-table-column>
					<el-table-column align="center" prop="realEndTime" label="实际完成日期" width="200"></el-table-column>
					<el-table-column align="center" prop="commander" label="负责人" width="150"></el-table-column>
					<el-table-column align="center" prop="completeRatio" width="200" label="完成比率(%)"></el-table-column>
					<el-table-column align="center" label="审核状态" width="150">
						<template #default="scope">
							<span>{{ scope.row.approvalStatus == 0 ? "未审核" : scope.row.approvalStatus == 1 ? "审核通过" : "已驳回" }}</span>
						</template>
					</el-table-column>
					<el-table-column align="center" label="状态" width="150">
						<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
									? "逾期完成"
									: scope.row.state == 7
									? "暂停"
									: ""
							}}</span>
						</template>
					</el-table-column>
					<el-table-column align="center" width="420" label="操作">
						<template #default="scope">
							<el-button
								v-if="scope.row.parentId == 0"
								v-auth="'sub_item_add'"
								type="primary"
								link
								:icon="CirclePlus"
								@click="handleAddSubItem(scope.row)"
								>子分项</el-button
							>
							<el-button v-auth="'sub_item_update'" type="primary" link @click="handleEditItem(1, scope.row)">
								<img src="@/assets/images/tableIcon/updateIcon.png" alt="" class="configureIcon" />
								<span>编辑</span>
							</el-button>
							<el-button v-auth="'sub_item_del'" type="primary" link :icon="Delete" @click="handleDeleteItem(scope.row)"
								>删除</el-button
							>
							<el-button type="primary" link @click="handleEditItem(2, scope.row)">
								<img src="@/assets/images/tableIcon/updateIcon.png" alt="" class="configureIcon" />
								<span>查看</span>
							</el-button>
							<el-button
								v-auth="'sub_item_examine'"
								v-if="scope.row.approvalStatus == 0"
								type="primary"
								link
								@click="auditData(scope.row)"
								><img src="@/assets/images/tableIcon/seal.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>
			<changeTheme />
			<!-- 新增子分部分项 -->
			<el-dialog class="imgDialog" :title="newTitle" width="40%" v-model="childrenVisible" show-close>
				<el-form class="diaForm" :rules="rules" :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 v-model="childrenFormData.name" placeholder="请输入" />
					</el-form-item>
					<el-form-item label="施工位置：" prop="buildAddress">
						<el-input v-model="childrenFormData.buildAddress" placeholder="请输入" />
					</el-form-item>
					<el-form-item label="单位：" prop="unit">
						<el-input v-model="childrenFormData.unit" placeholder="请输入" />
					</el-form-item>
					<el-form-item label="工作量：" prop="workload">
						<el-input v-model="childrenFormData.workload" placeholder="请输入" />
					</el-form-item>
					<el-form-item label="完成比率：" prop="completeRatio">
						<el-input v-model="childrenFormData.completeRatio" placeholder="请输入" />
					</el-form-item>
					<el-form-item label="任务描述：" prop="taskDesc">
						<el-input v-model="childrenFormData.taskDesc" type="textarea" :rows="3" placeholder="请输入" />
					</el-form-item>
					<el-form-item label="状态：" prop="state">
						<el-select 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"
							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"
							placeholder="请选择时间"
						/>
					</el-form-item>
					<el-form-item label="实际完成日期：" prop="realEndTime">
						<el-date-picker
							style="width: 100%"
							v-model="childrenFormData.realEndTime"
							format="YYYY-MM-DD"
							value-format="YYYY-MM-DD"
							type="datetime"
							placeholder="请选择时间"
						/>
					</el-form-item>
					<el-form-item label="重要程度：" prop="importance">
						<el-input v-model="childrenFormData.importance" placeholder="请输入" />
					</el-form-item>
					<el-form-item label="负责人：" prop="commander">
						<el-input 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="upload1"
							:headers="headers"
							:file-list="fileList1"
							class="upload-demo"
							:action="`${baseUrl}` + '/xmgl/file/upload'"
							:on-remove="onRemove1"
							multiple
							:limit="1"
							:on-success="uploadSuccess1"
							style="width: 100%"
						>
							<el-button class="uploadBtn" type="primary">点击上传</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"
							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 v-if="newTitle != '查看'">
					<div>
						<el-button class="hzCancelStyle" @click="childrenVisible = false">取消</el-button>
						<el-button v-auth="'sub_item_add'" type="primary" @click="childrenConfirm(ruleFormRef, childrenFormData)">
							保存
						</el-button>
					</div>
				</template>
			</el-dialog>
			<!-- 审核 -->
			<el-dialog title="审批" width="26%" v-model="aproveVisible" show-close>
				<div style="display: flex; align-items: center">
					<el-icon style="color: var(--el-menu-text-color); margin: 0 12px; font-size: 20px"><WarningFilled /></el-icon>
					<span>是否通过审批?</span>
				</div>

				<template #footer>
					<span class="dialog-footer">
						<el-button class="hzCancelStyle" @click="reject">驳回</el-button>
						<el-button type="primary" @click="onSubmit">通过</el-button>
					</span>
				</template>
			</el-dialog>
		</div>
	</div>
</template>

<script lang="ts" setup name="divisionsAndISubItems">
import { ref, reactive, onMounted, onBeforeMount, watch } from "vue";
import type { FormRules, FormInstance } from "element-plus";
import { Delete, CirclePlus } from "@element-plus/icons-vue";
import { getDustprojectPage } from "@/api/modules/goverment";
import Pagination from "@/components/ProTable/components/Pagination.vue";
import { ElMessage, UploadProps } from "element-plus";
import changeTheme from "@/components/changeTheme/index.vue";
import { GlobalStore } from "@/stores";
import LeftMenu from "@/components/LeftMenu/LeftMenu.vue";
import {
	bigItemGovermentList,
	bigItemGovermentEngList,
	bigItemGovermentAudit,
	addEntBigItem,
	updateEntBigItem,
	deleteEntBigItem
} from "@/api/modules/huizhou";
import { jxj_User } from "@/api/types";
import { useHandleData } from "@/hooks/useHandleData";
import { useRoute } from "vue-router";
import { sendIframeMessage } from "@/utils/util";
const route = useRoute();
const modelActive = ref(0);
const rules = reactive<FormRules>({
	name: {
		required: true,
		message: "请输入",
		trigger: "blur"
	},
	workload: {
		required: true,
		message: "请输入",
		trigger: "blur"
	},
	completeRatio: {
		required: true,
		message: "请输入",
		trigger: "blur"
	},
	state: {
		required: true,
		message: "请选择",
		trigger: "change"
	},
	planStartTime: {
		required: true,
		message: "请选择",
		trigger: "change"
	},
	planEndTime: {
		required: true,
		message: "请选择",
		trigger: "change"
	}
});
const ruleFormRef = ref();
const statusList = ref([
	{ label: "未开始", value: 1 },
	{ label: "推进中", value: 2 },
	{ label: "按期完成", value: 3 },
	{ label: "临期", value: 4 },
	{ label: "超期", value: 5 },
	{ label: "逾期完成", value: 6 },
	{ label: "暂停", value: 7 }
]);
const tableData = ref([]);
const pages = ref({
	pageNo: 1,
	pageSize: 7,
	total: 0
});
const records = ref([]);
const active = ref(1);
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 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 aproveVisible = ref(false);
const rowId = ref("");
const form = ref({
	title: "",
	createTime: "",
	startTime: "",
	endTime: ""
});
// 搜索用的项目sn或者工程sn
const searchSn = ref("");

// 项目或者工程名字
const searchName = ref<string>("");

const reject = async () => {
	await bigItemGovermentAudit({ id: rowId.value, approvalStatus: 2 });
	ElMessage.success("已驳回");
	aproveVisible.value = false;
	getDataList();
};
const onSubmit = async () => {
	await bigItemGovermentAudit({ id: rowId.value, approvalStatus: 1 });
	ElMessage.success("通过成功");
	aproveVisible.value = false;
	getDataList();
};
// 审核
const auditData = async (row: any) => {
	rowId.value = row.id;
	aproveVisible.value = true;
};
// 删除
const handleDeleteItem = async (params: jxj_User.ResUserList) => {
	await useHandleData(deleteEntBigItem, { id: params.id }, `删除【${params.name}】`);
	getDataList();
};
const handleAddSubItem = (row: any) => {
	parentObj.value = row;
	childrenFormData.value = reactive({
		name: "",
		buildAddress: "",
		workload: "",
		unit: "",
		taskDesc: "",
		planStartTime: "",
		planEndTime: "",
		importance: "",
		commander: "",
		overdueIssueDesc: "",
		deadline: "",
		overdueIssueFile: "",
		annexFile: "",
		completeRatio: "",
		state: null
	});
	console.log(parentObj.value);
	newTitle.value = "新增子项";
	fileList.value = reactive([]);
	fileList1.value = reactive([]);
	childrenVisible.value = true;
};
// 导入文件
const uploadFileSuccess = (response: any) => {
	console.log(response);
	if (response.result) {
		getDataList();
	}
};
const childrenConfirm = async (formEl: FormInstance | undefined, form: any) => {
	// 标记表单校验
	if (!formEl) return;
	await formEl.validate(async (valid, fields) => {
		if (valid) {
			form.engineeringSn = searchSn.value;
			console.log(form);
			if (form.id) {
				if (newTitle.value == "编辑子项") {
					form.parentId = parentObj.value.parentId;
				}
				const res = await updateEntBigItem(form);
				ElMessage.success("编辑成功");
				childrenVisible.value = false;
			} else {
				if (newTitle.value == "新增子项") {
					form.parentId = parentObj.value.id;
				}
				const res = await addEntBigItem(form);
				ElMessage.success("保存成功");
				childrenVisible.value = false;
			}
			getDataList();
		} else {
			console.log("error submit!", fields);
			ElMessage({
				showClose: true,
				message: "请完善表单信息！",
				type: "error"
			});
		}
	});
};
const handleAddItem = () => {
	childrenFormData.value = reactive({
		name: "",
		buildAddress: "",
		workload: "",
		unit: "",
		taskDesc: "",
		planStartTime: "",
		planEndTime: "",
		importance: "",
		commander: "",
		overdueIssueDesc: "",
		deadline: "",
		overdueIssueFile: "",
		annexFile: "",
		completeRatio: "",
		state: null
	});
	newTitle.value = "新增";
	fileList.value = reactive([]);
	fileList1.value = reactive([]);
	childrenVisible.value = true;
};
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 (index: number, row: any) => {
	console.log(row);
	if (index == 1) {
		if (row.parentId != 0) {
			newTitle.value = "编辑子项";
		} else {
			newTitle.value = "编辑";
		}
	} else {
		newTitle.value = "查看";
	}
	parentObj.value = row;
	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[0],
		realEndTime_end: 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);
};
// 页面的项目名称和工程名称的div点击事件
const onSearch = async (params: any) => {
	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 bigItemGovermentEngList({ 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 bigItemGovermentEngList({ ...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 bigItemGovermentEngList(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 getEngPage();
	searchSn.value = (records.value as any[])[0].projectSn;
	searchName.value = (records.value as any[])[0].projectName;
	if (route.query.projectName) {
		let defaultActive = records.value.findIndex((item: any) => {
			return route.query.projectName == item.engineeringName;
		});
		if (defaultActive != -1) {
			modelActive.value = defaultActive;
			onSearch(records.value[defaultActive]);
		}
	} else {
		onSearch(records.value[0]);
	}
	await sendIframeMessage({ obj: { path: route.path } }, 2, undefined);
});
</script>

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