// 注册 Vant 组件
Vue.use(vant.NavBar);
Vue.use(vant.Steps);
Vue.use(vant.Step);
Vue.use(vant.Search);
Vue.use(vant.Radio);
Vue.use(vant.RadioGroup);
Vue.use(vant.Button);
Vue.use(vant.List);
Vue.use(vant.Toast);
Vue.use(vant.Dialog);

var app = new Vue({
	el: "#app",
	data: {
		// 搜索关键字
		searchKeyword: '',

		// 选中的盘点单ID
		selectedId: null,

		// 选中的盘点单对象
		selectedItem: null,

		// 所有盘点单数据
		allInventoryList: [],

		// 过滤后的列表
		filteredList: [],

		// 当前显示的列表
		displayedList: [],

		// 当前加载到第几页
		currentPage: 0,

		// 每页显示数量
		pageSize: 10,

		// 是否正在加载
		loading: false,

		// 是否加载完毕
		finished: false,

		// IndexDB 数据库实例
		checkVouchDb: null,
	},

	methods: {
		/**
		 * 返回上一页
		 */
		goBack: function () {
			history.go(-1);
		},

		/**
		 * 去同步页面
		 */
		goToSync: function () {
			window.location.href = './DataSync.html';
		},

		/**
		 * 从 IndexDB 加载盘点单数据
		 */
		loadInventoryData: function () {
			var _self = this;

			if (!_self.checkVouchDb) {
				vant.Toast.fail('数据库未初始化');
				return;
			}

			_self.checkVouchDb.getAll('checkVouchList', function (dataList) {
				if (dataList && dataList.length > 0) {
					// 转换数据格式
					_self.allInventoryList = dataList.map(function (item) {
						return {
							id: item.checkVouchId,
							checkVouchId: item.checkVouchId,
							name: item.name,
							documentNo: item.documentNo,
							warehouseId: item.warehouseId,
							warehouseName: item.warehouseName,
							description: item.description,
							inventoryStartDate: item.inventoryStartDate || '',
							inventoryEndDate: item.inventoryEndDate || '',
							cfCheckVouchsResponses: item.cfCheckVouchsResponses || []
						};
					});
					_self.filteredList = _self.allInventoryList;
					console.log('从 IndexDB 加载了 ' + dataList.length + ' 条盘点单数据');
				} else {
					console.log('IndexDB 中没有盘点单数据');
					_self.allInventoryList = [];
					_self.filteredList = [];
				}
			}, function (error) {
				console.error('从 IndexDB 加载盘点单数据失败:', error);
				vant.Toast.fail('加载盘点单数据失败');
				_self.allInventoryList = [];
				_self.filteredList = [];
			});
		},

		/**
		 * 格式化日期
		 */
		formatDate: function (date) {
			var year = date.getFullYear();
			var month = String(date.getMonth() + 1).padStart(2, '0');
			var day = String(date.getDate()).padStart(2, '0');
			var hours = String(date.getHours()).padStart(2, '0');
			var minutes = String(date.getMinutes()).padStart(2, '0');
			var seconds = String(date.getSeconds()).padStart(2, '0');

			return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds;
		},

		/**
		 * 搜索处理
		 */
		onSearch: function () {
			var _self = this;
			var keyword = _self.searchKeyword.trim().toLowerCase();

			if (!keyword) {
				// 如果搜索关键字为空，显示全部
				_self.filteredList = _self.allInventoryList;
			} else {
				// 前端搜索：根据名称、单据号搜索
				_self.filteredList = _self.allInventoryList.filter(function (item) {
					return item.name.toLowerCase().indexOf(keyword) > -1 ||
						item.documentNo.toLowerCase().indexOf(keyword) > -1;
				});
			}

			// 重置分页
			_self.resetPagination();
		},

		/**
		 * 重置分页
		 */
		resetPagination: function () {
			var _self = this;
			_self.currentPage = 0;
			_self.displayedList = [];
			_self.finished = false;
			_self.loading = true;

			// 触发加载
			_self.onLoad();
		},

		/**
		 * 加载更多数据
		 */
		onLoad: function () {
			var _self = this;

			// 模拟加载延迟
			setTimeout(function () {
				var startIndex = _self.currentPage * _self.pageSize;
				var endIndex = startIndex + _self.pageSize;

				// 获取当前页的数据
				var pageData = _self.filteredList.slice(startIndex, endIndex);

				if (pageData.length > 0) {
					// 追加到显示列表
					_self.displayedList = _self.displayedList.concat(pageData);
					_self.currentPage++;
					_self.loading = false;

					// 判断是否加载完毕
					if (_self.displayedList.length >= _self.filteredList.length) {
						_self.finished = true;
					}
				} else {
					// 没有更多数据了
					_self.finished = true;
					_self.loading = false;
				}
			}, 300);
		},

		/**
		 * 选择盘点单
		 */
		selectItem: function (item) {
			var _self = this;
			_self.selectedId = item.id;
			_self.selectedItem = item;
		},

		/**
		 * 下一步
		 */
		goNext: function () {
			var _self = this;

			if (!_self.selectedItem) {
				vant.Toast.fail('请先选择盘点单');
				return;
			}

			// 保存选中的盘点单到localStorage
			localStorage.setItem('selectedInventory', JSON.stringify(_self.selectedItem));

			// 跳转到盘点页面
			window.location.href = './AssetInventoryCheck.html';
		},

		/**
		 * 初始化
		 */
		init: function () {
			var _self = this;

			// 初始化 IndexDB 数据库
			var objectStoreDefines = [
				{
					name: 'checkVouchList',
					defineOption: { keyPath: 'checkVouchId' },
					indexDefineList: null
				},
				{
					name: 'uploadQueue',
					defineOption: { keyPath: 'checkVouchId' },
					indexDefineList: null
				}
			];

			_self.checkVouchDb = new IndexDbFactory('checkVouchDB', objectStoreDefines, 1);
			_self.checkVouchDb.open(function () {
				console.log('盘点数据库初始化成功');
				// 数据库初始化成功后，加载盘点单数据
				_self.loadInventoryData();
			}, function () {
				console.error('盘点数据库初始化失败');
				vant.Dialog.alert({
					title: '错误',
					message: '数据库初始化失败，请先进行数据同步。',
					theme: 'round-button',
				});
			});
		}
	},

	created: function () {
		console.log('AssetInventorySelect Vue实例创建完成');
	},

	mounted: function () {
		var _self = this;
		_self.init();
		console.log('AssetInventorySelect页面加载完成');
		
		// 隐藏页面加载指示器
		setTimeout(function() {
			var loadingElement = document.getElementById('pageLoading');
			if (loadingElement) {
				loadingElement.style.display = 'none';
			}
		}, 100);
	}
});
