<template>
	<div class="table-box">
		<ProTable
			ref="proTable"
			title="用户列表"
			:columns="columns"
			:requestApi="getTableList"
			:dataCallback="dataCallback"
			:tool-button="false"
			:pagination="true"
			background
			:isShowSearch="false"
			:onReset="true"
		>
			<template #formButton="scope">
				<el-button class="addButtonStyle" @click="handleEditItem(1)">新增</el-button>
			</template>
			<template #operation="{ row }">
				<el-button type="primary" link @click="handleEditItem(2, 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 #examineState="{ row }">
				{{ row.examineState === 1 ? "待审核" : row.examineState === 2 ? "审核驳回" : "审核通过" }}
			</template>
			<template #state="{ row }">
				<span :class="row.state === 1 ? '' : 'redText'">{{ row.state == 1 ? "在线" : "离线" }}</span>
			</template>
		</ProTable>
		<DialogForm
			:title="title"
			:formConfig="formConfig"
			:formData="formData"
			v-model:visible="visible"
			append-to-body
			width="700px"
			@confirm="saveItem"
		>
			<template #mapIcon>
				<div class="diaMapIcon" @click="isOpen = true">
					<el-icon style="font-size: 19px"><Location /></el-icon>
				</div>
			</template>
		</DialogForm>
		<AMap v-model="isOpen" @get-address="getAddress" />
		<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="ts" name="enterpriseVideoManageMent">
import { ref, reactive, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { ColumnProps } from "@/components/ProTable/interface";
import { Delete } from "@element-plus/icons-vue";
import { jxj_User } from "@/api/types";
import { useHandleData } from "@/hooks/useHandleData";
import ProTable from "@/components/ProTable/index.vue";
import {
	getvideoManagementPage,
	addvideoManagementment,
	editvideoManagement,
	deletevideoManagement,
	getengineeringList,
	getEngineeringName
} from "@/api/modules/project";
import { getRelevanceList } from "@/api/modules/common";
import DialogForm from "@/components/DialogForm/index.vue";
import AMap from "@/components/AMap/AMap.vue";
import { GlobalStore } from "@/stores";
import engineeringEngDrawer from "@/components/engineeringEngDrawer/index.vue";
import allEngineering from "@/components/allEngineering/index.vue";

const store = GlobalStore();
const visible = ref(false);
const isOpen = ref(false);
const searchSn = ref();
const activeValue = ref("eng");
const engList = ref([]);
const engVisable = ref(false);
const title = ref("");
// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref();

interface formData {
	name?: string;
	code?: string;
	hardwareId?: string;
	lat?: number | undefined;
	lng?: number | undefined;
	position?: string;
	priority: number;
}

const formData = ref<formData>({
	name: "",
	code: "",
	hardwareId: "",
	priority: 1,
	lat: undefined,
	lng: undefined,
	position: ""
});

// 修改数据按钮
const handleEditItem = async (index: number, row: any) => {
	if (index === 1) {
		formConfig.formItemConfig[1].disabled = false;
		title.value = "新增视频";
		formData.value = reactive({
			name: "",
			code: "",
			hardwareId: "",
			priority: 1,
			lat: undefined,
			lng: undefined,
			position: ""
		});
	} else {
		formConfig.formItemConfig[1].disabled = true;
		title.value = "编辑视频";
		formData.value = reactive({ ...row });
		// 判断后端返回的经纬度是不是为null
		row.lng === null
			? formData.value.position === ""
			: (formData.value.position = "经度：" + row.lng + "，" + "维度：" + row.lat);
	}
	visible.value = true;
};

// 表格配置项
const columns: ColumnProps[] = [
	{ type: "index", label: "序号", width: 80 },

	// 多级 prop

	// { prop: "engineeringName", label: "工程名称" },
	{ prop: "name", label: "视频名称", search: { el: "input" } },
	{ prop: "state", label: "在线状态" },
	{ prop: "code", label: "监控点编码" },
	{ prop: "operation", label: "操作", fixed: "right" }
];

// 弹窗中的配置
const formConfig = reactive({
	formItemConfig: [
		{
			label: "设备名称",
			prop: "name",
			type: "input"
		},
		{
			label: "监控点编码",
			prop: "code",
			type: "input",
			disabled: true
		},
		{
			label: "显示排序",
			prop: "priority",
			type: "number"
		},

		{
			label: "经纬度",
			prop: "position",
			type: "input",
			mapIcon: true
		}
	],
	rules: {
		name: [
			{
				required: true,
				message: "请输入视频名称",
				trigger: "blur"
			}
		],
		code: [
			{
				required: true,
				message: "请输入设备编码",
				trigger: "blur"
			}
		],
		priority: [
			{
				required: true,
				message: "请输入排序",
				trigger: "blur"
			}
		],
		position: [
			{
				required: true,
				message: "请输入经纬度",
				trigger: "change"
			}
		]
	}
});

// 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 (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 getvideoManagementPage(newParams);
};

// 删除用户信息
const handleDeleteItem = async (params: jxj_User.ResUserList) => {
	await useHandleData(deletevideoManagement, { monitorId: params.monitorId }, `删除【${params.name}】`);
	proTable.value.getTableList();
};

// 页面新增，编辑数据
const saveItem = async (form: any) => {
	if (activeValue.value == "eng") {
		form.engineeringSn = searchSn.value;
	} else if (activeValue.value == "project") {
		form.projectSn = searchSn.value;
	}
	if (form.monitorId) {
		const res = await editvideoManagement(form);
		proTable.value.getTableList();
		ElMessage.success("编辑成功");
	} else {
		const res = await addvideoManagementment(form);
		ElMessage.success("新增成功");
		proTable.value.getTableList();
	}
	visible.value = false;
};

const getAddress = async (e: any) => {
	formData.value.lng = e.lng;
	formData.value.lat = e.lat;
	formData.value.position = "经度：" + e.lng + "，" + "维度：" + e.lat;
	isOpen.value = false;
	ElMessage.success("获取经纬度成功");
};

// 抽屉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;
	}
	console.log(res);
};
// 点击抽屉的工程名称更新页面
const onUpdate = async row => {
	if (activeValue.value == "eng") {
		searchSn.value = row.engineeringSn;
	} else if (activeValue.value == "project") {
		searchSn.value = row.projectSn;
	}
	ElMessage.success("页面已更新");
};
onMounted(async () => {
	getengineering();
});
</script>
