<template>
	<view class="mainBox">
		<view v-for="(item, index) in productList" :key="index">
			<myCard :item="item" :index="index + 1" :columns="columns">
				<!-- 产品名称（标题行） -->
				<view slot="productName">
					<text style="font-weight: 600;">{{ item.productName || '-' }}</text>
				</view>
				<!-- 供应商选择 -->
				<view slot="supplierIds">
					<view v-if="isView" class="supplier-view">
						<text class="supplier-text">{{ getSupplierNames(item) || '点击选择供应商' }}</text>
						<text class="arrow">›</text>
					</view>
					<view v-else>
						<u-row gutter="10">
							<u-col span="8">
								<view class="supplier-tags" @click="openPicker(item, index)">
									<text v-if="!item.supplierIds || !item.supplierIds.length" class="placeholder">选择供应商</text>
									<!-- <u-tag v-for="sId in (item.supplierIds || [])" :key="sId" :text="getSupplierNameById(item, sId)" size="mini" type="success" :closeable="true" @close="removeSupplierId(item, index, sId)"></u-tag> -->
                  <text v-else>{{ getSupplierNames(item) || '-' }}</text>
								</view>
							</u-col>
							<u-col span="4">
								<view class="supplier-tags" @click="openPicker(item, index)">
									<u-tag text="选择" size="mini" type="primary" @click="openPicker(item, index)"></u-tag>
								</view>
							</u-col>
						</u-row>
					</view>
				</view>
				<!-- 核价状态 -->
				<view slot="isInquiry">
					<text>{{ getInquiryStatus(item.isInquiry) || '-' }}</text>
				</view>
				<!-- 物品级别 -->
				<view slot="goodsLevel">
					<text>{{ getGoodsLevel(item.goodsLevel) || '-' }}</text>
				</view>
				<!-- 属性类型 -->
				<view slot="produceType">
					<text>{{ getProduceType(item.produceType) || '-' }}</text>
				</view>
				<!-- 产地 -->
				<view slot="provenance">
					<text>{{ getProvenance(item.provenance) || '-' }}</text>
				</view>
				<!-- 附件 -->
				<view slot="files">
					<fileMain :value="item.files || []" type="view" v-if="item.files && item.files.length"></fileMain>
					<text v-else>-</text>
				</view>
				<!-- 备注 -->
				<view slot="remark">
					<text>{{ item.remark || '-' }}</text>
				</view>
			</myCard>
		</view>
		<u-gap height="20" bgColor="#f0f0f0"></u-gap>
		<u-empty v-if="!productList.length" text="暂无物品" mode="list"></u-empty>

    <!-- 选择物品类型 -->
		<ba-tree-picker ref="treePicker" :multiple="true" @select-change="suplierConfirm" title="选择供应商"
			:localdata="supplierOptions" valueKey="id" textKey="name" childrenKey="child" />
	</view>
</template>

<script>
	import myCard from '@/pages/purchasingManage/components/myCard.vue'
	import fileMain from "@/pages/doc/index.vue"
	import { levelList, lbjtList } from '@/enum/dict.js'

	export default {
		components: {
			myCard,
			fileMain
		},
		props: {
			productList: {
				type: Array,
				default: () => []
			},
			status: {
				type: String,
				default: 'edit'
			},
			acceptUnpack: {
				default: ''
			}
		},
		data() {
			return {
        supplierOptions: [],
        currentIndex: -1,
				selection: [],
        // 核价状态
        inquiryStatusList: [
              { value: 0, text: '未核价' },
              { value: 1, text: '部分核价' },
              { value: 2, text: '全部核价完成' }
            ],
			}
		},
		computed: {
			isView() {
				return this.status === 'Detail'
			},
			btnList() {
				if (this.isView) return []
				return [
					{
						name: '生成报价单',
						apiName: 'supplierSelect',
						btnType: 'primary',
						type: '2',
						judge: [{ fn: (row) => !this.isView && row.supplierIds && row.supplierIds.length > 0 }]
					},
					{
						name: '删除',
						apiName: 'del',
						btnType: 'error',
						type: '2',
						judge: [{ fn: () => !this.isView && !!this.acceptUnpack }]
					}
				]
			},
			columns() {
				return [
					[{ label: '名称：', prop: 'productName', slot: 'productName', type: 'title', className: 'perce100' }],
					[{ label: '编码：', prop: 'productCode' }, { label: '分类：', prop: 'productCategoryName' }],
					[{ label: '核价状态：', prop: 'isInquiry', slot: 'isInquiry' }, { label: '物品级别：', prop: 'goodsLevel', slot: 'goodsLevel' }],
					[{ label: '供应商：', prop: 'supplierIds', slot: 'supplierIds', className: 'perce100' }],
					[{ label: '数量：', prop: 'purchaseCount', formatter: (item) => (item.purchaseCount || item.totalCount || '-') + ' ' + (item.purchaseUnit || item.measuringUnit || '') },
					 { label: '库存：', prop: 'availableCountBase', formatter: (item) => (item.availableCountBase || '-') + ' ' + (item.measuringUnit || '') }],
					[{ label: '型号：', prop: 'modelType' }, { label: '规格：', prop: 'specification' }],
					[{ label: '牌号：', prop: 'productBrand' }, { label: '图号/件号：', prop: 'imgCode' }],
					[{ label: '包装规格：', prop: 'packingSpecification' }, { label: '重量：', prop: 'totalWeight' }],
					[{ label: '属性类型：', prop: 'produceType', slot: 'produceType' }, { label: '产地：', prop: 'provenance', slot: 'provenance' }],
					[{ label: '工序：', prop: 'taskName' }, { label: '批次号：', prop: 'batchNo' }],
					[{ label: '到货日期：', prop: 'expectReceiveDate' }, { label: '附件：', prop: 'files', slot: 'files' }],
					[{ label: '备注：', prop: 'remark', slot: 'remark', className: 'perce100' }]
				]
			}
		},
		methods: {
      openPicker(item, index) {
        this.supplierOptions = item.supplierList || []
        this.currentIndex = index
				this.$refs.treePicker._show()
			},
			suplierConfirm(data, name, allList) {
				if (this.currentIndex === -1) return
				const item = this.productList[this.currentIndex]
				if (!item) return
				this.$set(item, 'supplierIds', (allList || []).map(s => s.id))
			},
			// 获取核价状态文本
      getInquiryStatus(val) {
        const found = this.inquiryStatusList.find(item => item.value == val)
        return found ? found.text : ''
      },
			getGoodsLevel(val) {
				const found = levelList.find(item => item.value == val)
				return found ? found.label || found.text : ''
			},
			getProduceType(val) {
				if (val && val.length) {
					return val.map(item => lbjtList[item] || item).toString()
				}
				return ''
			},
			getProvenance(val) {
				if (val && val.length) {
					return val.join(',')
				}
				return ''
			},
			getSupplierNames(item) {
        console.log('item-------', item)
				return (item.supplierIds || []).map(id => {
					const sup = (item.supplierList || []).find(s => s.id == id)
					return sup ? sup.name : ''
				}).filter(Boolean).join(', ')
			},
			getSupplierNameById(item, id) {
				const sup = (item.supplierList || []).find(s => s.id == id)
				return sup ? sup.name : id
			},
			removeSupplierId(item, index, id) {
				this.$set(this.productList[index], 'supplierIds', (item.supplierIds || []).filter(i => i != id))
			},
			onSupplierSelect(item, index) {
        console.log('onSupplierSelect~~', item)
				this.$emit('supplierSelect', item, index)
			},
			delProduct(index) {
				if (!this.acceptUnpack) {
					uni.showToast({ title: '本采购计划不能拆单', icon: 'none' })
					return
				}
				const code = this.productList[index]?.productCode
				this.productList.splice(index, 1)
				this.$emit('delList', code)
			},
			// 返回列表数据
			getTableValue() {
				const datasource = this.productList
				if (!datasource.length) return []
				datasource.forEach(v => {
					v.totalPrice = (v.totalCount * v.singlePrice)?.toFixed(2) || 0
					v.files = v.files || null
				})
				return datasource
			}
		}
	}
</script>

<style lang="scss" scoped>
	.mainBox {
		background: #fff;
	}

	.supplier-view {
		display: flex;
		align-items: center;
		justify-content: space-between;
		min-height: 44rpx;
		color: #157A2C;
		font-size: 26rpx;

		.supplier-text {
			flex: 1;
			overflow: hidden;
			text-overflow: ellipsis;
			white-space: nowrap;
		}

		.arrow {
			font-size: 32rpx;
			color: #ccc;
			margin-left: 8rpx;
		}
	}

	.supplier-tags {
		display: flex;
		flex-wrap: wrap;
		align-items: center;
		min-height: 44rpx;
		gap: 8rpx;

		.placeholder {
			color: #ccc;
			font-size: 26rpx;
		}
	}

	.text-gray {
		color: #999;
		font-size: 24rpx;
	}
</style>
