<template>
	<el-card style="margin-bottom: 20px">
		<!-- 查询 -->
		<el-form :model="state.queryParams" ref="queryForm" :inline="true">
			<el-form-item v-for="(item, index) in filteredQueryData" :label="item.columnTitle" :prop="item.fieldName"
				:key="index">
				<el-select v-if="item.htmlType == 'select'" v-model="state.queryParams[item.fieldName]"
					placeholder="请选择" clearable style="width: 240px">
					<el-option v-for="dict in state[item.fieldName + 'Option']" :key="dict.dictValue"
						:label="dict.dictLabel" :value="dict.dictValue" />
				</el-select>

				<el-date-picker v-else-if="item.htmlType == 'datetime'" v-model="state.queryParams[item.fieldName]"
					type="date" placeholder="请选择" clearable style="width: 240px" />
				<el-input v-else v-model="state.queryParams[item.fieldName]" :placeholder="'请输入'" clearable
					@keyup.enter="$emit('handleQuery', state.queryParams)" />
			</el-form-item>
			<el-form-item>
				<el-button type="primary" @click="$emit('handleQuery', state.queryParams)">
					<SvgIcon name="elementSearch" />搜索
				</el-button>
				<el-button @click="resetQuery">
					<SvgIcon name="elementRefresh" />
					重置
				</el-button>
			</el-form-item>
		</el-form>
	</el-card>
	<div v-loading="loading" style="min-height: 600px">
		<el-card class="box-card" v-if="filteredListData.length && className">
			<template #header>
				<div class="card-header">
					<span class="card-header-text">{{ listName }}</span>
					<div>
						<el-button type="primary" plain v-auth="`${className}:add`" @click="$emit('onOpenAddModule')">
							<SvgIcon name="elementPlus" />新增
						</el-button>
						<el-button type="danger" plain v-auth="`${className}:batchDelete`" :disabled="state.multiple"
							@click="handleTableRowDel">
							<SvgIcon name="elementDelete" />删除
						</el-button>
					</div>
				</div>
			</template>
			<!--数据表格-->
			<BasicList 
				:column="filteredListData"
				:rowData="tableData"
				@onTableRowDel="handleTableRowDel"
				@rowDoubleClicked="handleRowDoubleClicked">
			</BasicList>
			<!-- 分页设置-->
			<div v-show="total > 0">
				<el-divider></el-divider>
				<el-pagination background :total="total" v-model:current-page="state.queryParams.pageNum"
					v-model:page-size="state.queryParams.pageSize" :page-sizes="[10, 100, 200, 300, 500, 1000]"
					layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
					@current-change="handleCurrentChange" />
			</div>
		</el-card>
	</div>
</template>

<script lang="ts" setup >
import { reactive, onMounted, getCurrentInstance, onUnmounted, computed, watch } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import { del, get, } from '@/api/public/basic';
import { getDicts } from '@/api/system/dict/data';
import Text from './Text.vue';
import { BasicList } from '@/xForm/pc/index.es.js';

const { proxy } = getCurrentInstance() as any;
// props
const props = defineProps({
	listId: {
		type: String,
		default: '',
	},
	className: {
		type: String,
		default: '',
	},
	listName: {
		type: String,
		default: '',
	},
	tableData: {
		type: Array,
		default: () => [],
	},
	loading: {
		type: Boolean,
		default: true,
	},
	// 总条数
	total: {
		type: Number,
		default: 0,
	},
	// 当前表单的编码名
	mainKeyName: {
		type: String,
		default: '',
	},
});

interface TableStructData {
	fieldName: string;
	columnTitle: string;
	htmlType: string;
	isQuery: boolean;
	isList: boolean;
	dictType?: string;
	htmlWidth?: number;
	sort?: number;
}

// emits
const emit = defineEmits(['handleQuery', 'onOpenEditModule', 'onOpenAddModule', 'onTableRowDetail']);
const state = reactive({
	tableStructData: [] as TableStructData[],
	// 选中数组
	ids: [],
	// 非单个禁用
	single: true,
	// 非多个禁用
	multiple: true,
	// 查询参数
	queryParams: {
		// 页码
		pageNum: 1,
		// 每页大小
		pageSize: 10,
	},
	gridApi: {
		api: {} as any,
	},
});

// 可搜索的字段
const filteredQueryData = computed(() => {
	return state.tableStructData.filter((item: any) => item.isQuery) || [];
});


const ragCellClassRules = {
	// apply green to electric cars
	'tag-cell': (params) => true,
};

// 列表展示字段
const filteredListData = computed(() => {
	const newData = state.tableStructData.filter((item: any) => item.isList) || [];
	const col = newData.map((item: any) => {
		if (item.fieldName == props.mainKeyName) {
			return {
				hide: true,
			};
		}
		if (item.htmlType == 'textarea') {
			return {
				headerName: item.columnTitle,
				field: item.fieldName,
				width: item.htmlWidth ? item.htmlWidth : 'auto',
				cellRenderer: Text,
				cellRendererParams: {
					fieldName: item.fieldName,
				},
			};
		}

		if (item.dictType) {
			return {
				headerName: item.columnTitle,
				field: item.fieldName,
				width: item.htmlWidth ? item.htmlWidth : 'auto',
				cellClassRules: ragCellClassRules,
				// cellRenderer: Tag, // 自定义渲染
				// cellRendererParams: {
				// 	findDictLabel: findDictLabel,
				// 	fieldName: item.fieldName,
				// },
				valueFormatter: (params) => {
					return findDictLabel(params.value, item.fieldName);
				},
			};
		} else {
			return {
				headerName: item.columnTitle,
				field: item.fieldName,
				width: item.htmlWidth ? item.htmlWidth : 'auto',
			};
		}
	});
	return col;
});


// 监听props.list
watch(
	() => props.listId,
	() => {
		if (!props.listId) return;
		// 获取table struct
		const tableStructId = 'hQrMVhPV7LY';
		get(
			{
				pageNum: 1,
				pageSize: 50, // 暂时默认
				listId: props.listId,
			},
			tableStructId
		).then((res: any) => {
			if (res.status == 0) {
				const promises = res.data.result.map((item: any) => {
					if (item.isQuery) {
						state.queryParams[item.fieldName] = undefined;
					}
					// 如果存在字典数据
					if ((item.isQuery || item.isList) && item.dictType) {
						return getDicts(item.dictType).then((response: any) => {
							state[item.fieldName + 'Option'] = response.data;
							return item; // 返回 item 以便后续处理
						});
					}
					return Promise.resolve(item); // 如果没有字典数据，返回已解析的 item
				});

				// 等待所有的字典请求完成
				Promise.all(promises).then((arr) => {
					arr.sort(compareSorts);
					state.tableStructData = arr;
					emit('handleQuery', state.queryParams);
				});
			}
		});
	},
	{ immediate: true }
);



/** 字典label */
const findDictLabel = (dictValue, fieldName) => {
	if (!state[fieldName + 'Option']) return;
	const obj = state[fieldName + 'Option'].find((item) => item.dictValue == dictValue) || {};
	return obj.dictLabel;
};

/**比较两个对象的 sort 属性*/
const compareSorts = (a: any, b: any) => {
	// 如果 sort 属性为 null，则将其视为无穷大
	if (a.sort === null || b.sort === null) {
		return 0; // 不参与排序
	}
	// 比较 sort 属性
	return a.sort - b.sort;
};

/** 重置按钮操作 */
const resetQuery = () => {
	// state.tableStructData.forEach((item: any) => {
	// 	if (item.isQuery) {
	// 		state.queryParams[item.columnName] = undefined;
	// 	}
	// 	return item;
	// });
	state.queryParams = {
		// 页码
		pageNum: 1,
		// 每页大小
		pageSize: 10,
	}
	emit('handleQuery', state.queryParams);
};

const handleCurrentChange = (val: number) => {
	state.queryParams.pageNum = val;
	emit('handleQuery', state.queryParams);
};
const handleSizeChange = (val: number) => {
	state.queryParams.pageSize = val;
	emit('handleQuery', state.queryParams);
};


/** 删除按钮操作 */
const handleTableRowDel = (row: any) => {
	const ids = row[props.mainKeyName] ? [row[props.mainKeyName]] : state.ids;

	ElMessageBox({
		message: '是否确认删除的数据项?',
		title: '警告',
		showCancelButton: true,
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	}).then(function () {
		return del({ [props.mainKeyName]: ids }, props.listId).then(() => {
			emit('handleQuery', state.queryParams);
			ElMessage.success('删除成功');
		});
	});
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: any) => {
	console.warn(selection);
	// state.ids = selection.map((item: any) => {
	// 	return item[props.mainKeyName];
	// });

	// state.single = selection.length != 1;
	// state.multiple = !selection.length;
};

const handleRowDoubleClicked = (row: any) => {
	emit('onOpenEditModule', row);
};

// 页面加载时
onMounted(() => { });
// 页面卸载时
onUnmounted(() => {
	proxy.mittBus.off('onEditModule');
});
</script>
<style scope>
.tag-cell {
	background: #3a51c2;
	color: #fff;
}

.ag-watermark {
	display: none !important;
}


</style>
