<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.native="$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">
			<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="onTableRowDel">
							<SvgIcon name="elementDelete" />删除
						</el-button>
					</div>
				</div>
			</template>
			<!--数据表格-->

			<el-table :data="tableData" @selection-change="handleSelectionChange">
				<el-table-column type="selection" width="55" align="center" />
				<el-table-column
					v-for="(item, index) in filteredListData"
					:key="index"
					:label="item.columnTitle"
					:width="item.htmlWidth ? item.htmlWidth : ''"
					:prop="item.fieldName"
				>
					<template #default="scope" v-if="$slots[item.fieldName]">
						<slot :name="item.fieldName" :row="scope.row"></slot>
					</template>
					<template #default="scope" v-if="item.dictType">
						<el-tag type="success" disable-transitions>{{ findDictLabel(scope.row[item.fieldName], item.fieldName) || '-- --' }} </el-tag>
					</template>
				</el-table-column>
				<!-- <el-table-column label="创建时间" align="center" prop="createTime" width="180">
                    <template #default="scope">
                        <span>{{ dateStrFormat(scope.row.createTime) }}</span>
                    </template>
                </el-table-column> -->
				<el-table-column label="操作" align="center" class-name="small-padding fixed-width">
					<template #default="scope">
						<div style="display: flex; align-items: center; justify-content: center; gap: 10px">
							<div>
								<el-tooltip class="box-item" effect="dark" content="编辑" placement="top-start">
									<el-button
										type="primary"
										size="small"
										circlesize="small"
										circle
										v-auth="`${className}:edit`"
										@click="$emit('onOpenEditModule', scope.row)"
									>
										<SvgIcon :size="12" name="elementEdit" />
									</el-button>
								</el-tooltip>
							</div>
							<div>
								<slot name="listBtn" :row="scope.row"></slot>
							</div>
							<div>
								<el-tooltip class="box-item" effect="dark" content="删除" placement="top-start">
									<el-button type="danger" size="small" circle v-auth="`${className}:delete`" @click="onTableRowDel(scope.row)">
										<SvgIcon :size="12" name="elementDelete" />
									</el-button>
								</el-tooltip>
							</div>
						</div>
					</template>
				</el-table-column>
			</el-table>
			<!-- 分页设置-->
			<div v-show="total > 0">
				<el-divider></el-divider>
				<el-pagination
					background
					:total="total"
					:current-page="state.queryParams.pageNum"
					:page-size="state.queryParams.pageSize"
					layout="total, sizes, prev, pager, next, jumper"
					@size-change="handleSizeChange"
					@current-change="handleCurrentChange"
				/>
			</div>
		</el-card>
	</div>
</template>

<script lang="ts" setup name="Partner">
import { reactive, onMounted, getCurrentInstance, onUnmounted, computed, watch } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import { del, get } from '@/api/public/basic';

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: '',
	},
});
// emits
const emit = defineEmits(['handleQuery', 'onOpenEditModule', 'onOpenAddModule']);
const state = reactive({
	tableStructData: [],
	// 选中数组
	ids: [],
	// 非单个禁用
	single: true,
	// 非多个禁用
	multiple: true,
	// 查询参数
	queryParams: {
		// 页码
		pageNum: 1,
		// 每页大小
		pageSize: 10,
	},
});

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

// 列表展示字段
const filteredListData = computed(() => {
	return state.tableStructData.filter((item: any) => item.isList) || [];
});

// 监听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 arr = res.data.result.map((item: any) => {
					if (item.isQuery) {
						state.queryParams[item.fieldName] = undefined;
					}
					// 如果存在字典数据
					if ((item.isQuery || item.isList) && item.dictType) {
						proxy.getDicts(item.dictType).then((response: any) => {
							state[item.fieldName + 'Option'] = response.data;
						});
					}

					return item;
				});
				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;
	});
	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 onTableRowDel = (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) => {
	state.ids = selection.map((item: any) => {
		return item[props.mainKeyName];
	});

	state.single = selection.length != 1;
	state.multiple = !selection.length;
};
// 页面加载时
onMounted(() => {});
// 页面卸载时
onUnmounted(() => {
	proxy.mittBus.off('onEditModule');
});
</script>
