<template>
	<div class="overview">
		<el-dialog :show-close="false" v-model="visible1" :style="dialogStyle" width="1305" @close="closeMain">
			<template #title>
				<div class="title-detail">
					<span>{{ title }}</span>
					<el-icon>
						<close @click="closeMain" />
					</el-icon>
				</div>
			</template>
			<div class="search-select">
				<span style="margin: 0 10px 2px 0px">验收阶段</span>
				<el-input style="width: 200px" v-model="allForm.stage" clearable placeholder="请输入" />
				<span style="margin: 0 10px 2px 10px">类型</span>
				<el-select style="width: 200px" v-model="allForm.type" clearable placeholder="请选择">
					<el-option v-for="item in typeList" :key="item.dictLabel" :label="item.dictValue" :value="item.dictLabel" />
				</el-select>
				<span style="margin: 0 10px 2px 20px">备注</span>
				<el-input style="width: 200px" v-model="allForm.remark" clearable placeholder="请输入" />
			</div>
			<!-- 验收内容 -->
			<div class="detail-table">
				<div class="content-title">验收内容</div>
				<div class="content-button">
					<el-button class="addButtonStyle" v-if="title != '详情'" @click="addPlan">新增</el-button>
					<span v-if="title == '详情'">{{
						allForm.state == 1
							? "审批中"
							: allForm.state == 2
							? "资料验收通过"
							: allForm.state == 3
							? "已驳回"
							: allForm.state == 4
							? "已验收通过"
							: ""
					}}</span>
				</div>
				<div class="table">
					<el-table
						:data="recordData"
						class="el-table"
						max-height="300"
						:row-style="{ height: '40px' }"
						:header-cell-style="{ backgroundColor: '#F5F7FA', textAlign: 'center', height: '40px' }"
						:cell-style="{ textAlign: 'center', height: '40px' }"
					>
						<el-table-column type="index" label="序号" width="100" />
						<el-table-column prop="singleId" label="单体工程" width="200">
							<template #default="{ row }">
								<el-select v-if="row.isEdit" style="width: 100%" v-model="row.singleId" clearable placeholder="请选择">
									<el-option v-for="item in singleEngineerList" :key="item.singleId" :label="item.name" :value="item.singleId" />
								</el-select>
								<span v-else>{{ singleEngText(row.singleId) }}</span>
							</template>
						</el-table-column>
						<el-table-column prop="planCheckDate" label="计划验收时间" width="200">
							<template #default="{ row }">
								<el-date-picker
									v-if="row.isEdit"
									v-model="row.planCheckDate"
									style="width: 100%"
									format="YYYY-MM-DD"
									value-format="YYYY-MM-DD"
									type="date"
									placeholder="请选择"
								/>
								<span v-else>{{ row.planCheckDate }}</span>
							</template>
						</el-table-column>
						<el-table-column prop="startFlag" label="起始标识" width="200">
							<template #default="{ row }">
								<el-input v-model="row.startFlag" v-if="row.isEdit" />
								<span v-else>{{ row.startFlag }}</span>
							</template>
						</el-table-column>
						<el-table-column prop="endFlag" label="截止标识" width="200">
							<template #default="{ row }">
								<el-input v-model="row.endFlag" v-if="row.isEdit" />
								<span v-else>{{ row.endFlag }}</span>
							</template>
						</el-table-column>
						<el-table-column prop="headPerson" label="验收负责人" width="200">
							<template #default="{ row }">
								<el-input v-model="row.headPerson" v-if="row.isEdit" />
								<span v-else>{{ row.headPerson }}</span>
							</template>
						</el-table-column>
						<el-table-column prop="headPersonPhone" label="负责人电话" width="200">
							<template #default="{ row, $index }">
								<el-input v-model="row.headPersonPhone" v-if="row.isEdit" @blur="e => validatorPhone(e, $index)" />
								<span v-else>{{ row.headPersonPhone }}</span>
							</template>
						</el-table-column>
						<!-- <el-table-column prop="type8" label="状态" width="150">
							<template #default="{ row }">
								<el-input v-model="row.type1" v-if="!row.id" />
								<span v-else>{{ row.type1 }}</span>
							</template>
						</el-table-column> -->
						<el-table-column prop="remark" label="备注" width="200">
							<template #default="{ row }">
								<el-input v-model="row.remark" v-if="row.isEdit" />
								<span v-else>{{ row.remark }}</span>
							</template>
						</el-table-column>
						<el-table-column align="center" width="180" label="操作" v-if="title != '详情'">
							<template #default="scope">
								<el-button type="primary" v-if="scope.row.isEdit" link @click="scope.row.isEdit = false">
									<img src="@/assets/images/tableIcon/save.png" alt="" class="configureIcon" />
									<span>保存</span>
								</el-button>
								<el-button type="primary" v-if="!scope.row.isEdit" link @click="scope.row.isEdit = true">
									<img src="@/assets/images/tableIcon/updateIcon.png" alt="" class="configureIcon" />
									<span>编辑</span>
								</el-button>
								<el-button type="danger" v-if="!scope.row.isEdit" link :icon="Delete" @click="handleDeleteItem(scope.$index)"
									>删除</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>
				</div>
				<!-- <div class="operation-btn" v-if="basicData?.state != 4">
					<el-button type="info" style="margin-right: 98px">驳回,请尽快整改</el-button>
					<el-button type="primary">整改完成,全部合格</el-button>
					<el-button type="primary" @click="allSubmit">全部整改完成,提交审核</el-button>
				</div> -->
			</div>
			<!-- 资料附件 -->
			<div class="detail-table">
				<div class="content-title">资料附件</div>
				<div class="table">
					<el-table
						:data="documentData"
						border
						max-height="300"
						class="el-table"
						:row-style="{ height: '40px', textAlign: 'center' }"
						:header-cell-style="{ height: '40px', backgroundColor: '#e1eeff', textAlign: 'center' }"
						:cell-style="{ height: '40px', textAlign: 'center' }"
					>
						<el-table-column type="index" label="序号" width="200" />
						<el-table-column prop="annexName" label="附件名称">
							<template #default="{ row, $index }">
								<span v-if="title == '详情'">{{ row.annexName }}</span>
								<el-input v-else class="test" v-model="row.annexName" />
							</template>
						</el-table-column>
						<el-table-column prop="fileList" label="操作">
							<template #default="{ row, $index }">
								<!-- <el-button v-if="title == '详情'" type="primary" @click="onDownLoad(row)" link>下载附件</el-button> -->
								<el-button type="primary" @click="onUpload(row)" link>上传附件</el-button>
							</template>
						</el-table-column>
						<el-table-column fixed="right" v-if="title != '详情'">
							<template #header>
								<el-button type="primary" round @click="addEngineeringSingle"> 添加 </el-button>
							</template>

							<template #default="{ row, $index }">
								<el-button type="danger" link @click="removeEngineeringSingle($index)">删除</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>
				</div>
				<!-- <div class="operation-btn" v-if="basicData?.state != 4">
					<el-button type="info" style="margin-right: 98px">驳回,请尽快整改</el-button>
					<el-button type="primary">整改完成,全部合格</el-button>
					<el-button type="primary" @click="allSubmit">全部整改完成,提交审核</el-button>
				</div> -->
			</div>
			<!-- 驳回原因 -->
			<div class="back-reason" v-if="allForm.state == 3">
				<div class="content-title">驳回原因</div>
				<div class="form-content">
					<el-input disabled v-model="allForm.rejectReason" :rows="4" type="textarea" placeholder="请输入" />
				</div>
			</div>
			<!-- 现场检查 -->
			<div class="detail-table" v-if="allForm.state == 2 || allForm.state == 4">
				<div class="content-title">现场检查</div>
				<div class="table">
					<el-table
						:data="checkData"
						class="el-table"
						max-height="300"
						:row-style="{ height: '40px' }"
						:header-cell-style="{ backgroundColor: '#F5F7FA', textAlign: 'center', height: '40px' }"
						:cell-style="{ textAlign: 'center', height: '40px' }"
					>
						<el-table-column type="index" label="序号" width="100" />
						<el-table-column prop="inspectUserName" label="监督员" width="150" />
						<el-table-column prop="createTime" label="检查时间" width="180" />
						<el-table-column prop="buildEnt" label="建设单位" width="150" />
						<el-table-column prop="supervisorEnt" label="监理单位" width="150" />
						<el-table-column prop="opEnt" label="施工单位" width="150" />
						<el-table-column prop="surveyEnt" label="勘察单位" width="150" />
						<el-table-column prop="designEnt" label="设计单位" width="150" />
						<el-table-column prop="state" label="状态" width="150">
							<template #default="{ row }">
								<span>{{
									row.state == 0
										? "待执法"
										: row.state == 1
										? "执法中"
										: row.state == 2
										? "待整改"
										: row.state == 3
										? "待审核"
										: row.state == 4
										? "已闭合"
										: row.state == 5
										? "已驳回"
										: ""
								}}</span>
							</template>
						</el-table-column>
						<el-table-column align="center" width="100" label="操作">
							<template #default="{ row }">
								<el-button type="primary" link @click="handleLookItem(row)">
									<img src="@/assets/images/tableIcon/look.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>
				</div>
			</div>
			<template #footer>
				<div>
					<el-button type="primary" @click="visible1 = false" v-if="title == '详情'">关闭</el-button>
					<el-button type="primary" @click="confirm()" v-if="title != '详情'">提交申请</el-button>
				</div>
			</template>
		</el-dialog>
		<!-- 附件上传 -->
		<FilesUploadPlus v-model="showFilesUpload" @update:files="handlechange" :files="current.files" :reset="true" />
		<!-- 现场检查详情 -->
		<transformInfo v-model:detailsDialog="detailsDialog" :relativeId="checkRowId" @confirm="confirmReform"></transformInfo>
	</div>
</template>

<script lang="ts" setup>
import { onMounted, ref, watch, reactive } from "vue";
import { ElMessage } from "element-plus";
import { submitAll, acceptanceApplyAdd, acceptanceApplyDetails } from "@/api/modules/project";
import { Delete } from "@element-plus/icons-vue";
import { jxj_User } from "@/api/types";
import { useHandleData } from "@/hooks/useHandleData";
import { GlobalStore } from "@/stores";
import { getDicList } from "@/api/modules/jxjview";
import { singleEngineer } from "@/api/modules/common";
import FilesUploadPlus from "@/components/FilesUploadPlus/FilesUpload.vue";
import transformInfo from "./transformInfo.vue";
const current = ref({
	files: []
});
const showFilesUpload = ref(false);
const singleEngineerList = ref([]);
const typeList = ref([]);
const detailsDialog = ref(false);
const checkData = ref([]);
const checkRowId = ref("");
const globalStore = GlobalStore();
const headers = ref({ Authorization: "Bearer " + globalStore.token });
const documentData = ref<any>([]);
const baseUrl = import.meta.env.VITE_API_URL;
const props = defineProps({
	dialogVisible: Boolean,
	relativeId: String,
	title: String
});
const emits = defineEmits(["update:dialogVisible", "confirm"]);
const visible1 = ref(false);
const transformDialog = ref(false); // 整改记录对话框
const recordData = ref<any>([]); // 整改记录表格数据
const recordRowData = ref(); // 整改记录表格行数据
const basicData = ref(); // 基础信息
const dialogStyle = ref({
	"min-width": "824px"
});
const allForm = ref({
	stage: "",
	type: null,
	remark: "",
	rejectReason: "",
	state: null
});
const handleLookItem = row => {
	console.log(row);
	checkRowId.value = row.id;
	detailsDialog.value = true;
};
const validatorPhone = (e: any, index: any) => {
	// 校验手机号码
	let pattern = /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/;
	let dataValue = recordData.value[index].headPersonPhone;
	if (!pattern.test(dataValue)) {
		ElMessage.error("请输入正确的手机号码");
		recordData.value[index].headPersonPhone = "";
	}
};
// 下载附件按钮
const onDownLoad = (row: any) => {
	console.log(row);
	// if (row.url) {
	// 	window.open(baseUrl + "/xmgl/file/preview?fileUrl=" + row.url);
	// } else {
	// 	ElMessage.error("暂无可下载文件");
	// }
};
// 上传附件按钮
const onUpload = async row => {
	showFilesUpload.value = true;
	if (row.fileList.length > 0) {
		current.value.files = row.fileList;
	} else {
		current.value = row;
	}
};
const handlechange = e => {
	console.log(e);
	current.value.files = e.map(item => {
		item.label = current.value.dictLabel;
		return item;
	});
	console.log(current.value);
};
// 单体工程名称转换
const singleEngText = (id: any) => {
	let findItem: any = singleEngineerList.value.find(item => item.singleId == id);
	return findItem?.name;
};
// 整改完成，全部已提交审核
const confirmReform = () => {
	getInfo();
};
const confirm = async () => {
	console.log(allForm.value);
	console.log(recordData.value);
	console.log(documentData.value);
	let requestData = {
		...allForm.value,
		detailList: recordData.value,
		annexList: documentData.value,
		engineeringSn: globalStore.engineeringSn
	};
	requestData.detailList.map(item => {
		delete item.id;
	});
	requestData.annexList.map(item => {
		if (item.files && item.files.length > 0) {
			item.files.map(item2 => {
				item.fileList.push({
					createTime: item2.response.createTime,
					extendName: item2.response.ext,
					fileId: item2.response.id,
					fileName: item2.response.filename,
					fileSize: item2.response.size,
					fileUrl: item2.response.url,
					contentType: item2.response.contentType
				});
			});
		} else if (item.fileList && item.fileList.length > 0) {
			item.fileList.map(item2 => {
				delete item2.fileId;
			});
		}
		delete item.id;
	});
	delete requestData.state;
	const res = await acceptanceApplyAdd(requestData);
	if (res.message) {
		ElMessage.success("操作成功");
	} else {
		ElMessage({
			showClose: true,
			message: "操作失败",
			type: "error"
		});
	}
	visible1.value = false;
};
const getSingleEngineerData = async () => {
	const res = await singleEngineer({ engineeringSn: globalStore.engineeringSn });
	singleEngineerList.value = res.result;
	console.log(res);
};
const getDicMainList = async () => {
	// 获取学历字典
	const { result } = await getDicList({ dictType: "check_accept_type" });
	typeList.value.length = 0;
	typeList.value.push(...result);
};
// 导入文件
const uploadFileSuccess = (response: any) => {
	console.log(response);
};
const removeEngineeringSingle = (index: any) => {
	documentData.value.splice(index, 1);
};
const addEngineeringSingle = () => {
	documentData.value.push({
		annexName: "",
		fileList: []
	});
};
// 删除用户信息
const handleDeleteItem = async (index: any) => {
	// await useHandleData(deleteBigItem, { id: params.id }, `删除【${params.name}】`);
	recordData.value.splice(index, 1);
};
const addPlan = () => {
	recordData.value.push({
		singleId: "",
		singleProject: "",
		planCheckDate: "",
		startFlag: "",
		endFlag: "",
		headPerson: "",
		headPersonPhone: "",
		remark: "",
		isEdit: true
	});
};
// 修改数据按钮
const handleEditItem = async (row: any) => {
	console.log(row);
};
// 全部整改完成，提交
const allSubmit = async () => {
	const res = await submitAll({ id: basicData.value.id });
	closeMain();
	ElMessage.success("提交成功");
};
// 关闭两个对话框
const closeMain = () => {
	visible1.value = false;
	transformDialog.value = false;
	dialogStyle.value = {
		"min-width": "824px",
		transform: "translateX(0px)"
	};
};
// 相关信息接口调用
const getInfo = async () => {
	const res = await acceptanceApplyDetails({ id: props.relativeId });
	console.log(res);
	if (res && res.result) {
		for (let i in allForm.value) {
			allForm.value[i] = res.result[i];
		}
		recordData.value = res.result.detailList;
		documentData.value = res.result.annexList;
		checkData.value = res.result.acceptInspectRecordList;
	}
};
const timelineList = ref([{ name: 1 }]);
const auditVisible = ref(false);
// 监听父组件的visible，用来简介控制el-dialog的弹框开关，一般是用于开
watch(
	() => props.dialogVisible,
	(n, o) => {
		visible1.value = n;
		if (n) {
			if (props.title == "新增") {
				allForm.value = {
					stage: "",
					type: null,
					remark: "",
					rejectReason: ""
				};
				recordData.value = [];
				documentData.value = [];
			} else if (props.title == "详情" || props.title == "重新发起") {
				getInfo();
			}
		} else {
			emits("confirm");
		}
	}
);
// 监听el-dialog显示状态，再通过@update:visible 通知父组件，一般是用于关
watch(visible1, (n, o) => {
	emits("update:dialogVisible", n);
});
onMounted(() => {
	getDicMainList();
	getSingleEngineerData();
});
</script>

<style lang="scss" scoped>
@mixin fullwidth {
	width: -webkit-fill-available;
	width: -moz-available;
	width: stretch;
}
@mixin flex {
	display: flex;
	align-items: center;
}
@mixin title {
	font-size: 14px;
	font-family: Source Han Sans CN-Regular, Source Han Sans CN;
	font-weight: 400;
	color: #333333;
	border-left: 2px solid #008bff;
	padding-left: 5px;
}
.overview {
	:deep() {
		.el-dialog__body {
			padding-top: 0;
			padding-bottom: 0;
		}
	}
	.title-detail {
		@include flex;
		border-left: 3px solid #0f81ff;
		> span {
			font-family: Source Han Sans CN-Regular, Source Han Sans CN;
			font-weight: 400;
			color: #333333;
			margin-left: 12px;
			margin-right: auto;
			font-size: 18px;
		}
		:deep(.el-icon) {
			cursor: pointer;
			color: #a8abb2;
		}
	}
	.search-select {
		@include flex;
		box-shadow: none;
	}
	.detail-table {
		// height: 391px;
		margin-top: 18px;
		.content-title {
			@include title;
		}
		.content-button {
			@include flex;
			justify-content: flex-end;
			> span {
				font-size: 14px;
				font-family: Source Han Sans CN-Regular, Source Han Sans CN;
				font-weight: 400;
				color: #008bff;
			}
		}
		.table {
			width: 100%;
			// height: 310px;
			margin-top: 20px;
			:deep(.el-table) {
				height: 100%;
			}
			.table-empty {
				display: flex;
				justify-content: center;
				align-items: center;
				height: 150px;
				flex: 1;
				flex-direction: column;
				color: #999;
			}
		}
		.operation-btn {
			display: flex;
			align-items: center;
			justify-content: center;
			margin-top: 20px;
		}
	}
	.back-reason {
		// height: 391px;
		margin-top: 18px;
		.content-title {
			@include title;
		}
		.form-content {
			margin-top: 20px;
		}
	}
}
</style>
