<template>
	<view class="">
		<u-sticky offset-top="50">
			<u-subsection fontSize='25' mode='subsection' :list="list" :current="curNow" @change="sectionChange"
				activeColor='#157A2C'></u-subsection>
		</u-sticky>

		<!-- 基本信息 -->
		<view v-show='curNow===0'>
			<u--form style="margin: 0 20px;" labelPosition="left" :model="form" ref="uForm" labelWidth='180rpx'>
				<u-form-item label="采购计划单名称" prop="planName" borderBottom @click="handParent">
					<u--input style="width: 100%;" v-model="form.planName" placeholder="点击选择"></u--input>
				</u-form-item>
				<u-form-item label="询价单名称" prop="inquiryName" borderBottom>
					<u--input style="width: 100%;" v-model="form.inquiryName"></u--input>
				</u-form-item>
				<u-form-item label="是否接受拆单" prop="acceptUnpack" borderBottom>
					<u-tag v-if='form.acceptUnpack==1' text="接受" size="large" type="success"></u-tag>
					<u-tag v-else-if='form.acceptUnpack==0' text="不接受" size="large" type="warning"></u-tag>
					<u--input v-else style="width: 100%;" disabled value="-"></u--input>
				</u-form-item>
				<u-form-item label="备注" prop="remark" borderBottom>
					<u--input style="width: 100%;" v-model="form.remark"></u--input>
				</u-form-item>
				<u-form-item label="附件" prop="files" borderBottom>
					<fileMain v-model="form.files" type="add"></fileMain>
				</u-form-item>
			</u--form>
		</view>

		<!-- 物品清单 -->
		<view v-show='curNow===1'>
			<inventoryTable :productList="productList" :acceptUnpack="form.acceptUnpack" status="edit"
				ref="inventoryTableRef" @supplierSelect="onItemSupplierSelect">
			</inventoryTable>
		</view>

		<!-- 报价清单 -->
		<view v-show='curNow===2'>
			<inquiryTable ref="inquiryTableRef" :supplierList="supplierList" status="edit"></inquiryTable>
			<u-empty v-if="!supplierList.length" text="暂无报价" mode="list"></u-empty>
		</view>
	</view>
</template>

<script>
	import {
		getpurchaseinquiry
	} from '@/api/purchasingManage/inquiryManage'
	import { getplanDetail } from '@/api/purchasingManage/purchasePlanManage'
	import fileMain from "@/pages/doc/index.vue"
	import inquiryTable from './inquiryTable.vue'
	import inventoryTable from './inventoryTable.vue'
	import { contactQueryByCategoryIdsAPI } from '@/api/warehouseManagement/index.js'
	import { orderSourceType } from '@/enum/dict'

	export default {
		components: {
			fileMain,
			inquiryTable,
			inventoryTable
		},
		props: {
			businessId: {
				default: ''
			},
			taskDefinitionKey: {
				default: ''
			},
		},
		data() {
			return {
				form: {},
				supplierList: [],
				productList: [],
				rawList: [],
				outputList: [],
				loading: false,
				list: ['基本信息', '物品清单', '报价清单'],
				curNow: 0
			}
		},
		async mounted() {
			await this.getDetailData(this.businessId, 'init')
			// 监听采购计划选择回调
			uni.$on('changeInquiryManageList', (data) => {
				this.changeInquiryManageList(data)
			})
			// 监听供应商选择回调
			uni.$on('supplierManageChange', (data) => {
				this.supplierManageChange(data)
			})
		},
		beforeDestroy() {
			uni.$off('changeInquiryManageList')
			uni.$off('supplierManageChange')
		},
		methods: {
			sectionChange(index) {
				this.curNow = index
			},
			// 打开采购计划选择页
			handParent() {
				uni.navigateTo({
					url: '/pages/home/wt/components/pricingManage/inquiryManageList?planCode=' + (this.form.planCode || '')
				})
			},
			// 打开供应商选择页
			openSupplier() {
				uni.navigateTo({
					url: '/pages/home/wt/components/pricingManage/supplierManageList'
				})
			},
			// 选择采购计划后回调
			changeInquiryManageList(data) {
				console.log('changeInquiryManageList~~', data)
				this.getplanData(data.id, 'change')
			},
			// 选择供应商后回调
			supplierManageChange(list) {
				const existingIds = this.supplierList.map(item => item.supplierId)
				list.forEach(supplier => {
					if (!existingIds.includes(supplier.supplierId)) {
						this.supplierList.push(supplier)
					}
				})
			},
			// 物品清单中某产品选择供应商
			onItemSupplierSelect(item, index) {
				console.log('onItemSupplierSelect~~', item)
				uni.navigateTo({
					url: '/pages/home/wt/components/pricingManage/supplierManageList'
				})
			},
			// 获取计划详情
			async getplanData(id, type) {
				this.loading = true
				const data = await getplanDetail(id)
				this.rawList = data.rawDetailList || []
				this.outputList = data.outputDetailList || []
				this.loading = false
				if (data) {
					// 获取产品对应的供应商
					const supplierObj = await this.getSupplierObj(data.detailList, 'productId')
					// 处理产品列表：补充到货日期和供应商信息
					data.detailList.forEach((item) => {
						if (item.arrivalWay == 2 && item.arrivalBatch && item.arrivalBatch.length > 0) {
							item.expectReceiveDate = item.arrivalBatch[item.arrivalBatch.length - 1].arriveDate
						}
						item.supplierList = supplierObj[item.productId] || []
						if (item.supplierList.length === 1) {
							item.supplierIds = [item.supplierList[0].id]
						}
					})
					// 设置表单字段
					this.$set(this.form, 'acceptUnpack', data.acceptUnpack)
					this.form.planId = data.id
					this.form.planCode = data.planCode
					this.form.planName = data.planName
					// init 类型不覆盖 productList（已在 getDetailData 中设置）
					if (type === 'init') return
					// 变更时合并产品清单
					if (orderSourceType.includes(this.form.sourceType)) {
						this.productList = [...data.detailList, ...this.rawList, ...this.outputList]
					} else {
						this.productList = [...data.detailList]
					}
				}
			},
			async getSupplierObj(productList, queryName) {
				try {
					const categoryIds = productList.map((item) => item[queryName])
					return await contactQueryByCategoryIdsAPI({ categoryIds })
				} catch (e) {
					return Promise.resolve({})
				}
			},
			async getDetailData(id, type) {
				this.loading = true
				const data = await getpurchaseinquiry(id)
				this.loading = false
				if (data) {
					this.form = data
					this.supplierList = data.supplierList || []
					// 获取产品对应的供应商列表
					const supplierObj = await this.getSupplierObj(data.detailList, 'productId')
					data.detailList.forEach((item) => {
						item.supplierList = supplierObj[item.productId] || []
					})
					// 合并产品清单
					this.rawList = data.rawList || []
					this.outputList = data.outputList || []
					if (orderSourceType.includes(this.form.sourceType)) {
						this.productList = [...data.detailList, ...this.rawList, ...this.outputList]
					} else {
						this.productList = [...data.detailList]
					}
					// 是否首次加载，需要拉取计划详情
					if (type === 'init') {
						this.getplanData(data.planId, type)
					}
				}
			},
			async getTableValue() {
				// 1. 校验基本信息
				if (!this.form.inquiryName) {
					uni.showToast({ title: '请输入询价单名称', icon: 'none' })
					return false
				}
				if (!this.form.planId) {
					uni.showToast({ title: '请选择采购计划', icon: 'none' })
					return false
				}

				// 2. 校验物品清单不为空
				const inventoryData = this.$refs.inventoryTableRef?.getTableValue()
				if (!inventoryData || inventoryData.length === 0) {
					uni.showToast({ title: '物品清单不能为空', icon: 'none' })
					return false
				}

				// 3. 校验报价清单
				const supplierList = this.$refs.inquiryTableRef?.getTableValue() || []
				if (supplierList.length === 0) {
					uni.showToast({ title: '报价清单不能为空', icon: 'none' })
					return false
				}
				for (let i = 0; i < supplierList.length; i++) {
					const supplier = supplierList[i]
					// 校验供应商可填写字段
					if (!supplier.settlementMode) {
						uni.showToast({ title: `供应商${supplier.supplierName || i + 1}：请选择结算方式`, icon: 'none' })
						return false
					}
					if (!supplier.deliveryDate) {
						uni.showToast({ title: `供应商${supplier.supplierName || i + 1}：请选择交货日期`, icon: 'none' })
						return false
					}
					// 校验报价明细
					const items = supplier.resultList || []
					for (let j = 0; j < items.length; j++) {
						const item = items[j]
						const name = item.productName || item.productCode || (j + 1)
						if (item.isWinner === '' || item.isWinner === null || item.isWinner === undefined) {
							uni.showToast({ title: `${supplier.supplierName || ''} ${name}：请选择是否中标`, icon: 'none' })
							return false
						}
						if (!item.supplierProductName) {
							uni.showToast({ title: `${supplier.supplierName || ''} ${name}：请输入供应商产品名称`, icon: 'none' })
							return false
						}
						if (!item.purchaseCount || item.purchaseCount <= 0) {
							uni.showToast({ title: `${supplier.supplierName || ''} ${name}：请输入数量`, icon: 'none' })
							return false
						}
						if (!item.singlePrice || item.singlePrice <= 0) {
							uni.showToast({ title: `${supplier.supplierName || ''} ${name}：请输入单价`, icon: 'none' })
							return false
						}
						if (!item.taxRate && item.taxRate !== 0) {
							uni.showToast({ title: `${supplier.supplierName || ''} ${name}：请输入税率`, icon: 'none' })
							return false
						}
						// 校验最低订购量
						if (item.minimumOrderQuantity && item.purchaseCount < item.minimumOrderQuantity) {
							uni.showToast({ title: `${supplier.supplierName || ''} ${name}：购买数量不能小于最低订购量`, icon: 'none' })
							return false
						}
					}
				}

				// 4. 组装返回数据
				this.form.detailList = inventoryData
				this.form.supplierList = supplierList
				// 合并 rawList/outputList 到 supplierList
				if (orderSourceType.includes(this.form.sourceType)) {
					this.form.supplierList.forEach(sup => {
						sup.resultList = [...(sup.resultList || []), ...this.rawList, ...this.outputList]
					})
				}
				this.form.files = this.form.files || []
				return this.form
			},
		}
	}
</script>

<style lang="scss" scoped>
</style>
