<template>
	<div class="overview">
		<el-form ref="ruleFormRef" :model="form" label-width="160px" :rules="rules" class="form" size="default">
			<!-- <el-form ref="ruleFormRef" :model="form" label-width="150px" class="form" size="default"> -->
			<!-- <el-form-item label="项目名称:" prop="projectName">
				<el-input placeholder="请输入" v-model="form.projectName" disabled />
			</el-form-item> -->
			<div class="row">
				<el-form-item label="概算编制单位:" prop="fiveUnit">
					<el-input placeholder="请输入" v-model="form.fiveUnit" />
				</el-form-item>
				<el-form-item label="概算审核单位:" prop="fiveApprovalUnit">
					<el-input placeholder="请输入" v-model="form.fiveApprovalUnit" />
				</el-form-item>
			</div>
			<el-form-item label="初步设计及概算批复文件名称:" prop="fiveReplyFileName">
				<el-input placeholder="请输入" v-model="form.fiveReplyFileName" />
			</el-form-item>
			<div class="row">
				<el-form-item label="时间:" prop="fiveReplyTime">
					<el-date-picker
						ref="fiveReplyTimeRef"
						class="date"
						format="YYYY-MM-DD"
						value-format="YYYY-MM-DD"
						v-model="form.fiveReplyTime"
						type="date"
						placeholder="选择日期"
					/>
					<div class="calendar" @click="fiveReplyTimeRef?.focus()">
						<el-icon class="icon"><Calendar /></el-icon>
					</div>
				</el-form-item>
				<el-form-item label="文号:" prop="fiveReplyNum">
					<el-input placeholder="请输入" v-model="form.fiveReplyNum" />
				</el-form-item>
			</div>
			<div class="row">
				<el-form-item label="批复单位:" prop="fiveReplyUnit">
					<el-input placeholder="请输入" v-model="form.fiveReplyUnit" />
				</el-form-item>
			</div>
			<div class="row">
				<el-form-item label="开始时间:" prop="fiveStartTime">
					<el-date-picker
						ref="fiveStartTimeRef"
						class="date"
						format="YYYY-MM-DD"
						value-format="YYYY-MM-DD"
						v-model="form.fiveStartTime"
						type="date"
						placeholder="选择日期"
					/>
					<div class="calendar" @click="fiveStartTimeRef?.focus()">
						<el-icon class="icon"><Calendar /></el-icon>
					</div>
				</el-form-item>
				<el-form-item label="结束时间:" prop="fiveEndTime">
					<el-date-picker
						ref="fiveEndTimeRef"
						class="date"
						format="YYYY-MM-DD"
						value-format="YYYY-MM-DD"
						v-model="form.fiveEndTime"
						type="date"
						placeholder="选择日期"
					/>
					<div class="calendar" @click="fiveEndTimeRef?.focus()">
						<el-icon class="icon"><Calendar /></el-icon>
					</div>
				</el-form-item>
			</div>
			<div class="row">
				<el-form-item label="项目状态:" prop="fiveState">
					<el-select class="select" placeholder="请选择" v-model="form.fiveState">
						<el-option v-for="item in engineeringState" :key="item.value" :label="item.name" :value="item.value" />
					</el-select>
				</el-form-item>
				<el-form-item label="填报人:" prop="fiveReportedBy">
					<el-select class="select" placeholder="请选择" v-model="form.fiveReportedBy">
						<el-option v-for="item in reportPerson" :key="item.value" :label="item.name" :value="item.value" />
					</el-select>
				</el-form-item>
			</div>
		</el-form>

		<div class="table">
			<h4>附件</h4>
			<el-table
				:data="form.engineeringSingles"
				border
				class="el-table"
				:header-cell-style="{ textAlign: 'center' }"
				:cell-style="{ textAlign: 'center' }"
			>
				<el-table-column type="index" label="序号" width="200" />
				<el-table-column prop="dictValue" label="附件名称" />
				<el-table-column label="操作" width="200">
					<template #default="{ row }">
						<el-button type="primary" link size="small" @click="addAnnexFile(row)">添加</el-button>
					</template>
				</el-table-column>
			</el-table>

			<FileUpload v-model="showFilesUpload" @update:files="handlechange" :files="current.files" :reset="true" />
		</div>
		<footer class="footer">
			<el-button type="primary" @click="prev">上一步</el-button>
			<el-button type="primary" @click="next(ruleFormRef)">下一步</el-button>
		</footer>
		<AMap v-model="isOpen" @get-address="getAddress" />
	</div>
</template>

<script lang="ts" setup>
import { ref, onMounted, onUnmounted, onActivated, onDeactivated } from "vue";
import { form, reset, rules } from "./overview5";
import { getDicList } from "@/api/modules/jxjview";
import { getEngineeringName } from "@/api/modules/project";
import { ElDatePicker } from "element-plus";
import type { ReqQueryDictData, EngineeringSingle } from "@/api/types";
import { ElMessage, FormInstance, ElForm } from "element-plus";
import type { OverviewForm } from "./overview5";
import AreaSelected from "@/components/ChinaAreaData/index.vue";
import AMap from "@/components/AMap/AMap.vue";
import { GlobalStore } from "@/stores";
import type { Options } from "@/views/goverment/approve/company/components/unit-table.vue";
import type { UploadFile } from "@/components/FilesUpload/FilesUpload.vue";
import FileUpload from "@/components/FilesUpload/FilesUpload.vue";
import type { AnnexFile } from "@/api/types";
type AnnexFilesOptions = Options & {
	files: UploadFile[];
};
const ruleFormRef = ref<FormInstance>();

const showFilesUpload = ref(false);

const current = ref<AnnexFilesOptions>({} as AnnexFilesOptions);

const dictLabel = ref<undefined | number>(undefined);
const store = GlobalStore();
const isOpen = ref(false);
const emit = defineEmits<{
	(e: "next", data: OverviewForm): void;
	(e: "prev", data: void): void;
}>();

type DictDataList = Array<ReqQueryDictData>;
type ElDatePickerType = typeof ElDatePicker;

const fiveReplyTimeRef = ref<ElDatePickerType>(),
	fiveStartTimeRef = ref<ElDatePickerType>(),
	fiveEndTimeRef = ref<ElDatePickerType>();

const reportPerson = ref<any>([
	{
		name: "曹晓童",
		value: "曹晓童"
	},
	{
		name: "黄浩正",
		value: "黄浩正"
	},
	{
		name: "黄培峰",
		value: "黄培峰"
	},
	{
		name: "李燕",
		value: "李燕"
	},
	{
		name: "周韵",
		value: "周韵"
	},
	{
		name: "牟红洁",
		value: "牟红洁"
	},
	{
		name: "杨润韬",
		value: "杨润韬"
	}
]);
const engineeringState = ref<any>([
	{
		name: "未开始",
		value: "未开始"
	},
	{
		name: "进行中",
		value: "进行中"
	},
	{
		name: "已完结",
		value: "已完结"
	}
]);
const addAnnexFile = (row: AnnexFilesOptions) => {
	// console.log(row);

	showFilesUpload.value = true;
	current.value = row;
	dictLabel.value = row.dictLabel;
};
const handlechange = e => {
	current.value.files = e.map(item => {
		item.label = current.value.dictLabel;
		return item;
	});
};
const handleGetAdress = (data: any) => {
	// form.value.address = data;
	form.value.province = data.name[0];
	form.value.city = data.name[1];
	form.value.district = data.name[2];
};

const openMap = () => {
	isOpen.value = true;
};

const getAddress = (e: any) => {
	isOpen.value = false;
	form.value.position = "经度：" + e.lng + " 纬度：" + e.lat;
	form.value.latitude = e.lat;
	form.value.longitude = e.lng;
	ElMessage.success("已获取地址");
};

const next = async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	await formEl.validate(async (valid, fields) => {
		if (valid) {
			const fileList: AnnexFile[] = [];
			form.value.engineeringSingles.forEach((item: any) => {
				if (item.files && item.files.length > 0) {
					const files = item.files;
					files.forEach((file: any) => {
						const curr: any = {};

						curr.createTime = file.response?.createTime;
						curr.extendName = file.response?.ext;

						// TODO: 上传文件后, 后端返回两个 name 字段, 一个后端存储的 filename, 一个文件本身的 originalFilename
						curr.fileName = file.response?.originalFilename;
						// curr.fileName = file.response?.filename;

						// curr.fileId = file.response && +file.response.id;
						curr.fileSize = `${file.response?.size || ""}`;
						curr.fileUrl = file.response?.url;

						curr.label = item.dictValue;
						curr.fileType = 15;

						fileList.push(curr);
					});
					item.files = fileList;
				}
			});
			emit("next", form.value);
		} else {
			console.log("error submit!", fields);
			ElMessage({
				showClose: true,
				message: "请完善表单信息！",
				type: "error"
			});
		}
	});
};
const prev = async () => {
	emit("prev");
};
onMounted(async () => {
	ruleFormRef.value?.clearValidate();
	if (store.Message) {
		for (let i in form.value) {
			if (i != "engineeringSingles") {
				form.value[i] = store.Message[i];
			}
		}
		if (store.Message.annexFiles.length) {
			form.value.engineeringSingles.forEach((item: any) => {
				const currFiles = store.Message.annexFiles.filter((j: any) => {
					// console.log("file", j);
					// console.log("dict", item);
					return j.label == item.dictValue;
				});
				const files: any = [];

				currFiles.forEach((curr: any) => {
					files.push({
						id: curr.fileId,
						name: curr.fileName,
						size: +curr.fileSize,
						type: "image/png",
						response: { ...curr, contentType: "image/png" }
					});
				});

				item.files = files;
			});
		}
	}
	// if (store.Message) {
	// 	form.value = store.Message;
	// 	addressList.value = store.Message;
	// } else {
	// 	form.value = {};
	// 	addressList.value = {
	// 		province: "",
	// 		city: "",
	// 		area: "",
	// 		district: ""
	// 	};
	// }
});
onUnmounted(() => {
	ruleFormRef.value?.clearValidate();
	reset();
});
</script>

<style lang="scss" scoped>
@import "./overview5.scss";
.test :deep(.el-input__inner) {
	text-align: center;
}
:deep(.el-table__empty-text) {
	min-height: 200px;
	display: flex;
	justify-content: center;
	align-items: center;
}
</style>
