<template>
	<div class="contenBox">
		<div class="table-action flex-b">
			<div class="customList">{{ contentConfig.header.title ? contentConfig.header.title : '' }}</div>
			<div class="btns">
				<slot name="button"></slot>
			</div>
		</div>
		<el-table
			:data="pageList"
			style="width: 100%; max-height: 55vh; overflow: auto"
			@selection-change="handleSelectionChange"
			ref="multipleTableRef"
			v-bind="props.contentConfig?.tableProps"
			:row-key="getRowKeys"
			v-loading="loading"
		>
			<template v-for="item in contentConfig.propsList">
				<!-- 序号 -->
				<el-table-column
					:fixed="item.fixed"
					v-if="item.type === 'index'"
					type="index"
					:key="item.prop"
					center
				>
				</el-table-column>
				<!-- 选择 -->
				<el-table-column
					:fixed="item.fixed"
					type="selection"
					width="55"
					align="center"
					:key="item.prop"
					v-if="item.type === 'selection'"
					:reserve-selection="true"
				/>
				<!-- 操作类 -->
				<el-table-column
					:key="item"
					:fixed="item.fixed"
					align="center"
					v-bind="item"
					v-else-if="item.type === 'handler'"
				>
					<template #default="scope">
						<slot :name="item.slotName" v-bind="scope"></slot>
					</template>
				</el-table-column>

				<!-- 自定义类 -->
				<el-table-column
					show-overflow-tooltip
					:fixed="item.fixed"
					:key="item.label"
					v-else-if="item.type === 'custom'"
					:label="item.label"
					:width="item.width"
					:prop="item.prop"
					:sortable="item.sortable || false"
					:column-key="item.prop"
				>
					<template #default="scope">
						<slot :name="item.slotName" v-bind="scope"></slot>
					</template>
				</el-table-column>
				<!-- 时间类 -->
				<el-table-column
					show-overflow-tooltip
					:fixed="item.fixed"
					:key="item.label"
					v-else-if="item.type === 'time'"
					align="center"
					:label="item.label"
					:width="item.width"
				>
					<template #default="scope">
						{{ parseTime(scope.row[item.prop]) }}
					</template>
				</el-table-column>
				<!-- 普通渲染类 -->
				<el-table-column
					:fixed="item.fixed"
					show-overflow-tooltip
					v-else-if="item.type === 'normal'"
					:key="item.label"
					v-bind="item"
					:prop="item.prop"
					:sortable="item.sortable || false"
					:column-key="item.prop"
				/>
				<!-- 倒序类 -->
				<el-table-column
					:fixed="item.fixed"
					show-overflow-tooltip
					v-else-if="item.type === 'sortable'"
					:key="item.label"
					sortable
					v-bind="item"
				/>
			</template>
		</el-table>
	</div>
</template>

<script setup lang="ts" name="content">
import useSystemStore from '@/store/main';
import { parseTime } from '@/utils/ruoyi';
import useUserStore from '@/store/modules/user';
const userStore = useUserStore().userInfo.userName === 'admin' ? '' : useUserStore().userInfo.userId;
import { ref, watch } from 'vue';
// import { ElTable } from 'element-plus';
import { useSharedValueStore } from './sharedValueStore';

const props = withDefaults(
	defineProps<{
		contentConfig: {
			pageName: string;
			status: string;
			createUser: string;
			oneself: number;
			header: {
				title: string;
			};
			tableProps: any;
			propsList: any[];
			pageListParams?: {};
			moneyTotal?: boolean;
			energyConsumption?: boolean;
			energyConsumptionType?: boolean;
			energyMonery?: boolean;
			moneyTotalType?: boolean;
			customSubtotal?: boolean;
		};
		sizes?: number[];
		showSummary?: boolean;
		summaryMethod?: () => any;
		subtotalNum?: number;
	}>(),
	{
		sizes: [10, 50, 100, 300, 500],
		customSubtotal: false,
	}
);
const emit = defineEmits(['handleSelect', 'pageChanged']);
const loading = ref(true);

// 请求数据
const systemStore = useSystemStore();
// const pageNum = ref(1);
// const pageSize = ref(10);

const sharedValueStore = useSharedValueStore();
const sharedValue = computed(() => sharedValueStore.sharedValue);

// 获取列表
async function fetchPageListData(queryInfo: any = {}) {
	loading.value = true;
	// const pageNumber = pageNum.value;
	// const pageSizeValue = pageSize.value;
	// 2.发生网络请求
	await systemStore
		.getPageListDataAction(props.contentConfig.pageName, {
			pageNum: systemStore.pageInfo.pageNum,
			pageSize: systemStore.pageInfo.pageSize,
			userId: userStore,
			status: props.contentConfig.status,
			createUser: props.contentConfig.createUser,
			oneself: props.contentConfig.oneself,
			...queryInfo,
			...props.contentConfig.pageListParams,
		})
		.then(res => {
			loading.value = false;
		})
		.finally(() => {
			loading.value = false;
		});
}

fetchPageListData();
systemStore.$onAction(arg => {
	if (arg.name === 'newPageDataAction' || arg.name === 'deletePageDataAction') {
		// pageNum.value = 1;
		// pageSize.value = 10;
		systemStore.pageInfo.pageNum = 1;
		systemStore.pageInfo.pageSize = 50;
	}
});

// 2.展示数据
const { pageList, pageTotalCount, resDate } = storeToRefs(systemStore);
// 监听列表数据变化清空选择器
const multipleTableRef = ref();
let subtotal = ref(0 as any);
let subNumber = ref(0 as any);
const clearFlag = ref(true);
const rowDate = reactive<any>([]);
const electricityDosage = ref();
const gasDosage = ref();
const waterDosage = ref();
const electricityTotalPrice = ref();
const gasTotalPrice = ref();
const waterTotalPrice = ref();
watch(
	() => resDate,
	(newValue: any) => {
		if (props.contentConfig?.energyConsumption === true) {
			if (props.contentConfig?.energyConsumptionType === false) {
				rowDate.value = newValue._object.resDate.otherEnergyList;
			} else {
				electricityDosage.value = newValue._object.resDate.electricityDosage;
				gasDosage.value = newValue._object.resDate.gasDosage;
				waterDosage.value = newValue._object.resDate.waterDosage;
			}
		}
		if (props.contentConfig?.energyMonery === true) {
			electricityTotalPrice.value = newValue._object.resDate.electricityDosage;
			gasTotalPrice.value = newValue._object.resDate.gasDosage;
			waterTotalPrice.value = newValue._object.resDate.waterDosage;
		}
	},
	{ deep: true }
);
watch(
	() => pageList,
	(newValue: any) => {
		if (clearFlag.value) {
			multipleTableRef.value!.clearSelection();
			subtotal.value = 0;
			subNumber.value = 0;
		}
		// 控制是否清空所选项
		clearFlag.value = true;
		// pageList.value.forEach((item: any) => {
		//     subtotal.value += item.moneyTotal;
		// });
		// subtotal.value = Number(subtotal.value.toFixed(2)).toFixed(2);
	},
	{ deep: true }
);
// 处理选中状态
const selectedItems = ref([] as any);

const getRowKeys = row => {
	return row.checkId;
};

const echoWay = async () => {
	await pageList.value.forEach((row: any) => {
		if (selectedItems.value!.indexOf(row.checkId) >= 0) {
			multipleTableRef.value!.toggleRowSelection(row, true);
		}
	});
	// console.log(selectedItems.value);
};

// 清空多选
function clearSelection() {
	if (pageList) {
		multipleTableRef.value!.clearSelection();
	}
}
const water = ref();
const electricity = ref();
const gas = ref();
// 多选框切换
function handleSelectionChange(e: any) {
	emit('handleSelect', e);
	if (props.contentConfig.energyMonery) {
		water.value = 0;
		electricity.value = 0;
		gas.value = 0;
		e.forEach(item => {
			if (item.energyType == '水') {
				let waters = item.moneyTotal * 100; // 将金额转换为分;
				water.value += waters;
			} else if (item.energyType == '电') {
				let electricitys = item.moneyTotal * 100; // 将金额转换为分;
				electricity.value += electricitys;
			} else if (item.energyType == '气') {
				let gase = item.moneyTotal * 100; // 将金额转换为分;
				gas.value += gase;
			}
		});
		water.value = (water.value / 100).toFixed(2);
		electricity.value = (electricity.value / 100).toFixed(2);
		gas.value = (gas.value / 100).toFixed(2);
		console.log('zheshi', water.value, electricity.value, gas.value);
	} else {
		subtotal.value = 0;
		subNumber.value = 0;
		selectedItems.value = [];
		e.forEach(item => {
			subNumber.value += item.moneyTotal;
			let moneyTotalInCents = item.moneyTotal * 100; // 将金额转换为分
			subtotal.value += moneyTotalInCents;
			selectedItems.value.push(item.checkId);
		});
		subtotal.value = (subtotal.value / 100).toFixed(2);
		// selectedItems.value = e.map(item => {
		//     console.log(item.moneyTotal);
		//     subtotal.value += item.moneyTotal;
		//     return item.checkId;
		// });
		// console.log(subtotal.value);
	}
}

// 页码变化
async function onPageSizeChange(size: number) {
	// 每页条数改变函数
	// pageSize.value = size;
	// pageNum.value = 1;
	systemStore.pageInfo.pageSize = size;
	systemStore.pageInfo.pageNum = 1;
	// 控制是否清空所选项
	clearFlag.value = false;
	await fetchPageListData();
	// 恢复选中状态
	// await echoWay();
}
async function onPageChange(current: number) {
	// 页码改变函数
	systemStore.pageInfo.pageNum = current;
	systemStore.pageInfo.pageNum = current;
	// 控制是否清空所选项
	clearFlag.value = false;
	await fetchPageListData();
	// 恢复选中状态
	// await echoWay();
}
watch(
	() => sharedValueStore.pageNum,
	(newVal, oldVal) => {
		// pageNum.value = 1;
		systemStore.pageInfo.pageNum = 1;
	},
	{ deep: true }
);
// 暴露函数
defineExpose({
	clearSelection,
	fetchPageListData,
});
</script>

<style scoped lang="scss">
.contenBox {
	padding: 15px 20px 20px 20px;
	margin-top: 20px;
	background-color: #fff;

	.table-action {
		margin-bottom: 15px;

		button {
			margin-right: 10px;
		}
	}

	.ivu-table-header thead tr th {
		background-color: #f0f9fe;
	}
}

.customList {
	color: #606266;
	font-weight: 700;
}

.itemName {
	margin: 0 10px 5px 10px;
}

.energyClass {
	display: flex;
	align-items: center;
	flex-wrap: wrap;
	flex: 1;
}
</style>
