<template>
	<view style="width: 100%;">
		<u-action-sheet :show="show" @close="onClose">
			<view class="cu-bar bg-white">
				<view class="action text-blue"  @tap="onClose">取消</view>
				<view v-if="isShow">
					<u-radio-group v-model="checkType" >
						<u-radio
								:customStyle="{marginRight: '16px'}"
								v-for="(item, index) in checkTypeList"
								:key="index"
								:label="item.name"
								:name="item.value"
								@change="checkTypeChange"
						></u-radio>
					</u-radio-group>
				</view>
				<view class="action text-green" @tap="selectUsers">确定</view>
			</view>
			<view style="max-height: 300px; overflow-y: auto;">
				<view v-for="item in data" :key="item.id" style="padding: 10px;">
					<view @tap="onItemClick(item)" style="display: flex; align-items: center;">
						<view style="flex: 1;text-align: left; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">{{ item.projectName }}</view>
						<view v-if="item.checked" style="color: #409eff;">已选择</view>
					</view>
				</view>
			</view>
			<view v-if="!allDataLoaded && !loading" style="text-align: center; padding: 10px;">
				<button class="load-more-button" @tap="loadMore">加载更多</button>
			</view>
			<view v-if="loading" style="text-align: center; padding: 10px;">
				Loading...
			</view>
		</u-action-sheet>
	</view>
</template>

<script>
	import projectRecordsService from '@/api/cw/projectRecords/ProjectRecordsService'

	export default {
		data() {
			return {
				checkType: '1',
				checkTypeList: [{
					name: '项目',
					value: '1',
					disabled: false
				},{
					name: '报告',
					value: '2',
					disabled: false
				}],
				show: false,
				isShow: false,
				labels:'',
				index:'',
				type:'',
				data: [],
				localMode: '', // 声明一个本地数据属性
				allDataLoaded: false, // 跟踪是否所有数据都已加载
				loading: false, // 跟踪加载状态
				pageSize: 10, // 每页获取的项目数
				currentPage: 1 // 当前页数
			};
		},
		props: {
			value: String,
			placeholder: {
				type: String,
				default: '请选择项目'
			},
			readonly: {
				type: Boolean,
				default: false
			},
			disabled: {
				type: Boolean,
				default: false
			},
		},
		mounted() {
			// this.loadData();
		},
		methods: {
			init(index, type) {
				this.pageSize = 10
				this.currentPage = 1
				this.show = true;
				this.index = index;
				//选项的选择模式，单选或多选，默认为多选
				// if (type === 'report') {
				// 	this.localMode = 'single'
				// } else {
				// 	this.localMode = 'multiple'
				// }
				this.localMode = 'multiple'
				if (this.isNotEmpty(type)) {
					this.checkType = type
					this.isShow = false
				} else {
					this.isShow = true
				}
				if (index === 1 || index === '1') {
					if (type === '1') {
						uni.showToast({
							title: '第一条为项目后面新增只能选择项目',
							icon: 'none',
							duration: 2000
						});
					} else if (type === '2') {
						uni.showToast({
							title: '第一条为报告后面新增只能选择报告',
							icon: 'none',
							duration: 2000
						});
					}
				}

				this.loadData();
			},
			onItemClick(item) {
				if (this.localMode  === 'single') {
					this.data.forEach(node => {
						node.checked = node === item;
					});
				} else {
					item.checked = !item.checked;
				}
			},
			selectUsers() {

				if (this.data.some(item => item.checked)) {
					let checkedItems = this.data.filter(item => item.checked).map(item => {
						return {
							id: item.id,
							projectName: item.projectName,
							contractName: item.contractName,
							projectNumber: item.projectNumber,
							contractId: item.contractId,
							reportNo: item.reportNo,
							isPreInvoice: item.isPreInvoice,
						};
					});
					this.$emit('input', checkedItems, this.index);
					this.onClose()
				} else {
					uni.showToast({
						title: '请至少选择一条数据',
						icon: 'none',
						duration: 2000
					});
				}
			},
			loadData() {
				this.loading = true; // 开始加载数据，显示loading状态
				if (this.checkType === '1') {
					projectRecordsService.noReportList({ status: 5, current: this.currentPage, pageSize: this.pageSize })
							.then(data => {
								this.loading = false; // 数据加载完成，隐藏loading状态
								// 检查新返回的数据是否已经存在，如果存在，则不添加到原始数据数组中
								let newData = data.records.filter(record => !this.data.some(item => item.id === record.id));
								if (this.currentPage === 1) {
									// 如果是加载第一页，则直接赋值给 data
									this.data = newData.map(item => ({ ...item, checked: false }));
								} else {
									// 如果不是第一页，则追加到原始数据数组后面
									this.data = [...this.data, ...newData.map(item => ({ ...item, checked: false }))];
								}
								if (data.records.length < this.pageSize) {
									this.allDataLoaded = true; // 如果返回的数据少于每页数量，则表示所有数据都已加载
								}
								if (this.value) {
									let keys = this.value.split(',');
									this.data.forEach(node => {
										if (keys.includes(node.id)) {
											node.checked = true;
										}
									});
									this.labels = this.data.filter(node => node.checked).map(node => node.label).join(',');
								}
							})
							.catch(e => {
								this.loading = false; // 数据加载失败，隐藏loading状态
								throw e;
							});
				} else if (this.checkType === '2') {
					projectRecordsService.list1({ status: 5, current: this.currentPage, pageSize: this.pageSize })
							.then(data => {
								this.loading = false; // 数据加载完成，隐藏loading状态
								// 检查新返回的数据是否已经存在，如果存在，则不添加到原始数据数组中
								let newData = data.records.filter(record => !this.data.some(item => item.id === record.id));
								if (this.currentPage === 1) {
									// 如果是加载第一页，则直接赋值给 data
									this.data = newData.map(item => ({ ...item, checked: false }));
								} else {
									// 如果不是第一页，则追加到原始数据数组后面
									this.data = [...this.data, ...newData.map(item => ({ ...item, checked: false }))];
								}
								if (data.records.length < this.pageSize) {
									this.allDataLoaded = true; // 如果返回的数据少于每页数量，则表示所有数据都已加载
								}
								if (this.value) {
									let keys = this.value.split(',');
									this.data.forEach(node => {
										if (keys.includes(node.id)) {
											node.checked = true;
										}
									});
									this.labels = this.data.filter(node => node.checked).map(node => node.label).join(',');
								}
							})
							.catch(e => {
								this.loading = false; // 数据加载失败，隐藏loading状态
								throw e;
							});
				}
			},
			loadMore() {
				this.currentPage++; // 增加当前页数
				this.loadData(); // 加载更多数据
			},
			onClose() {
				// 在关闭操作中清除已选择标记
				this.data.forEach(item => {
					item.checked = false;
				});
				this.labels = ''; // 清空标签
				this.show = false;
				this.checkType = '1';
				this.data = []; // 清空原始数据
			},
			checkTypeChange(value){
				this.checkType = value
				this.pageSize = 10
				this.currentPage = 1
				this.data = []; // 清空原始数据
				this.loadData(); // 加载更多数据
			},
			isEmpty(value) {
				let result = false;
				if (value == null || value == undefined) {
					result = true;
				}
				if (typeof value == 'string' && (value.replace(/\s+/g, "") == "" || value == "")) {
					result = true;
				}
				if (typeof value == "object" && value instanceof Array && value.length === 0) {
					result = true;
				}
				return result;
			},
			isNotEmpty (value) {
				return !this.isEmpty(value)
			},
		}
	};
</script>

<style scoped>
	.load-more-button {
		background-color: #409eff;
		color: #fff;
		border: none;
		padding: 10px 20px;
		border-radius: 4px;
		cursor: pointer;
	}
</style>
