<template>
	<view>
		<view class="filterBar">
			<u-search v-model="filters.order_no" placeholder="出仓单号" :show-action="false" @search="loadList" @custom="loadList" />
			<view class="filterBtn" @click="filterShow = true">
				<u-icon name="list" size="40" color="#666"></u-icon>
				<text>筛选</text>
			</view>
		</view>

		<scroll-view scroll-y :style="{ height: scrollHeight }" refresher-enabled
			:refresher-triggered="triggered" @refresherrefresh="onRefresh">
			<dataNull v-if="list.length === 0" src="/src/static/img/chahua/gjNull.png"
				title="暂无加工出仓单" title1="请点击右下角按钮新增">
			</dataNull>
			<view v-for="(item, index) in list" :key="item.id" @click="goView(item)">
				<ProcessOutItem :item="item" :index="index" />
			</view>
		</scroll-view>

		<addBtn url="./storeGoodsProcessOutAdd"></addBtn>

		<u-popup v-model="filterShow" mode="right" width="580rpx" :safe-area-inset-bottom="true">
			<view class="filterPanel">
				<view class="filterTitle">筛选条件</view>
				<view class="filterItem">
					<text class="filterLabel">出仓单号</text>
					<u-input v-model="filters.order_no" placeholder="请输入出仓单号" />
				</view>
				<view class="filterItem" @click="openProcessUnitSelect">
					<text class="filterLabel">加工单位</text>
					<view class="filterValue">{{ processUnitLabel || '全部' }} <u-icon name="arrow-right" size="28"></u-icon></view>
				</view>
				<view class="filterItem" @click="openWarehouseSelect">
					<text class="filterLabel">仓库</text>
					<view class="filterValue">{{ warehouseLabel || '全部' }} <u-icon name="arrow-right" size="28"></u-icon></view>
				</view>
				<view class="filterItem" @click="openStatusSelect">
					<text class="filterLabel">订单状态</text>
					<view class="filterValue">{{ statusLabel || '全部' }} <u-icon name="arrow-right" size="28"></u-icon></view>
				</view>
				<view class="filterActions">
					<u-button type="warning" size="medium" @click="resetFilter">重置</u-button>
					<u-button type="primary" size="medium" @click="applyFilter">确定</u-button>
				</view>
			</view>
		</u-popup>

		<u-select v-model="statusSelectShow" :list="statusSelectList" @confirm="onStatusConfirm"></u-select>
		<u-select v-model="unitSelectShow" :list="unitSelectList" @confirm="onUnitConfirm"></u-select>
	</view>
</template>

<script>
import addBtn from '@/components/addBtn/addBtn.vue';
import ProcessOutItem from '@/components/card/storeGoodsProcessOutItem.vue';
import {
	getStatusOptions,
	AUDIT_STATUS_MAP,
	BUSINESS_UNIT_TYPE_PROCESS,
	WAREHOUSE_TYPE_FINISHED,
	formatRoll,
	mapToSelectOptions,
	fetchAllOrderList,
} from '@/common/storeGoodsProcessOut';

export default {
	components: { addBtn, ProcessOutItem },
	data() {
		return {
			list: [],
			scrollHeight: '667px',
			triggered: false,
			listLoading: false,
			filterShow: false,
			statusSelectShow: false,
			unitSelectShow: false,
			unitSelectType: '',
			processUnitOptions: [],
			warehouseOptions: [],
			unitOptionsLoading: false,
			filters: {
				order_no: '',
				process_unit_id: '',
				process_name: '',
				warehouse_id: '',
				warehouse_name: '',
				audit_status: '',
			},
			statusSelectList: [
				{ value: '', label: '全部' },
				...getStatusOptions(),
			],
		};
	},
	computed: {
		statusLabel() {
			if (this.filters.audit_status === '' || this.filters.audit_status === null) return '';
			return AUDIT_STATUS_MAP[Number(this.filters.audit_status)] || '';
		},
		processUnitLabel() {
			return this.filters.process_name || '';
		},
		warehouseLabel() {
			return this.filters.warehouse_name || '';
		},
		unitSelectList() {
			const options = this.unitSelectType === 'warehouse' ? this.warehouseOptions : this.processUnitOptions;
			return [{ value: '', label: '全部' }, ...options];
		},
	},
	onLoad() {
		uni.setNavigationBarTitle({ title: '加工出仓列表' });
		uni.getSystemInfo({
			success: (res) => {
				this.scrollHeight = `${res.windowHeight - 50}px`;
			},
		});
	},
	onShow() {
		this.loadList();
	},
	methods: {
		loadProcessUnitOptions() {
			if (this.processUnitOptions.length) return Promise.resolve(this.processUnitOptions);
			return this.$u.api.businessUnit.list({ unit_type_id: BUSINESS_UNIT_TYPE_PROCESS })
				.then((res) => {
					this.processUnitOptions = mapToSelectOptions(res);
					return this.processUnitOptions;
				})
				.catch(() => {
					this.processUnitOptions = [];
					return this.processUnitOptions;
				});
		},
		loadWarehouseOptions() {
			if (this.warehouseOptions.length) return Promise.resolve(this.warehouseOptions);
			return this.$u.api.physicalWarehouse.getDropdownList({ warehouse_type_id: WAREHOUSE_TYPE_FINISHED })
				.then((res) => {
					this.warehouseOptions = mapToSelectOptions(res);
					return this.warehouseOptions;
				})
				.catch(() => {
					this.warehouseOptions = [];
					return this.warehouseOptions;
				});
		},
		openUnitSelect(type) {
			if (this.unitOptionsLoading) return;
			this.unitOptionsLoading = true;
			const loadFn = type === 'warehouse' ? this.loadWarehouseOptions : this.loadProcessUnitOptions;
			loadFn.call(this)
				.then((list) => {
					if (!list.length) {
						uni.showToast({ title: '暂无可选数据', icon: 'none' });
						return;
					}
					this.unitSelectType = type;
					this.unitSelectShow = true;
				})
				.finally(() => {
					this.unitOptionsLoading = false;
				});
		},
		openProcessUnitSelect() {
			this.openUnitSelect('process');
		},
		openWarehouseSelect() {
			this.openUnitSelect('warehouse');
		},
		onUnitConfirm(e) {
			const item = e[0] || {};
			if (this.unitSelectType === 'warehouse') {
				this.filters.warehouse_id = item.value;
				this.filters.warehouse_name = item.value ? item.label : '';
			} else {
				this.filters.process_unit_id = item.value;
				this.filters.process_name = item.value ? item.label : '';
			}
		},
		loadList() {
			if (this.listLoading) return;
			this.listLoading = true;
			const params = {};
			if (this.filters.order_no) params.order_no = this.filters.order_no;
			if (this.filters.process_unit_id) params.process_unit_id = this.filters.process_unit_id;
			if (this.filters.warehouse_id) params.warehouse_id = this.filters.warehouse_id;
			if (this.filters.audit_status !== '' && this.filters.audit_status !== null) {
				params.audit_status = this.filters.audit_status;
			}
			fetchAllOrderList((p) => this.$u.api.fpmProcessOutOrder.list(p), params)
				.then((rows) => {
					this.list = rows.map(this.mapToCard);
				})
				.catch((err) => {
					this.list = [];
					uni.showToast({ title: err.message || '加载失败', icon: 'none' });
				})
				.finally(() => {
					this.listLoading = false;
					this.triggered = false;
					// 避免并发请求下 uView 全局 loading 遮罩关不掉
					uni.hideLoading();
				});
		},
		mapToCard(order) {
			return {
				id: order.id,
				order_no: order.order_no || '',
				process_unit_id: order.process_unit_id || '',
				process_name: order.process_name || '',
				warehouse_id: order.warehouse_id || '',
				warehouse_name: order.warehouse_name || '',
				create_user_name: order.creator_name || '',
				create_time: order.create_time || '',
				auditor_name: order.auditor_name || '',
				audit_date: order.audit_time || '',
				audit_status: order.audit_status,
				audit_status_name: order.audit_status_name || AUDIT_STATUS_MAP[order.audit_status] || '',
				total_roll: formatRoll(order.total_roll),
			};
		},
		onRefresh() {
			this.triggered = true;
			this.loadList();
		},
		goView(item) {
			uni.navigateTo({ url: `./storeGoodsProcessOutView?id=${item.id}` });
		},
		openStatusSelect() { this.statusSelectShow = true; },
		onStatusConfirm(e) { this.filters.audit_status = e[0].value; },
		resetFilter() {
			this.filters = {
				order_no: '',
				process_unit_id: '',
				process_name: '',
				warehouse_id: '',
				warehouse_name: '',
				audit_status: '',
			};
		},
		applyFilter() {
			this.filterShow = false;
			this.loadList();
		},
	},
};
</script>

<style>
page { background-color: #F8F8F8; }
.filterBar { display: flex; align-items: center; padding: 16rpx 20rpx; background: #fff; gap: 16rpx; }
.filterBtn { display: flex; flex-direction: column; align-items: center; font-size: 22rpx; color: #666; min-width: 80rpx; }
.filterPanel { padding: 30rpx; }
.filterTitle { font-size: 32rpx; font-weight: bold; margin-bottom: 30rpx; }
.filterItem { margin-bottom: 24rpx; }
.filterLabel { display: block; font-size: 28rpx; color: #666; margin-bottom: 12rpx; }
.filterValue { display: flex; align-items: center; justify-content: space-between; padding: 16rpx; background: #f5f5f5; border-radius: 8rpx; font-size: 28rpx; }
.filterActions { display: flex; gap: 20rpx; margin-top: 40rpx; }
</style>
