<template>
	<cl-crud ref="Crud">
		<el-row>
			<!-- 刷新按钮 -->
			<cl-refresh-btn />
			<!-- 新增按钮 -->
			<cl-add-btn />
			<!-- 删除按钮 -->
			<cl-multi-delete-btn />
			<cl-flex1 />
			<!-- 关键字搜索 -->
			<cl-search-key />
		</el-row>

		<el-row>
			<!-- 数据表格 -->
			<cl-table ref="Table" row-key="id" @row-click="onRowClick">
				<!-- 行新增 -->
				<template #slot-add="{ scope }">
					<el-button type="success" text bg @click="append(scope.row)">新增</el-button>
				</template>
			</cl-table>
		</el-row>

		<el-row>
			<cl-flex1 />
			<!-- 分页控件 -->
			<cl-pagination layout="total" />
		</el-row>

		<!-- 新增、编辑 -->
		<cl-upsert ref="Upsert">
			<template #slot-parentId="{ scope }">
				<layers-select v-model="scope.parentId" />
			</template>
		</cl-upsert>
	</cl-crud>
</template>

<script lang="ts" name="base-sys-layers" setup>
import { useCrud, useTable, useUpsert } from "@cool-vue/crud";
import { useCool } from "/@/cool";
import { deepTree } from "/@/cool/utils";
import LayersSelect from "./components/select.vue";
import { computed, onMounted, nextTick, ref } from "vue";
import Sortable from "sortablejs";
import { isArray } from "lodash-es";

const { service } = useCool();

const table_list = ref<any[]>([]);

// 行拖拽
const rowDrop = function () {
	// 要拖拽元素的父容器
	const tbody = document.querySelector(".el-table__body-wrapper tbody");
	Sortable.create(tbody, {
		//  可被拖拽的子元素
		// draggable: ".draggable .el-table__row",
		onEnd(evt: any) {
			let newArr = table_list.value;
			console.log(newArr);
			let oldIndex = evt.oldIndex;
			let newIndex = evt.newINdex;
			const currRow = newArr.splice(oldIndex, 1)[0];
			newArr.splice(newIndex, 0, currRow);
			table_list.value = [];
			nextTick(async () => {
				// table_list.value = newArr;
				const ids: any[] = [];

				function deep(list: any[], pid: any) {
					list.forEach((e) => {
						e.parentId = pid;
						ids.push(e);

						if (e.children && isArray(e.children)) {
							deep(e.children, e.id);
						}
					});
				}

				deep(newArr, null);

				await service.base.sys.department
					.order(
						ids.map((e, i) => {
							return {
								id: e.id,
								parentId: e.parentId,
								// 有两个排序字段，pid,layerorder,ordernum,laycode都需要考虑考虑如何处理,做完功能后记得把实体中的表名改回去
								orderNum: i
							};
						})
					)
					.then(() => {
						// ElMessage.success("更新排序成功");
					})
					.catch((err) => {
						// ElMessage.error(err.message);
					});
				console.log(table_list.value);
			});
		}
	});
};

// cl-upsert 配置
const Upsert = useUpsert({
	dialog: {
		width: "800px"
	},
	items: [
		{
			label: "图层名称",
			span: 12,
			prop: "layerName",
			required: true,
			component: {
				name: "el-input",
				props: {
					data: computed(async () => {
						const data = Upsert.value?.getForm("layerName");
						if (Upsert.value?.mode == "add") {
							const orderNum = await service.base.sys.layers.getMaxOrderNum();
							Upsert.value?.setForm("orderNum", orderNum);
						}
						return data;
					})
				}
			}
		},
		{
			prop: "parentId",
			span: 12,
			label: "上级图层",
			component: {
				name: "slot-parentId"
			}
		},
		{
			label: "图层类型",
			prop: "layerType",
			span: 12,
			value: [],
			component: {
				name: "el-select",
				options: [],
				props: {
					// 编辑的时候两个排序号有问题，需解决
					data: computed(async () => {
						const data = Upsert.value?.getForm("layerType");
						const id = Upsert.value?.getForm("id");
						let oldLayerType = "";
						if (id !== undefined) {
							oldLayerType = await (
								await service.base.sys.layers.info({ id: id })
							).layerType;
						}
						console.log(data);
						if (data.indexOf(",") > 0) {
							// if (data.toString().split(",")[0] !== oldLayerType) {
							const layerType = data.toString().split(",")[0];
							Upsert.value?.setForm("layerType", layerType);
							const loadType = data.toString().split(",")[1];
							Upsert.value?.setForm("loadType", loadType);
							const layerCode = data.toString().split(",")[2];
							Upsert.value?.setForm("layerCode", layerCode);
							const parameterSet = data.toString().split(",")[3];
							Upsert.value?.setForm("parameterSet", parameterSet);
							const layerOrder = await service.base.sys.layers.getMaxLayerOrder({
								layerCode: layerCode
							});
							Upsert.value?.setForm("layerOrder", layerOrder);
							const orderNum = await service.base.sys.layers.getMaxOrderNum();
							Upsert.value?.setForm("orderNum", orderNum);
							// }
						}
						return data;
					})
				}
			}
		},
		{
			label: "接口类型",
			prop: "loadType",
			span: 12,
			value: "#",
			required: true,
			component: {
				name: "el-input"
				// options: [
				// 	{
				// 		label: "UrlTemplateImageryProvider",
				// 		value: "UrlTemplateImageryProvider"
				// 	},
				// 	{
				// 		label: "Cesium3DTileset",
				// 		value: "Cesium3DTileset"
				// 	},
				// 	{
				// 		label: "Cesium3DTileset_BM",
				// 		value: "Cesium3DTileset_BM"
				// 	},
				// 	{
				// 		label: "PolygonImageMaterial",
				// 		value: "PolygonImageMaterial"
				// 	},
				// 	{
				// 		label: "entitiesGltf",
				// 		value: "entitiesGltf"
				// 	},
				// 	{
				// 		label: "GeoJsonPolyline",
				// 		value: "GeoJsonPolyline"
				// 	},
				// 	{
				// 		label: "GeoJsonPoint",
				// 		value: "GeoJsonPoint"
				// 	},
				// 	{
				// 		label: "CrImageServerLayer",
				// 		value: "CrImageServerLayer"
				// 	},
				// 	{
				// 		label: "WebMapTileServiceImageryProvider",
				// 		value: "WebMapTileServiceImageryProvider"
				// 	},
				// 	{
				// 		label: "WebMapServiceImageryProvider",
				// 		value: "WebMapServiceImageryProvider"
				// 	},
				// 	{
				// 		label: "ArcGisMapServerImageryProvider",
				// 		value: "ArcGisMapServerImageryProvider"
				// 	},
				// 	{
				// 		label: "TileMapServiceImageryProvider",
				// 		value: "TileMapServiceImageryProvider"
				// 	},
				// 	{
				// 		label: "DEM",
				// 		value: "DEM"
				// 	}
				// ]
			}
		},
		{
			label: "类型编码",
			prop: "layerCode",
			component: {
				name: "el-input"
			}
		},
		{
			label: "图层顺序",
			prop: "layerOrder",
			component: {
				name: "el-input-number",
				props: {
					placeholder: "请填写图层顺序",
					min: 0,
					max: 99,
					"controls-position": "right"
				}
			}
		},
		{
			label: "排序号",
			prop: "orderNum",
			required: true,
			component: {
				name: "el-input-number",
				props: {
					placeholder: "请填写排序号",
					min: 0,
					max: 99,
					"controls-position": "right"
				}
			}
		},
		{
			label: "数据源",
			prop: "dataSource",
			required: true,
			value: "#",
			component: {
				name: "el-input",
				props: { type: "textarea", rows: 4 }
			}
		},
		{ label: "样式图片", prop: "imageUrl", component: { name: "cl-upload" } },
		{
			label: "参数集",
			prop: "parameterSet",
			component: { name: "el-input", props: { type: "textarea", rows: 6 } }
		},
		{ label: "过滤条件", span: 12, prop: "queryFilter", component: { name: "el-input" } },
		{
			label: "是否查询",
			span: 12,
			prop: "mapQuery",
			component: {
				name: "el-select",
				options: [
					{
						label: "否",
						value: ""
					},
					{
						label: "是,表查询",
						value: "table"
					},
					{
						label: "是,服务查询",
						value: "url"
					}
				]
			}
		},
		{ label: "查询源", span: 12, prop: "querySetLi", component: { name: "el-input" } },
		{ label: "展示字段", span: 12, prop: "displayField", component: { name: "el-input" } },
		{ label: "查询字段", span: 12, prop: "queryField", component: { name: "el-input" } },
		{ label: "查询提示", span: 12, prop: "promptInfo", component: { name: "el-input" } }
	],

	async onOpen() {
		let typeId;
		await service.dict.type.list({ name: "图层类型" }).then((res) => {
			if (res.length > 0) {
				typeId = res[0].id;
			}
		});
		const list = await service.dict.info.list({ typeId: typeId });

		// 设置图层类型列表
		Upsert.value?.setOptions(
			"layerType",
			list.map((e) => {
				return {
					label: e.name || "",
					value:
						(e.name || "") +
						"," +
						(e.value || "") +
						"," +
						(e.orderNum || "") +
						"," +
						(e.remark || "")
				};
			})
		);
	}
});

// cl-table 配置
const Table = useTable({
	columns: [
		{ type: "selection" },
		// { label: "ID", prop: "id" },
		{ label: "图层名称", prop: "layerName" },
		{ label: "图层类型", prop: "layerType", dict: [] },
		{ label: "图层顺序", prop: "layerOrder" },
		{ label: "排序号", prop: "orderNum" },
		{ label: "类型编码", prop: "layerCode" },
		{ label: "数据源", prop: "dataSource" },
		// { label: "过滤条件", prop: "filterConditions" },
		// { label: "参数集", prop: "parameterSet" },
		// { label: "接口类型", prop: "loadType", dict: [] },
		// { label: "是否查询", prop: "mapQuery" },
		// { label: "数据表", prop: "table" },
		// { label: "展示字段", prop: "displayField" },
		// { label: "查询字段", prop: "queryField" },
		// { label: "查询提示", prop: "promptInfo" },
		{ label: "创建时间", prop: "createTime" },
		// { label: "更新时间", prop: "updateTime" },
		{ type: "op", buttons: ["edit", "delete"] }
	]
});

// cl-crud 配置
const Crud = useCrud(
	{
		service: service.base.sys.layers,
		onRefresh(_, { render }) {
			service.base.sys.layers.list().then((list) => {
				render(deepTree(list));
				table_list.value = list;
			});
		}
	},
	(app) => {
		app.refresh();
	}
);

// 行点击展开
function onRowClick(row: any, column: any) {
	if (column?.property && row.children) {
		Table.value?.toggleRowExpansion(row);
	}
}

// 子集新增
function append({ type, id }: any) {
	Crud.value?.rowAppend({
		parentId: id,
		parentType: type,
		type: type + 1,
		keepAlive: true,
		isShow: true
	});
}
// onMounted(function () {
// 	rowDrop();
// });
</script>
