<template>
	<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 type="primary" style="margin-left: 20px" @click="handleAddItem()">新增</el-button>
				<el-upload
					accept=".mpp"
					:headers="headers"
					:action="`${baseUrl}` + '/project/projectSubItem/importMpp'"
					:on-success="uploadFileSuccess"
					multiple
					:limit="1"
					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="left" prop="name" 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="300" label="操作">
					<template #default="scope">
						<el-button v-if="scope.row.parentId == 0" type="primary" link :icon="CirclePlus" @click="handleAddSubItem(scope.row)"
							>子分项</el-button
						>
						<el-button type="primary" link @click="handleEditItem(scope.row)">
							<img src="@/assets/images/tableIcon/updateIcon.png" alt="" class="configureIcon" />
							<span>编辑</span>
						</el-button>
						<el-button type="danger" link :icon="Delete" @click="handleDeleteItem(scope.row)">删除</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" :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>
				<div>
					<el-button class="hzCancelStyle" @click="childrenVisible = 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, onMounted } from "vue";
import { Delete, CirclePlus } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox, UploadProps } from "element-plus";
import { useRouter } from "vue-router";
import { addBigItem, updateBigItem, bigItemList, deleteBigItem } from "@/api/modules/project";
import { GlobalStore } from "@/stores";
import type { FormRules, FormInstance, UploadInstance } from "element-plus";
import Pagination from "@/components/ProTable/components/Pagination.vue";
import { jxj_User } from "@/api/types";
import { useHandleData } from "@/hooks/useHandleData";
const parentObj = ref({
	name: ""
});
const statusList = ref([
	{ label: "未开始", value: 1 },
	{ label: "进行中", value: 2 },
	{ label: "已完成", value: 3 },
	{ label: "逾期未开始", value: 4 },
	{ label: "逾期进行中", value: 5 },
	{ label: "逾期已完成", value: 6 }
]);
const pageable = ref({
	pageNo: 1,
	pageSize: 12,
	total: 0
});
const tableData = ref([]);
const searchForm = ref({
	name: "",
	state: null,
	realEndTime_begin: "",
	realEndTime_end: "",
	timeRange: []
});
const globalStore = GlobalStore();
const baseUrl = import.meta.env.VITE_API_URL;
const fileList1 = ref([]);
const fileList = ref([]);
const headers = ref({ Authorization: "Bearer " + globalStore.token });
const ruleFormRef = ref<FormInstance>();
const newTitle = ref("新增");
const rules = reactive<FormRules>({
	name: {
		required: true,
		message: "请输入",
		trigger: "blur"
	}
});
const childrenVisible = ref(false);
const router = useRouter();
const childrenFormData = ref({
	name: "",
	buildAddress: "",
	workload: "",
	unit: "",
	taskDesc: "",
	planStartTime: "",
	planEndTime: "",
	realEndTime: "",
	importance: "",
	commander: "",
	overdueIssueDesc: "",
	deadline: "",
	overdueIssueFile: "",
	annexFile: "",
	completeRatio: "",
	state: null
});
// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref();

const getId = ref<number | undefined>(undefined);

// 删除用户信息
const handleDeleteItem = async (params: jxj_User.ResUserList) => {
	await useHandleData(deleteBigItem, { id: params.id }, `删除【${params.name}】`);
	getDataList();
};
const handleSizeChange = (val: any) => {
	pageable.value.pageNo = 1;
	pageable.value.pageSize = val;
	getDataList();
};
const handleCurrentChange = (val: any) => {
	pageable.value.pageNo = val;
	getDataList();
};
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;
	const res = await bigItemList(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);
};
const childrenConfirm = async (formEl: FormInstance | undefined, form: any) => {
	// 标记表单校验
	if (!formEl) return;
	await formEl.validate(async (valid, fields) => {
		if (valid) {
			if (form.id) {
				if (newTitle.value == "编辑子项") {
					form.parentId = parentObj.value.parentId;
				}
				const res = await updateBigItem(form);
				ElMessage.success("编辑成功");
				childrenVisible.value = false;
			} else {
				if (newTitle.value == "新增子项") {
					form.parentId = parentObj.value.id;
				}
				const res = await addBigItem(form);
				ElMessage.success("保存成功");
				childrenVisible.value = false;
			}
			getDataList();
		} else {
			console.log("error submit!", fields);
			ElMessage({
				showClose: true,
				message: "请完善表单信息！",
				type: "error"
			});
		}
	});
};
// 导入文件
const uploadFileSuccess = (response: any) => {
	console.log(response);
	if (response.result) {
		getDataList();
	}
};
const uploadSuccess1 = (response: any) => {
	ElMessage.success("上传成功");
	childrenFormData.value.overdueIssueFile = response.result.url;
	fileList1.value = [{ name: response.result.originalFilename, url: response.result.downloadPath }];
};
const uploadSuccess = (response: any) => {
	ElMessage.success("上传成功");
	childrenFormData.value.annexFile = response.result.url;
	fileList.value = [{ name: response.result.originalFilename, url: response.result.downloadPath }];
};
const onRemove1: UploadProps["onRemove"] = (file, uploadFiles) => {
	childrenFormData.value.overdueIssueFile = "";
	fileList1.value = reactive([]);
};
const onRemove: UploadProps["onRemove"] = (file, uploadFiles) => {
	childrenFormData.value.annexFile = "";
	fileList.value = reactive([]);
};
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 importData = () => {};
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 handleEditItem = async (row: any) => {
	console.log(row);
	parentObj.value = row;
	if (row.parentId != 0) {
		newTitle.value = "编辑子项";
	} else {
		newTitle.value = "编辑";
	}
	childrenFormData.value = { ...row };
	fileList.value = [{ name: "文件", url: row.annexFile }];
	fileList1.value = [{ name: "文件", url: row.overdueIssueFile }];
	childrenVisible.value = true;
};
onMounted(() => {
	getDataList();
});
</script>
<style scoped lang="scss">
.table-box {
	height: 100%;
	position: relative;
	.search-select {
		box-shadow: none;
		:deep() {
			.el-card {
				border-radius: 8px;
				width: 100%;
			}
		}
		.topCard {
			display: flex;
			align-items: center;
			:deep(.el-card__body) {
				display: flex;
				align-items: center;
			}
		}
	}
	.statistics-table {
		height: calc(100% - 100px);
		box-shadow: none;
		margin-top: 20px;
		padding-bottom: 20px;
		border-radius: 8px;
		padding: 20px;
		display: flex;
		flex-direction: column;
		position: relative;
		background-color: #fff;
	}
	.imgDialog {
		.uploadBtn {
			color: #30ac7c;
			font-size: 14px;
			border: 1px solid #30ac7c;
			background: #eaf6f1;
		}
	}
}
:deep(.el-input-number) {
	width: 100%;
	.el-input-number__increase {
		background-color: #09405f;
		color: #3f6ab0;
		font-size: 16px;
		border: 0 !important;
		border-bottom: 1px solid #087ba4 !important;
		border-left: 1px solid #087ba4 !important;
	}
	.el-input-number__decrease {
		background-color: #09405f;
		color: #3f6ab0;
		font-size: 16px;
		border: 0 !important;
		border-top: 1px solid #087ba4 !important;
		border-left: 1px solid #087ba4 !important;
	}
	.el-icon {
		font-size: 20px;
	}
}
:deep() {
	.el-input__inner,
	.el-textarea__inner,
	.el-range-input {
		font-size: 16px;
	}
	.el-table__expand-icon > .el-icon {
		font-size: 14px;
	}
}
</style>
