<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> -->
			<el-form-item label="立项批复取得文件名称:" prop="twoFileName">
				<el-input placeholder="请输入" v-model="form.twoFileName" />
			</el-form-item>
			<div class="row">
				<el-form-item label="可研编制单位:" prop="twoUnit">
					<el-input placeholder="请输入" v-model="form.twoUnit" />
				</el-form-item>
				<el-form-item label="时间:" prop="twoTime">
					<el-date-picker
						ref="twoTimeRef"
						class="date"
						format="YYYY-MM-DD"
						value-format="YYYY-MM-DD"
						v-model="form.twoTime"
						type="date"
						placeholder="选择日期"
					/>
					<div class="calendar" @click="twoTimeRef?.focus()">
						<el-icon class="icon"><Calendar /></el-icon>
					</div>
				</el-form-item>
			</div>
			<div class="row">
				<el-form-item label="文号:" prop="twoDocumentNum">
					<el-input placeholder="请输入" v-model="form.twoDocumentNum" />
				</el-form-item>
				<el-form-item label="批复单位:" prop="twoApprovalUnit">
					<el-input placeholder="请输入" v-model="form.twoApprovalUnit" />
				</el-form-item>
			</div>
			<div class="row">
				<el-form-item label="项目编号:" prop="engineeringCode">
					<el-input placeholder="请输入" v-model="form.engineeringCode" />
				</el-form-item>
				<el-form-item label="项目总投资:" prop="engineeringCost">
					<el-input placeholder="请输入" v-model="form.engineeringCost" />
				</el-form-item>
			</div>
			<div class="row">
				<el-form-item label="建安费:" prop="twoInstallationFees">
					<el-input placeholder="请输入" v-model="form.twoInstallationFees" />
				</el-form-item>
				<el-form-item label="项目概况:" prop="twoEngineeringOverview">
					<el-input placeholder="请输入" v-model="form.twoEngineeringOverview" />
				</el-form-item>
			</div>
			<div class="row">
				<el-form-item label="开始时间:" prop="twoStartTime">
					<el-date-picker
						ref="twoStartTimeRef"
						class="date"
						format="YYYY-MM-DD"
						value-format="YYYY-MM-DD"
						v-model="form.twoStartTime"
						type="date"
						placeholder="选择日期"
					/>
					<div class="calendar" @click="twoStartTimeRef?.focus()">
						<el-icon class="icon"><Calendar /></el-icon>
					</div>
				</el-form-item>
				<el-form-item label="结束时间:" prop="twoEndTime">
					<el-date-picker
						ref="twoEndTimeRef"
						class="date"
						format="YYYY-MM-DD"
						value-format="YYYY-MM-DD"
						v-model="form.twoEndTime"
						type="date"
						placeholder="选择日期"
					/>
					<div class="calendar" @click="twoEndTimeRef?.focus()">
						<el-icon class="icon"><Calendar /></el-icon>
					</div>
				</el-form-item>
			</div>
			<div class="row">
				<el-form-item label="项目状态:" prop="twoState">
					<el-select class="select" placeholder="请选择" v-model="form.twoState">
						<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="twoReportedBy">
					<el-select class="select" placeholder="请选择" v-model="form.twoReportedBy">
						<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="next(ruleFormRef, true)">保存</el-button>
			<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 "./overview2";
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 "./overview2";
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, isTemporary: any): void;
	(e: "prev", data: void): void;
}>();

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

const twoTimeRef = ref<ElDatePickerType>(),
	twoStartTimeRef = ref<ElDatePickerType>(),
	twoEndTimeRef = 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, isTemporary?: any) => {
	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 = 12;

						fileList.push(curr);
					});
					item.files = fileList;
				}
			});
			emit("next", form.value, isTemporary);
		} 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 "./overview2.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>
