<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" @click="handleAddItem">新增</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="handleEditItem(row)">
					<img src="@/assets/images/tableIcon/updateIcon.png" alt="" class="configureIcon" />
					<span>编辑</span>
				</el-button>
				<el-button type="danger" link :icon="Delete" @click="handleDeleteItem(row)">删除</el-button>
			</template>
			<template #state="{ row }">
				<span :class="row.state === 1 ? '' : 'redText'">{{ row.state == 1 ? "启用" : "禁用" }}</span>
			</template>
		</ProTable>
		<el-dialog :title="title" show-close v-model="newUnitDialog" style="min-width: 1200px">
			<el-form ref="formRef" :model="formData" label-width="180px" :rules="rules" class="basic-form" size="default">
				<!-- <el-form ref="formDataRef" :model="formData" label-width="150px" class="basic-form"> -->
				<el-row :gutter="120">
					<el-col :span="12">
						<el-form-item label="设备名称:" prop="devName">
							<el-input v-model="formData.devName" placeholder="请输入" :disabled="title == '查看设备'" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="设备编号:" prop="devNumber">
							<el-input v-model="formData.devNumber" placeholder="请输入" :disabled="title == '查看设备'" />
						</el-form-item>
					</el-col>
				</el-row>
				<el-row :gutter="120">
					<el-col :span="12">
						<el-form-item label="升降机类型:" prop="elevatorType">
							<el-select v-model="formData.elevatorType" :disabled="title == '查看设备'" placeholder="请选择" style="width: 100%">
								<el-option v-for="item in typeList" :key="item.value" :label="item.label" :value="item.value"> </el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="安装日期:" prop="installTime">
							<el-date-picker
								:disabled="title == '查看设备'"
								style="width: 100%"
								v-model="formData.installTime"
								format="YYYY-MM-DD"
								value-format="YYYY-MM-DD"
								type="date"
								placeholder="请选择"
							/>
						</el-form-item>
					</el-col>
				</el-row>

				<el-row :gutter="120">
					<el-col :span="12">
						<el-form-item label="安装图片:" prop="installImage">
							<div class="face-img">
								<el-upload
									class="face-uploader"
									:action="`${baseUrl}` + '/xmgl/file/upload'"
									:show-file-list="false"
									:on-success="(response: any, uploadFile: any) => handleAvatarSuccess(response, uploadFile)"
									accept="image/jpg, image/jpeg, image/png"
								>
									<img v-if="formData.installImage" :src="formData.installImage" class="face-avatar" />
									<el-icon v-else><plus /></el-icon>
								</el-upload>
							</div>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="登记证书照片:" prop="registrationCertificate">
							<div class="face-img">
								<el-upload
									class="face-uploader"
									:action="`${baseUrl}` + '/xmgl/file/upload'"
									:show-file-list="false"
									:on-success="(response: any, uploadFile: any) => handleRegistSuccess(response, uploadFile)"
									accept="image/jpg, image/jpeg, image/png"
								>
									<img v-if="formData.registrationCertificate" :src="formData.registrationCertificate" class="face-avatar" />
									<el-icon v-else><plus /></el-icon>
								</el-upload>
							</div>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row :gutter="120">
					<el-col :span="12">
						<el-form-item label="设备型号:" prop="model">
							<el-input v-model="formData.model" placeholder="请输入" :disabled="title == '查看设备'" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="齿轮模数:" prop="gearModule">
							<el-input v-model="formData.gearModule" placeholder="请输入" :disabled="title == '查看设备'" />
						</el-form-item>
					</el-col>
				</el-row>
				<el-row :gutter="120">
					<el-col :span="12">
						<el-form-item label="最大高度:" prop="maxHeight">
							<el-input v-model="formData.maxHeight" placeholder="请输入" :disabled="title == '查看设备'" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="最大载重:" prop="maxLoad">
							<el-input v-model.number="formData.maxLoad" placeholder="请输入" :disabled="title == '查看设备'" />
						</el-form-item>
					</el-col>
				</el-row>
				<el-row :gutter="120">
					<el-col :span="12">
						<el-form-item label="额定人数:" prop="ratedPeopleNum">
							<el-input v-model.number="formData.ratedPeopleNum" placeholder="请输入" :disabled="title == '查看设备'" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="备案编号:" prop="filingNumber">
							<el-input v-model.number="formData.filingNumber" placeholder="请输入" :disabled="title == '查看设备'" />
						</el-form-item>
					</el-col>
				</el-row>
				<el-row :gutter="120">
					<el-col :span="12">
						<el-form-item label="升降机所在楼层总层数:" prop="totalFloor">
							<el-input v-model.number="formData.totalFloor" placeholder="请输入" :disabled="title == '查看设备'" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="使用登记办理编号:" prop="useRegistrationNumber">
							<el-input v-model.number="formData.useRegistrationNumber" placeholder="请输入" :disabled="title == '查看设备'" />
						</el-form-item>
					</el-col>
				</el-row>
				<el-row :gutter="120">
					<el-col :span="12">
						<el-form-item label="使用登记办理时间:" prop="useRegistrationTime">
							<el-date-picker
								:disabled="title == '查看设备'"
								style="width: 100%"
								v-model="formData.useRegistrationTime"
								format="YYYY-MM-DD"
								value-format="YYYY-MM-DD"
								type="date"
								placeholder="请选择日期"
							/>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="设备标识码:" prop="verifyCode">
							<el-input v-model="formData.verifyCode" placeholder="请输入" :disabled="title == '查看设备'" />
						</el-form-item>
					</el-col>
				</el-row>
				<footer class="footer flx-center" v-if="title != '查看设备'">
					<el-button class="cancelButtonStyle" @click="newUnitDialog = false">取消</el-button>
					<el-button type="primary" @click="submitForm(formData)">保存</el-button>
				</footer>
			</el-form>
		</el-dialog>
		<!-- 侧边栏选择 -->
		<engineeringEngDrawer v-model="engVisable" :active="activeValue" ref="engDrawer" :engList="engList" @select="tabsSelect">
			<template #default="{ data }">
				<span style="margin-left: 10px" @click="onUpdate(data)">{{
					activeValue == "eng" ? data.engineeringName : data.projectName
				}}</span>
			</template>
		</engineeringEngDrawer>
		<allEngineering @click="engVisable = true" />
	</div>
</template>

<script setup lang="tsx" name="ProjectSupervisionRecord">
import { ref, reactive, nextTick, onMounted } from "vue";
import { ElMessage, ElMessageBox, ElTree, FormInstance } from "element-plus";
import type { UploadProps } from "element-plus";
import { useRouter } from "vue-router";
import { ColumnProps } from "@/components/ProTable/interface";
import { useHandleData } from "@/hooks/useHandleData";
import ProTable from "@/components/ProTable/index.vue";
import { jxj_User } from "@/api/types";
import { getRelevanceList } from "@/api/modules/common";
import engineeringEngDrawer from "@/components/engineeringEngDrawer/index.vue";
import allEngineering from "@/components/allEngineering/index.vue";
import { lifterEquipAdd, lifterEquipEdit, lifterEquipDel, lifterEquipPage, getEngineeringName } from "@/api/modules/project";
import { GlobalStore } from "@/stores";
import { Delete } from "@element-plus/icons-vue";
const baseUrl = import.meta.env.VITE_API_URL;
// 升降机类型
const typeList = ref([
	{ label: "单笼", value: 0 },
	{ label: "多笼", value: 1 }
]);
const stateList = ref([
	{ label: "设备进场", value: 1 },
	{ label: "设备安装", value: 2 },
	{ label: "设备验收", value: 3 },
	{ label: "设备使用", value: 4 },
	{ label: "设备拆除", value: 5 },
	{ label: "设备退场", value: 6 }
]);
const activeValue = ref("eng");
const engList = ref([]);
const engVisable = ref(false);
const searchSn = ref("");
const changeType = ref(1);
const datas = reactive([]);
const formRef = ref<FormInstance>();
const router = useRouter();
const store = GlobalStore();
const drawerVisible = ref(false);
const title = ref("");
const newUnitDialog = ref(false);
// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({
	engineeringSn: ""
});
const formData = ref({
	id: "",
	devName: "",
	devNumber: "",
	elevatorType: "",
	installTime: "",
	installImage: "",
	registrationCertificate: "",
	model: "",
	gearModule: "",
	maxHeight: "",
	maxLoad: "",
	ratedPeopleNum: "",
	filingNumber: "",
	totalFloor: "",
	useRegistrationNumber: "",
	useRegistrationTime: "",
	verifyCode: ""
});

const emptyFormData = ref({
	id: "",
	devName: "",
	devNumber: "",
	elevatorType: "",
	installTime: "",
	installImage: "",
	registrationCertificate: "",
	model: "",
	gearModule: "",
	maxHeight: "",
	maxLoad: "",
	ratedPeopleNum: "",
	filingNumber: "",
	totalFloor: "",
	useRegistrationNumber: "",
	useRegistrationTime: "",
	verifyCode: ""
});
// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref();

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

// 表格配置项
const columns: ColumnProps[] = [
	{ type: "index", label: "序号", width: 80 },
	{
		prop: "devName",
		label: "设备名称",
		search: { el: "input" }
	},
	{
		prop: "devNumber",
		label: "设备编号"
	},
	{
		prop: "installTime",
		label: "安装时间",
		search: {
			el: "date-picker",
			props: {
				type: "daterange",
				format: "YYYY-MM-DD",
				valueFormat: "YYYY-MM-DD"
				// defaultTime: defaultTime2
			}
		}
	},
	// { prop: "blackBox", label: "黑匣子信息" },
	{ prop: "operation", label: "操作", fixed: "right", width: 260 }
];
const rules = ref({
	devName: [
		{
			required: true,
			message: "请输入",
			trigger: "blur"
		}
	],
	devNumber: [
		{
			required: true,
			message: "请输入",
			trigger: "blur"
		}
	],
	installTime: [
		{
			required: true,
			message: "请输入",
			trigger: "blur"
		}
	],
	model: [
		{
			required: true,
			message: "请输入",
			trigger: "blur"
		}
	],
	gearModule: [
		{
			required: true,
			message: "请输入",
			trigger: "blur"
		},
		{
			pattern: /^\d+(\.\d{0,2})?$/,
			message: "请输入整数或小数点后两位小数",
			trigger: "blur"
		}
	],
	installImage: [
		{
			required: true,
			message: "请上传",
			trigger: "change"
		}
	],
	elevatorType: [
		{
			required: true,
			message: "请选择",
			trigger: "change"
		}
	],
	registrationCertificate: [
		{
			required: true,
			message: "请上传",
			trigger: "change"
		}
	],
	maxHeight: [
		{
			required: true,
			message: "请输入",
			trigger: "blur"
		},
		{
			pattern: /^\d+(\.\d{0,2})?$/,
			message: "请输入整数或小数点后两位小数",
			trigger: "blur"
		}
	],
	maxLoad: [
		{
			required: true,
			message: "请输入",
			trigger: "blur"
		},
		{
			pattern: /^\d+(\.\d{0,2})?$/,
			message: "请输入整数或小数点后两位小数",
			trigger: "blur"
		}
	],
	ratedPeopleNum: [
		{
			required: true,
			message: "请输入",
			trigger: "blur"
		},
		{
			pattern: /^[+]{0,1}(\d+)$/,
			message: "请输入正整数",
			trigger: "blur"
		}
	],
	filingNumber: [
		{
			required: true,
			message: "请输入",
			trigger: "blur"
		}
	],
	totalFloor: [
		{
			required: true,
			message: "请输入",
			trigger: "blur"
		},
		{
			pattern: /^-?\d+$/,
			message: "请输入整数",
			trigger: "blur"
		}
	],
	useRegistrationTime: [
		{
			required: true,
			message: "请输入",
			trigger: "blur"
		}
	],
	verifyCode: [
		{
			required: true,
			message: "请输入",
			trigger: "blur"
		}
	],
	independentLiftingHeight: [
		{
			required: true,
			message: "请输入",
			trigger: "blur"
		},
		{
			pattern: /^\d+(\.\d{0,2})?$/,
			message: "请输入整数或小数点后两位小数",
			trigger: "blur"
		}
	],
	renovations: [
		{
			required: true,
			message: "请输入",
			trigger: "blur"
		},
		{
			pattern: /^[1-9]\d*$/,
			message: "请输入正整数",
			trigger: "blur"
		}
	],
	useRegistrationNumber: [
		{
			required: true,
			message: "请输入",
			trigger: "blur"
		}
	]
});

// 图片上传成功后的钩子
const handleAvatarSuccess: UploadProps["onSuccess"] = (response, uploadFile) => {
	// console.log(response.result.url);
	// console.log(response, uploadFile);
	formData.value.installImage = response.result.url;
	formRef.value?.validateField("image");
};

// 图片上传成功后的钩子
const handleRegistSuccess: UploadProps["onSuccess"] = (response, uploadFile) => {
	// console.log(response.result.url);
	// console.log(response, uploadFile);
	formData.value.registrationCertificate = response.result.url;
	formRef.value?.validateField("image");
};

// 删除设备
const handleDeleteItem = async (params: jxj_User.ResUserList) => {
	await useHandleData(lifterEquipDel, { id: params.id }, `删除【${params.devName}】`);
	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)
	};
};

const transfrom = (arr: Array<any>) => {
	const result: any[] | ConcatArray<{ authorityId: any; roleId: number | undefined; type: any }> = [];
	return arr
		.map(item => {
			if (arr.children && Array.isArray(arr.children)) {
				result.concat(transfrom(arr.children));
			}

			return {
				authorityId: item.name,
				roleId: getId.value,
				type: item.type
			};
		})
		.concat(result);
};

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getUserList"
const getTableList = (params: any) => {
	let newParams = JSON.parse(JSON.stringify(params));
	if (newParams.installTime) {
		newParams.installTime_begin = newParams.installTime[0];
		newParams.installTime_end = newParams.installTime[1];
		delete newParams.installTime;
	}
	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 lifterEquipPage(newParams);
};
// 新增
const handleAddItem = () => {
	formData.value = emptyFormData.value;
	formRef.value?.resetFields();
	title.value = "新增设备";
	newUnitDialog.value = true;
};
// 查看
const handleLookItem = (row: any) => {
	formRef.value?.resetFields();
	title.value = "查看设备";
	console.log(row);
	formData.value = reactive({ ...row });
	changeType.value = formData.value.businessLicenseLifespan ? 1 : 2;
	newUnitDialog.value = true;
};
// 编辑
const handleEditItem = (row: any) => {
	formRef.value?.clearValidate();
	title.value = "编辑设备";
	console.log(row);
	formData.value = reactive({ ...row });
	changeType.value = formData.value.businessLicenseLifespan ? 1 : 2;
	newUnitDialog.value = true;
};
// TODO: 提交表单操作
const submitForm = async (data: any) => {
	const formEl = formRef.value;
	if (!formEl) return;
	await formEl.validate((valid, fields) => {
		if (valid) {
			if (changeType.value == 2) {
				delete data.businessLicenseLifespan;
			}
			if (activeValue.value == "eng") {
				data.engineeringSn = searchSn.value;
			} else if (activeValue.value == "project") {
				data.projectSn = searchSn.value;
			}
			saveItem(data);
		} else {
			console.log("error submit!", fields);
		}
	});
};
const saveItem = async (form: any) => {
	if (form.id) {
		// console.log(form.dictCode);
		const res = await lifterEquipEdit(form);
		proTable.value.getTableList();
		ElMessage.success("编辑成功");
		newUnitDialog.value = false;
	} else {
		const res = await lifterEquipAdd(form);
		proTable.value.getTableList();
		ElMessage.success("新增成功");
		newUnitDialog.value = false;
	}
};

// 抽屉tab选择时
const tabsSelect = val => {
	activeValue.value = val;
	if (val == "eng") {
		getengineering();
	} else if (val == "project") {
		getProject();
	}
};
// 获取项目信息
const getProject = async () => {
	const res = await getEngineeringName();
	engList.value = [res.result];
	if (res.result) {
		searchSn.value = res.result.projectSn;
	}
	proTable.value.getTableList();
	console.log(res);
};
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;
	}
	proTable.value.getTableList();
	console.log(res);
};
// 点击抽屉的工程名称更新页面
const onUpdate = async row => {
	if (activeValue.value == "eng") {
		searchSn.value = row.engineeringSn;
	} else if (activeValue.value == "project") {
		searchSn.value = row.projectSn;
	}
	proTable.value.getTableList();
	ElMessage.success("页面已更新");
};
onMounted(() => {
	getengineering();
});
</script>
<style scoped lang="scss">
@import "./index.scss";
</style>
