<template>
	<view>
		<view class="mainBox" v-for="(supplier, sIndex) in supplierList" :key="supplier.supplierId || sIndex">
			<!-- 供应商头部 -->
			<view class="supplier-header">
			<view class="supplier-name">
				<text class="label">供应商：</text>
				<text class="value">{{ supplier.supplierName || '-' }}</text>
			</view>
			<view class="supplier-summary">
				<view class="summary-item">
					<text class="label">总价：</text>
					<text class="value price">{{ supplier.totalPrice || '-' }}</text>
				</view>
				<view class="summary-item">
					<text class="label">优惠后：</text>
					<text v-if="isView" class="value price">{{ supplier.preferentialPrice || '-' }}</text>
					<u--input v-else type="number" border="surround" v-model="supplier.preferentialPrice"
						placeholder="请输入优惠金额" style="width: 200rpx; display: inline-block;"></u--input>
				</view>
				<view class="summary-item">
					<text class="label">结算方式：</text>
					<text v-if="isView" class="value">{{ supplier.settlementModeName || '-' }}</text>
					<uni-data-picker v-else v-model="supplier.settlementMode" placeholder="请选择"
						:localdata="settlementModeList" @change="onSettlementChange(supplier)"></uni-data-picker>
				</view>
				<view class="summary-item">
					<text class="label">交货日期：</text>
					<text v-if="isView" class="value">{{ supplier.deliveryDate || '-' }}</text>
					<uni-datetime-picker v-else type="date" v-model="supplier.deliveryDate"
						@change="onDeliveryDateChange(supplier)"></uni-datetime-picker>
				</view>
			</view>
			<view class="supplier-summary">
				<view class="summary-item">
					<text class="label">附件：</text>
				</view>
				<fileMain :type="isView ? 'view' : ''" :value="supplier.files"
					@input="val => onSupplierFilesChange(sIndex, val)"></fileMain>
			</view>
		</view>

		<!-- 报价明细 -->
		<view v-for="(item, index) in (supplier.resultList || [])" :key="index">
			<myCard :item="item" :btnList="btnList" :index="index + 1" :columns="columns"
				@del="delProduct(sIndex, index)">
				<!-- 名称 -->
				<view slot="productName">
					<text style="font-weight: 600;">{{ item.productName || '-' }}</text>
				</view>
				<!-- 是否中标 -->
				<view slot="isWinner">
					<u-tag v-if="isView && item.isWinner == 1" text="中标" size="mini" type="success"></u-tag>
					<u-tag v-else-if="isView" text="未中标" size="mini" type="warning"></u-tag>
					<uni-data-picker v-else v-model="item.isWinner" placeholder="请选择"
						:localdata="isWinnerList"></uni-data-picker>
				</view>
				<!-- 数量 -->
				<view slot="purchaseCount">
					<view v-if="isView">{{ (item.purchaseCount || item.totalCount || '-') + ' ' + (item.purchaseUnit || item.measuringUnit || '') }}</view>
					<view v-else>
						<u-row>
							<u-col span="6">
								<u--input type="number" placeholder="数量" border="surround" v-model="item.purchaseCount"
									@input="changeCount(supplier, sIndex, index)"></u--input>
							</u-col>
							<u-col span="6">
								<uni-data-picker v-model="item.purchaseUnitId" placeholder="单位"
									:localdata="item.packageDispositionList || []"
                  :map="{
                    text: 'conversionUnit',
                    value: 'id'
                  }"
									@change="changeCount(supplier, sIndex, index)"></uni-data-picker>
							</u-col>
						</u-row>
					</view>
				</view>
				<!-- 单价 -->
				<view slot="singlePrice">
					<text v-if="isView">{{ item.singlePrice ? item.singlePrice + ' 元' : '-' }}</text>
					<u--input v-else type="number" placeholder="请输入单价" border="surround" v-model="item.singlePrice"
						@input="changeCount(supplier, sIndex, index)"></u--input>
				</view>
				<!-- 金额 -->
				<view slot="totalPrice">
					<text v-if="item.totalPrice">{{ item.totalPrice }} 元</text>
					<text v-else>-</text>
				</view>
				<!-- 税率（必填） -->
				<view slot="taxRate">
					<text v-if="isView">{{ item.taxRate || item.taxRate === 0 ? item.taxRate + '%' : '-' }}</text>
					<u--input v-else type="number" placeholder="请输入税率" border="surround" v-model="item.taxRate"
						@input="calcItemTotal(supplier, index)"></u--input>
				</view>
				<!-- 供应商产品名称 -->
				<view slot="supplierProductName">
					<text v-if="isView">{{ item.supplierProductName || item.supplierProductCode || '-' }}</text>
					<u--input v-else placeholder="请输入供应商产品名称" border="surround" v-model="item.supplierProductName"></u--input>
				</view>
				<!-- 供应商产品编码 -->
				<view slot="supplierProductCode">
					<text v-if="isView">{{ item.supplierProductCode || '-' }}</text>
					<u--input v-else placeholder="供应商产品编码" border="surround" v-model="item.supplierProductCode"></u--input>
				</view>
				<!-- 不含税单价 -->
				<view slot="notaxSinglePrice">
					<text>{{ item.notaxSinglePrice ? item.notaxSinglePrice + ' 元' : '-' }}</text>
				</view>
				<!-- 型号 -->
				<view slot="modelType">
					<text v-if="isView">{{ item.modelType || '-' }}</text>
					<u--input v-else placeholder="型号" border="surround" v-model="item.modelType"></u--input>
				</view>
				<!-- 规格 -->
				<view slot="specification">
					<text v-if="isView">{{ item.specification || '-' }}</text>
					<u--input v-else placeholder="规格" border="surround" v-model="item.specification"></u--input>
				</view>
				<!-- 产地（多选） -->
				<view slot="provenance">
					<text v-if="isView">{{ getProvenanceLabel(item.provenance) || '-' }}</text>
					<u--input v-else placeholder="点击选择产地" border="surround"
						:value="getProvenanceLabel(item.provenance)" @click.native="openProvenancePicker(sIndex, index)"></u--input>
				</view>
				<!-- 交期 -->
				<view slot="deliveryDays">
					<text v-if="isView">{{ item.deliveryDays || '-' }}</text>
					<u--input v-else type="number" placeholder="交期(天)" border="surround" v-model="item.deliveryDays"></u--input>
				</view>
				<!-- 有效期 -->
				<view slot="guaranteePeriod">
					<text v-if="isView">{{ item.guaranteePeriod || '-' }}</text>
					<u--input v-else type="number" placeholder="有效期" border="surround" v-model="item.guaranteePeriod"></u--input>
				</view>
				<!-- 有效期单位 -->
				<view slot="guaranteePeriodUnitCode">
					<text v-if="isView">{{ getGuaranteeUnitLabel(item.guaranteePeriodUnitCode) || '-' }}</text>
					<uni-data-picker v-else v-model="item.guaranteePeriodUnitCode" placeholder="请选择" :localdata="guaranteeUnitList" @change="onGuaranteeUnitChange(item)"></uni-data-picker>
				</view>
				<!-- 备注 -->
				<view slot="remark">
					<text v-if="isView">{{ item.remark || '-' }}</text>
					<u--input v-else placeholder="备注" border="surround" v-model="item.remark"></u--input>
				</view>
				<!-- 附件 -->
				<view slot="files">
					<fileMain :value="item.files || []" :type="isView ? 'view' : ''" v-if="item.files && item.files.length"></fileMain>
					<text v-else>-</text>
				</view>
			</myCard>
		</view>
		<u-gap height="20" bgColor="#f0f0f0"></u-gap>
		</view>
		<ba-tree-picker ref="provenancePicker" :multiple="true" @select-change="provenanceConfirm"
			title="选择产地" :localdata="provenanceList" valueKey="value" textKey="text" childrenKey="children" />
	</view>
</template>

<script>
	import myCard from '@/pages/purchasingManage/components/myCard.vue'
	import fileMain from "@/pages/doc/index.vue"
	import { changeCountNew as productChangeCount } from '@/utils/setProduct.js'
  import dictMixns from "@/mixins/dictMixins";
  import { mapGetters, mapActions } from 'vuex'
  import baTreePicker from '@/components/ba-tree-picker/ba-tree-picker.vue'

	export default {
    mixins: [dictMixns],
		components: {
			myCard,
			fileMain,
      baTreePicker
		},
		props: {
			supplierList: {
				type: Array,
				default: () => []
			},
			status: {
				type: String,
				default: 'edit'
			}
		},
		data() {
			return {
				isWinnerList: [
					{ text: '是', value: 1 },
					{ text: '否', value: 0 }
				],
				settlementModeList: [],
				provenanceList: [],
				guaranteeUnitList: [],
        curProvenanceSIndex: -1,
        curProvenancePIndex: -1
			}
		},
		computed: {
      ...mapGetters(['dict', 'getDict', 'getDictValue']),
			isView() {
				return this.status === 'Detail'
			},
			btnList() {
				return this.isView ? [] : [{
					name: '删除',
					apiName: 'del',
					btnType: 'error',
					type: '2'
				}]
			},
			columns() {
				return [
					[{
						label: '产品名称：', prop: 'productName', slot: 'productName',
						type: 'title', className: 'perce100'
					}],
					[{ label: '编码：', prop: 'productCode' }, {
						label: '是否中标：', prop: 'isWinner', slot: 'isWinner',
						isRequired: !this.isView
					}],
					[{
						label: '数量：', prop: 'purchaseCount', slot: 'purchaseCount',
						isRequired: !this.isView
					}, {
						label: '采购单价：', prop: 'singlePrice', slot: 'singlePrice',
						isRequired: !this.isView
					}],
					[{ label: '采购金额：', prop: 'totalPrice', slot: 'totalPrice' }, {
						label: '税率：', prop: 'taxRate', slot: 'taxRate',
						isRequired: !this.isView
					}],
					[{ label: '不含税单价：', prop: 'notaxSinglePrice', slot: 'notaxSinglePrice', className: 'perce100' }],
					[{
						label: '供应商产品：', prop: 'supplierProductName', slot: 'supplierProductName',
						className: 'perce100', isRequired: !this.isView
					}],
					[{
						label: '供应商产品编码：', prop: 'supplierProductCode', slot: 'supplierProductCode',
						className: 'perce100'
					}],
					[{ label: '型号：', prop: 'modelType', slot: 'modelType' }, { label: '规格：', prop: 'specification', slot: 'specification' }],
					[{ label: '产地：', prop: 'provenance', slot: 'provenance', className: 'perce100' }],
					[{ label: '需求数量：', prop: 'reqTotalCount' }, { label: '库存：', prop: 'availableCountBase' }],
					[{ label: '最低订购量：', prop: 'minimumOrderQuantity' }, { label: '包装规格：', prop: 'packingSpecification' }],
					[{ label: '交期(天)：', prop: 'deliveryDays', slot: 'deliveryDays' }, {
						label: '有效期：', prop: 'guaranteePeriod', slot: 'guaranteePeriod'
					}],
					[{
						label: '有效期单位：', prop: 'guaranteePeriodUnitCode', slot: 'guaranteePeriodUnitCode',
						className: 'perce100'
					}],
					[{ label: '工序：', prop: 'taskName' }, { label: '批次号：', prop: 'batchNo' }],
					[{ label: '备注：', prop: 'remark', slot: 'remark', className: 'perce100' }],
					// [{ label: '附件：', prop: 'files', slot: 'files', className: 'perce100' }]
				]
			}
		},
		async created() {
			if (!this.isView) {
				await this.requestDict('结算方式')
        await this.requestDict('产地')
        await this.requestDict('质保期单位')
				this.settlementModeList = this.dict?.['settlement_mode']?.map(item => ({
					text: item.dictValue,
					value: item.dictCode
				})) || []
				this.provenanceList = this.dict?.['purchase_origin']?.map(item => ({
					text: item.dictValue,
					value: item.dictCode
				})) || []

				this.guaranteeUnitList = this.dict?.['date_unit']?.map(item => ({
					text: item.dictValue,
					value: item.dictCode
				})) || []

        this.setDeliveryDays()
			}
		},
		methods: {
			// 改变数量/单价 → 重算金额
			changeCount(supplier, sIndex, pIndex) {
        console.log(supplier, sIndex, pIndex)
				const item = supplier.resultList[pIndex]
				if (!item) return
				// 包装单位换算
				const changed = productChangeCount(item, {
					countKey: 'purchaseCount',
					unitKey: 'purchaseUnit',
					unitIdKey: 'purchaseUnitId'
				})
				this.$set(supplier.resultList, pIndex, changed)
				// 计算金额
				this.calcItemTotal(supplier, pIndex)
				// 更新总价
				this.calcSupplierTotal(supplier)
			},
			// 单项金额 = 数量 * 单价
			calcItemTotal(supplier, pIndex) {
        console.log('calcItemTotal', supplier, pIndex)
				const item = supplier.resultList[pIndex]
				if (item.singlePrice && item.purchaseCount) {
					item.totalPrice = +(item.singlePrice * item.purchaseCount).toFixed(2)
				}
				// 不含税单价（税率在报价明细中，每个产品独立）
				if (item.singlePrice && item.taxRate) {
					item.notaxSinglePrice = +(item.singlePrice / (1 + item.taxRate / 100)).toFixed(2)
				}
			},
			// 供应商总价 = 所有报价项金额之和
			calcSupplierTotal(supplier) {
				let total = 0
				supplier.resultList.forEach(item => {
					total += item.totalPrice || 0
				})
				supplier.totalPrice = +total.toFixed(2)
        supplier.preferentialPrice = supplier.totalPrice
			},
			onSettlementChange(supplier) {
				const found = this.settlementModeList.find(i => i.value === supplier.settlementMode)
				if (found) supplier.settlementModeName = found.text
			},
			onDeliveryDateChange(supplier) {
				supplier.resultList.forEach((item, index) => {
					if (supplier.deliveryDate && item.expectReceiveDate) {
						const deliver = new Date(supplier.deliveryDate).getTime()
						const expect = new Date(item.expectReceiveDate).getTime()
						if (deliver > expect) {
							uni.showToast({ title: '交货日期大于到货日期', icon: 'none' })
						}
					}
				})
			},
			onSupplierFilesChange(sIndex, val) {
				const supplier = this.supplierList[sIndex]
				if (supplier) this.$set(supplier, 'files', val)
			},
			getProvenanceLabel(val) {
				if (!val || !val.length) return ''
				return val.map(v => {
					const found = this.provenanceList.find(p => p.value == v)
					return found ? found.text : v
				}).join(', ')
			},
			getGuaranteeUnitLabel(val) {
				const found = this.guaranteeUnitList.find(g => g.value == val)
				return found ? found.text : val || ''
			},
			onGuaranteeUnitChange(item) {
				const found = this.guaranteeUnitList.find(g => g.value == item.guaranteePeriodUnitCode)
				if (found) item.guaranteePeriodUnitName = found.text
			},
			openProvenancePicker(sIndex, pIndex) {
				this.curProvenanceSIndex = sIndex
				this.curProvenancePIndex = pIndex
				this.$refs.provenancePicker._show()
			},
			provenanceConfirm(data, name, allList) {
				if (this.curProvenanceSIndex === -1 || this.curProvenancePIndex === -1) return
				const supplier = this.supplierList[this.curProvenanceSIndex]
				const item = supplier?.resultList[this.curProvenancePIndex]
				if (!item) return
				const selectedValues = (allList || []).map(s => s.id)
        console.log(selectedValues, allList)
				this.$set(item, 'provenance', selectedValues)
				this.curProvenanceSIndex = -1
				this.curProvenancePIndex = -1
			},
			delProduct(sIndex, pIndex) {
				const supplier = this.supplierList[sIndex]
				if (!supplier) return
				supplier.resultList.splice(pIndex, 1)
			},
			// 获取表格数据（供父组件保存时调用）
			getTableValue() {
				return this.supplierList
			},
      setDeliveryDays() {
        this.supplierList.forEach(supplier => {
          supplier.resultList.forEach((item, index) => {
          let day =
            supplier.deliveryDate &&
            (new Date(supplier.deliveryDate).getTime() -
              new Date().getTime()) /
              1000 /
              60 /
              60 /
              24;

          this.$set(
            supplier.resultList[index],
            'deliveryDays',
            Math.ceil(day) || 1
          );
        });
        })
        this.$forceUpdate();
      },
		}
	}
</script>

<style lang="scss" scoped>
	.mainBox {
		background: #fff;
		margin-bottom: 10rpx;
	}

	.supplier-header {
		padding: 20rpx 30rpx;
		background: #f8fdf8;
		border-bottom: 2rpx solid #e5e5e5;

		.supplier-name {
			font-size: 30rpx;
			font-weight: 600;
			color: #333;
			margin-bottom: 12rpx;

			.label {
				color: #999;
				font-weight: 400;
			}

			.value {
				color: #157A2C;
				font-weight: 600;
			}
		}

		.supplier-summary {
			display: flex;
			flex-wrap: wrap;
			align-items: center;

			.summary-item {
				margin-right: 30rpx;
				margin-bottom: 6rpx;
				display: flex;
				align-items: center;

				.label {
					font-size: 24rpx;
					color: #999;
				}

				.value {
					font-size: 24rpx;
					color: #333;

					&.price {
						color: #E6A23C;
						font-weight: 600;
					}
				}
			}
		}
	}

	.price-tag {
		color: #E6A23C;
		font-weight: 600;
	}

	/deep/.u-input {
		padding: 0 !important;
		height: 44rpx !important;
		font-size: 26rpx !important;
	}

	/deep/.uni-date-editor--x .uni-date__icon-clear {
		border: none !important;
	}

	/deep/.uni-date__x-input,
	/deep/.uni-date-x {
		padding: 0 !important;
		height: 44rpx !important;
		font-size: 26rpx !important;
	}
</style>
