<template>
	<view class="mainBox">
		<view v-for="(item, index) in tableList" :key="index" style="position: relative;">
			<myCard :item="item" :btnList="btnList" :index="index+1" :columns="columns" @del="del(index)">
				<u--input slot="totalCount" @input="changeCount(item,index)" type="number" placeholder="请输入"
					border="surround" :disabled="!!contractId" v-model="item.totalCount">
				</u--input>
				<u--input :disabled="!!contractId" slot="singleWeight" @input="singleWeightChange(item,index)"
					type="number" placeholder="请输入" border="surround" v-model="item.singleWeight"></u--input>
				<u--input :disabled="!!contractId" slot="singlePrice" style="flex:none;width: 50%;"
					@input="getTotalPrice()" type="number" placeholder="请输入" border="surround"
					v-model="item.singlePrice">
					<template slot="suffix">元</template>
				</u--input>
				<uni-datetime-picker :disabled="!!contractId" type="date" slot="customerExpectDeliveryDeadline"
					v-model="item.customerExpectDeliveryDeadline">
				</uni-datetime-picker>
				<u--input :disabled="!!contractId" slot="guaranteePeriod" placeholder="请输入" border="surround"
					v-model="item.guaranteePeriod"></u--input>
				<uni-data-picker :readonly="!!contractId" slot="guaranteePeriodUnitCode"
					v-model="item.guaranteePeriodUnitCode" placeholder="请选择" :localdata="date_unit">
				</uni-data-picker>
				<u--input slot="customerMark" placeholder="请输入" border="surround" v-model="item.customerMark">

				</u--input>
				<u--input slot="productBrand" placeholder="请输入" border="surround" :disabled="item.productCode"
					v-model="item.productBrand">
				</u--input>
				<u--input slot="specification" placeholder="请输入" border="surround" :disabled="item.productCode"
					v-model="item.specification">

				</u--input>
				<u--input slot="measuringUnit" placeholder="请输入" border="surround" :disabled="item.productCode"
					v-model="item.measuringUnit">
				</u--input>
				<u--input slot="modelType" placeholder="请输入" border="surround" :disabled="item.productCode"
					v-model="item.modelType">
				</u--input>

				<u--input slot="productName" placeholder="请输入" border="surround" :disabled="item.productCode"
					v-model="item.productName">
				</u--input>
			</myCard>


		</view>

		<view style="height: 84rpx;" v-if="isDrawer"></view>
		<view class="footerButton" v-if="isDrawer">
			<u-button type="primary" @click="save" text="保存"></u-button>
		</view>
		<view class="add" @click="add" v-if="!contractId">
			<u-icon name="plus" color="#fff"></u-icon>
		</view>
		<u-action-sheet :actions="addList" :show="show" :closeOnClickOverlay="true" :closeOnClickAction="true"
			@close="show=false" @select='select'> </u-action-sheet>
	</view>
</template>

<script>
	import {
		getByCode
	} from '@/api/pda/common.js'
	import myCard from './myCard.vue'
	export default {

		data() {
			return {
				tableList: [],
				addList: [{
						name: '选择物品清单',

					},
					{
						name: '新增临时产品',
					}
				],
				show: false,
				current: {},
				date_unit: [],
				allPrice: '',
				btnList: [{
					name: '删除',
					apiName: 'del',
					btnType: 'error ',
					type: '2',
					pageUrl: '',

				}],
				defaultForm: {
					key: null,
					endTime: '',
					isFirst: 0,
					name: '',
					startTime: '',
					workHour: '',
					guaranteePeriodUnitCode: '',
					technicalDrawings: [],
					arrivalWay: 1
				}

			}
		},
		props: {
			isDrawer: {
				default: false
			},
			pricingWay: {
				default: 1
			},
			isTemporary: {
				//临时
				type: Boolean,
				default: false
			},
			contractId: '',
			columns: {
				type: Array,
				default: () => [
					[{
						label: '产品名称：',
						prop: 'productName',
						slot: 'productName',
						type: 'title',
						className: 'perce100',
					}],
					[{
						label: '编码：',
						prop: 'productCode'
					}, {
						label: '牌号：',
						prop: 'productBrand',
						slot: 'productBrand',
					}],
					[{
						label: '规格：',
						prop: 'specification',
						slot: 'specification',
					}, {
						label: '型号：',
						prop: 'modelType',
						slot: 'modelType',
					}],
					[{
						label: '数量：',
						prop: 'totalCount',
						slot: 'totalCount',
					}, {
						label: '计量单位：',
						prop: 'measuringUnit',
						slot: 'measuringUnit',
					}],

					[{
						label: '单重：',
						prop: 'singleWeight',
						slot: 'singleWeight',
					}, {
						label: '总重：',
						prop: 'totalWeight',
					}],
					[{
						label: '单价：',
						prop: 'singlePrice',
						slot: 'singlePrice',
					}, {
						label: '合计：',
						prop: 'totalPrice',
						formatter: (item) => {
							return (item.totalPrice || '') + '元'
						}
					}],
					[{
						label: '客户期望交期：',
						prop: 'customerExpectDeliveryDeadline',
						slot: 'customerExpectDeliveryDeadline',
						className: 'perce100',
					}],
					[{
						label: '质保期：',
						prop: 'guaranteePeriod',
						slot: 'guaranteePeriod',
					}, {
						label: '单位：',
						prop: 'guaranteePeriodUnitCode',
						slot: 'guaranteePeriodUnitCode',
					}],
					[{
						label: '操作：',
						prop: 'action',
						type: 'action',
						className: 'perce100',
					}],

				]
			}
		},
		components: {
			myCard
		},
		created() {
			uni.$off('setProduceList')
			uni.$on('setProduceList', (data) => {
				data.forEach(item => {
					item['productId'] = item.id
					item['categoryName'] = item.name
					item['productCategoryId'] = item.categoryLevelId
					item['productBrand'] = item.brandNum
					item['productCategoryName'] = item.categoryLevelPath
					item['productCode'] = item.code
					item['productName'] = item.name
					item['approvalNumber'] = item.extField.approvalNumber
					item['packingSpecification'] = item.extField.packingSpecification
					item['packageDispositionList'] = item.packageDispositionList

					if (item.packageDispositionList?.length) {
						item['saleUnitId'] = item.packageDispositionList[0].id
						item['saleUnit'] = item.packageDispositionList[0].conversionUnit

					}
				})
				this.tableList.push(...data)
			})

			this.getByCode()
		},

		watch: {
			contractId(val) {
				if (val) {
					this.btnList = []
				}

			}
		},
		methods: {
			add() {
				if (this.isTemporary) {
					this.show = true
				} else {
					uni.navigateTo({
						url: '/pages/saleManage/components/selectProduce?isAll=' + 1
					})
				}


			},
			select({
				name
			}) {
				if (name == '选择物品清单') {
					uni.navigateTo({
						url: '/pages/saleManage/components/selectProduce?isAll=' + 1
					})
				} else {
					this.handlAdd()
				}



			},
			// 添加
			handlAdd() {
				let item = JSON.parse(JSON.stringify(this.defaultForm));
				item.key = this.tableList.length + 1;
				this.tableList.push(item);
			},
			init(list) {
				if (list) {
					this.tableList = JSON.parse(JSON.stringify(list))
					this.getTotalPrice(list)

				}
			},
			getValue() {
				return this.tableList
			},

			del(index) {

				this.tableList.splice(index, 1);

			},
			getByCode() {
				const codeS = ['date_unit']
				codeS.forEach(async (code) => {
					const codeValue = await getByCode(code);
					this[code] = codeValue.map(item => {
						const key = Object.keys(item)[0]
						return {
							value: key,
							text: item[key]
						}
					})
				})

			},
			save() {
				uni.$emit('setBusinessOpportunity')
			},
			//改变数量
			changeCount(row, index) {
				this.singleWeightChange(row, index);
				this.getTotalPrice();
			},
			//计算总金额
			getTotalPrice(row) {
				if (this.tableList.length) {
					let sum = 0;
					sum = this.getNumTotalPrice();
					let allsum = sum.toFixed(2);
					this.allPrice = allsum;
					if (!row) {
						uni.$emit('allsum', allsum)
					}
					return allsum;
				} else {
					this.allPrice = 0.0;
					if (!row) {
						uni.$emit('allsum', allsum)
					}
					return 0.0;
				}
				//回显总金额
			},
			//计算总金额
			getNumTotalPrice(sum = 0) {
				this.tableList.forEach((r, index) => {
					this.$set(
						r,
						'discountSinglePrice',
						r.singlePrice ? Number(r.singlePrice) : ''
					);
					if (r.singlePrice && r.totalCount) {
						r.totalPrice = this.getAllPrice(r);
						r.discountTotalPrice = this.getDiscountTotalPrice(r);
						this.$set(this.tableList[index], 'totalPrice', Number(r.totalPrice));
						this.$set(
							this.tableList[index],
							'discountTotalPrice',
							Number(r.discountTotalPrice)
						);
						sum += Number(r.totalPrice);
					} else {
						this.$set(r, 'totalPrice', '');
						this.$set(r, 'discountTotalPrice', '');
					}
				});
				return isNaN(sum) ? 0 : sum;
			},
			//计算单重
			singleWeightChange(row, index) {


				if (row.weightUnit == row.measuringUnit) {
					this.$set(this.tableList[index], 'totalWeight', row.totalCount);
				} else if (row.totalCount && row.singleWeight) {
					this.$set(this.tableList[index], 'totalWeight', (row.singleWeight * row.totalCount).toFixed(2) || 0);
				} else {
					this.$set(this.tableList[index], 'totalWeight', 0);
				}


			},
			//获取合计
			getAllPrice(row) {
				let num = Number(row.singlePrice) * Number(row.totalCount);



				return isNaN(num) ? '' : num.toFixed(2);

			},
			//设置优惠后总金额修改产品单价
			discountInputByOrder(val) {

				//获取优惠金额和总计的差价
				this.tableList.forEach((item) => {
					if (val === 0) {
						item.discountTotalPrice = 0;
						item.discountSinglePrice = 0;
						return;
					}
					if (!val) {
						item.discountTotalPrice = item.totalPrice;
						item.discountSinglePrice = item.singlePrice;
						return;
					}
					//获取折让单价
					item.discountSinglePrice = this.getDiscountSinglePrice(item, val);
					item.discountTotalPrice = this.getDiscountTotalPrice(item, val);
				});
				this.$forceUpdate()

			},
			//获取折让单价
			getDiscountSinglePrice(row, val) {
				let num =
					(Number(val) / Number(this.allPrice)) *
					Number(row.singlePrice);
				return isNaN(num) ? '' : num;
			},
			//获取折让合计
			getDiscountTotalPrice(row, val) {
				let num = Number(row.discountSinglePrice) * Number(row.totalCount);


				return isNaN(num) ? '' : num.toFixed(2);
			},
			//设置客户代号
			setCustomerMark(val) {
				this.tableList.forEach((item, index) => {
					this.$set(this.tableList[index], 'customerMark', val)
				})
			},


		}
	}
</script>

<style lang="scss" scoped>
	.add {
		width: 96rpx;
		height: 96rpx;
		border-radius: 48rpx;
		background: #3c9cff;
		position: fixed;
		bottom: 100rpx;
		right: 24rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 99;
	}

	.footerButton {
		width: 100%;
		height: 84rpx;
		display: flex;
		position: fixed;
		bottom: 0;
		z-index: 10;

		/deep/.u-button {
			height: 100%;
		}

		>view {
			flex: 1;

		}
	}


	/deep/.u-swipe-action-item__right__button__wrapper {
		background-color: #f56c6c !important;
	}
</style>