<template>
	<div class="table-box">
		<ProTable
			ref="proTable"
			title="监理月报"
			:columns="columns"
			:requestApi="getTableList"
			:dataCallback="dataCallback"
			:tool-button="false"
			:pagination="true"
			background
			:isShowSearch="false"
			:initParam="initParam"
			:onReset="true"
		>
			<template #formButton="scope">
				<el-button class="addButtonStyle" :disabled="!searchSn" @click="handleAddItem">新增</el-button>
			</template>
			<template #annexFile="{ row }">
				<span>{{ row.annexFile ? JSON.parse(row.annexFile).name : "" }}</span>
				<!-- <el-button type="primary" link>
					<span>{{ JSON.parse(row.annexFile).name }}</span>
				</el-button> -->
			</template>
			<template #operation="{ row }">
				<el-button type="primary" link @click="handleLookItem(row)">
					<img src="@/assets/images/tableIcon/look.png" alt="" class="configureIcon" />
					<span>查看</span>
				</el-button>
				<el-button type="primary" link @click="handleDownItem(row)" v-if="row.annexFile">
					<img src="@/assets/images/tableIcon/下载附件.png" alt="" class="configureIcon" />
					<span>下载附件</span>
				</el-button>
				<el-button type="primary" link @click="handleUploadItem(row)" v-else>
					<img src="@/assets/images/tableIcon/上传附件.png" alt="" class="configureIcon" />
					<span>上传附件</span>
				</el-button>
			</template>
		</ProTable>
		<el-dialog title="上传附件" show-close v-model="uploadDialog" style="width: 600px">
			<el-form ref="formRef" :model="formData" label-width="100px" :rules="rules" class="basic-form" size="default">
				<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"
						:limit="1"
						:on-success="uploadSuccess"
						style="width: 100%"
					>
						<el-button class="uploadBtn" type="primary">点击上传</el-button>
					</el-upload>
				</el-form-item>
				<footer class="footer flx-center">
					<el-button class="cancelButtonStyle" @click="uploadDialog = false">取消</el-button>
					<el-button type="primary" @click="submitForm(formRef, formData)">保存</el-button>
				</footer>
			</el-form>
		</el-dialog>
		<!-- 新增月报 -->
		<monthlyAdd
			v-model:addVisible="addVisible"
			:searchSn="searchSn"
			:activeValue="activeValue"
			:relativeId="searchId"
			@confirm="confirmAdd"
		></monthlyAdd>
		<!-- 月报详情 -->
		<monthlyDetails
			v-model:detailVisible="detailVisible"
			:searchSn="searchSn"
			:activeValue="activeValue"
			:relativeId="relativeId"
			:searchId="searchId"
		></monthlyDetails>
		<!-- 侧边栏选择 -->
		<engineeringEngDrawer v-model="engVisable" ref="engDrawer" :engList="engList">
			<template #default="{ data }">
				<span style="margin-left: 10px" @click="onUpdate(data)">{{ data.engineeringName }}</span>
			</template>
		</engineeringEngDrawer>
		<allEngineering @click="engVisable = true" />
	</div>
</template>

<script setup lang="tsx" name="ProjectSupervisionRecord">
import { ref, reactive, onMounted } from "vue";
import { ElMessage, UploadProps } from "element-plus";
import type { FormInstance } from "element-plus";
import { ColumnProps } from "@/components/ProTable/interface";
import ProTable from "@/components/ProTable/index.vue";
import { getRelevanceList } from "@/api/modules/common";
import engineeringEngDrawer from "@/components/engineeringEngDrawer/index.vue";
import allEngineering from "@/components/allEngineering/index.vue";
import { monthlyReportPage, updateMonthlyReport } from "@/api/modules/enterpriseApi";
import monthlyAdd from "./components/monthlyAdd.vue";
import monthlyDetails from "./components/monthlyDetails.vue";
import { GlobalStore } from "@/stores";
const relativeId = ref("");
const formRef = ref<FormInstance>();
const fileList = ref([]);
const rules = ref({
	annexFile: [
		{
			required: true,
			message: "请上传",
			trigger: "change"
		}
	]
});
const formData = ref({
	annexFile: ""
});
const uploadDialog = ref(false);
const baseUrl = import.meta.env.VITE_API_URL;
const store = GlobalStore();
const headers = ref({ Authorization: "Bearer " + store.token });
const detailVisible = ref(false);
const addVisible = ref(false);
const activeValue = ref("eng");
const engList = ref([]);
const engVisable = ref(false);
const searchSn = ref("");
const searchId = ref("");
// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({
	engineeringSn: ""
});
// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref();

// 表格配置项
const columns: ColumnProps[] = [
	{ type: "index", label: "序号", width: 80 },
	{
		prop: "buildCompanyName",
		label: "建设单位"
	},
	{
		prop: "constructionCompanyName",
		label: "施工单位"
	},
	{
		prop: "designCompanyName",
		label: "监理单位"
	},
	{
		prop: "createByName",
		label: "填写人"
	},
	{
		prop: "annexFile",
		label: "附件"
	},
	{
		prop: "createTime",
		label: "创建时间",
		search: {
			el: "date-picker",
			props: {
				type: "daterange",
				format: "YYYY-MM-DD",
				valueFormat: "YYYY-MM-DD"
				// defaultTime: defaultTime2
			}
		}
	},
	{ prop: "operation", align: "left", label: "操作", fixed: "right", width: 260 }
];
const submitForm = async (formEl: FormInstance | undefined, form: any) => {
	// 标记表单校验
	if (!formEl) return;
	await formEl.validate(async (valid, fields) => {
		if (valid) {
			let requestData = {
				id: relativeId.value,
				annexFile: JSON.stringify(formData.value.annexFile)
			};
			const res = await updateMonthlyReport(requestData);
			if (res.success) {
				ElMessage.success("操作成功");
				uploadDialog.value = false;
				proTable.value.getTableList();
			}
		} else {
			console.log("error submit!", fields);
			ElMessage({
				showClose: true,
				message: "请完善表单信息！",
				type: "error"
			});
		}
	});
};
const onRemove: UploadProps["onRemove"] = (file, uploadFiles) => {
	formData.value.annexFile = "";
	fileList.value = reactive([]);
};
// 图片上传成功钩子
const uploadSuccess = (response: any, index: number) => {
	formData.value.annexFile = { name: response.result.originalFilename, url: response.result.url };
	fileList.value = [{ name: response.result.originalFilename, url: response.result.downloadPath }];
	formRef.value?.validateField("annexFile");
};
const confirmAdd = () => {
	proTable.value.getTableList();
};
// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 list && total && pageNum && pageSize 这些字段，那么你可以在这里进行处理成这些字段
// 或者直接去 hooks/useTable.ts 文件中把字段改为你后端对应的就行
const dataCallback = (data: any) => {
	// console.log(data);
	return {
		list: data.records,
		total: Number(data.total),
		pageNo: Number(data.current),
		pageSize: Number(data.size)
	};
};

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getUserList"
const getTableList = (params: any) => {
	let newParams = JSON.parse(JSON.stringify(params));
	if (newParams.createTime) {
		newParams.createTime_begin = newParams.createTime[0];
		newParams.createTime_end = newParams.createTime[1];
		delete newParams.createTime;
	}
	if (searchSn.value) {
		if (activeValue.value == "eng") {
			newParams.engineeringSn = searchSn.value;
		} else if (activeValue.value == "project") {
			newParams.projectSn = searchSn.value;
		}
	} else {
		return { result: { current: "1", pages: "1", records: [], size: "10", total: "0" } };
	}
	return monthlyReportPage(newParams);
};
// 新增
const handleAddItem = () => {
	addVisible.value = true;
};
// 下载附件
const handleDownItem = (row: any) => {
	if (row.annexFile) {
		window.open(baseUrl + "/xmgl/file/preview?fileUrl=" + JSON.parse(row.annexFile).url);
	} else {
		ElMessage.error("暂无可下载文件");
	}
};
// 上传附件
const handleUploadItem = (row: any) => {
	formData.value.annexFile = "";
	fileList.value = [];
	relativeId.value = row.id;
	uploadDialog.value = true;
	setTimeout(function () {
		formRef.value?.clearValidate();
	}, 200);
};
// 查看
const handleLookItem = (row: any) => {
	relativeId.value = row.id;
	detailVisible.value = true;
};
const getengineering = async () => {
	// let newParams = JSON.parse(JSON.stringify(params));
	const res = await getRelevanceList();
	engList.value = res.result;
	if (res.result && res.result.length > 0) {
		searchSn.value = res.result[0].engineeringSn;
		searchId.value = res.result[0].id;
	}
	proTable.value.getTableList();
	console.log(res);
};
// 点击抽屉的工程名称更新页面
const onUpdate = async row => {
	if (activeValue.value == "eng") {
		searchSn.value = row.engineeringSn;
		searchId.value = row.id;
	} else if (activeValue.value == "project") {
		searchSn.value = row.projectSn;
		searchId.value = row.id;
	}
	proTable.value.getTableList();
	ElMessage.success("页面已更新");
};
onMounted(() => {
	getengineering();
});
</script>
<style scoped lang="scss">
@import "./index.scss";
</style>
