<template>
	<view class="mainBox">
		<view v-for="(item, index) in tableList" :key="index" style="position: relative;">
			<myCard :item="item" :btnList="btnList" :index="index+1" :isDrawer="isDrawer" :columns="columns" @del="del(index)">
				<view class="slot-box" slot="productName">
					<u-row>
						<u-col span="10">
							<u--input placeholder="请输入" border="surround" disabled v-model="item.productName"></u--input>
						</u-col>
						<u-col span="2">
							<u-button v-if="!isDrawer" type="primary" size="mini" @click="selectProduct(item, index)" text="选择"></u-button>
						</u-col>
					</u-row>
				</view>

				<view slot="purchaseCount">
					<view v-if="isDrawer">
						{{ item.purchaseCount + ' ' + (item.purchaseUnit || '') }}
					</view>
					<view v-else>
						<u-row>
							<u-col span="6">
								<u--input placeholder="请输入" type="number" border="surround" v-model="item.purchaseCount"  @input="changeCount(item, index)"></u--input>
							</u-col>
							<u-col span="6">
								<uni-data-picker v-model="item.purchaseUnitId" placeholder="请选择" :localdata="item.packageDispositionList" @change="changeCount(item, index)"></uni-data-picker>
							</u-col>
						</u-row>
					</view>
				</view>

				<view slot="goodsLevel">
					<view v-if="isDrawer">
						{{ getGoodsLevelVal(item.goodsLevel) }}
					</view>
					<view v-else>
						<uni-data-picker v-model="item.goodsLevel" placeholder="请选择" :localdata="levelList"></uni-data-picker>
					</view>
				</view>

				<view slot="arrivalWay">
					<view v-if="isDrawer">{{ item.arrivalWay == 1 ? '一次性到货' : '分批到货' }}</view>
					<view v-else>
						<uni-data-picker v-model="item.arrivalWay" placeholder="请选择" :localdata="arrivalWayList"></uni-data-picker>
					</view>
				</view>

				<view slot="expectReceiveDate">
					<view v-if="isDrawer">
						<view v-if="item.arrivalWay == 2" style="color: #409eff;" @click="settingDate(item, index)">分批时间</view>
						<view v-else>{{ item.expectReceiveDate }}</view>
					</view>
					<view v-else>
						<view v-if="item.arrivalWay == 2">
							<span @click="settingDate(item, index)" style="color: #409eff;">设置分批时间</span>
						</view>
						<view v-else>
							<uni-datetime-picker type="date" v-model="item.expectReceiveDate"></uni-datetime-picker>
						</view>
					</view>
				</view>

				<view slot="taskName">
					<view v-if="isDrawer">{{ item.taskName }}</view>
					<view v-else>
						<u-row>
							<u-col span="10">
								<u--input placeholder="" disabled border="surround" v-model="item.taskName"></u--input>
							</u-col>
							<u-col span="2">
								<u-button type="primary" size="mini" @click="selectTaskName(item, index)" text="选择"></u-button>
							</u-col>
						</u-row>
					</view>
				</view>

				<view slot="supplierName">
					<view v-if="isDrawer">{{ item.supplierName }}</view>
					<view v-else>
						<uni-data-picker v-model="item.supplierId" placeholder="请选择" :localdata="item.supplierList"></uni-data-picker>
					</view>
				</view>

				<view slot="provenance">
					<view v-if="isDrawer">{{ getProvenance(item.provenance) }}</view>
					<view v-else>
						<!-- <uni-data-picker v-model="item.provenance" placeholder="请选择" :localdata="purchase_origin"></uni-data-picker> -->
						 <u--input placeholder="请输入" border="surround" v-model="item.provenanceName" @click.native="changeMultiple(item, index, 'provenance', purchase_origin)"></u--input>
					</view>
				</view>

				<view slot="brand">
					<view v-if="isDrawer">{{ item.brand }}</view>
					<view v-else>
						<u--input placeholder="请输入" border="surround" disabled v-model="item.productName"></u--input>
					</view>
				</view>

				<view slot="modelKey">
					<view v-if="isDrawer">{{ item.modelKey }}</view>
					<view v-else>
						<u--input placeholder="请输入" border="surround" v-model="item.modelKey" @click.native="changeMultiple(item, index, 'modelKey', product_model_key)"></u--input>
					</view>
				</view>

				<view slot="colorKey">
					<view v-if="isDrawer">{{ item.colorKey }}</view>
					<view v-else>
						<u--input placeholder="请输入" border="surround" v-model="item.colorKey" @click.native="changeMultiple(item, index, 'colorKey', product_color_key)"></u--input>
					</view>
				</view>

				<view slot="remark">
					<view v-if="isDrawer">{{ item.remark }}</view>
					<view v-else>
						<u--input placeholder="请输入" border="surround" v-model="item.remark"></u--input>
					</view>
				</view>

				<view slot="technicalDrawings" style="display: flex;">
					<fileMain :type="isDrawer ? 'view' : ''" v-model="item.technicalDrawings"></fileMain>
				</view>
				<view slot="files" style="display: flex;">
					<fileMain :type="isDrawer ? 'view' : ''" v-model="item.files"></fileMain>
				</view>
			</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="!isDrawer">
			<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>
		<timePopup ref="timePopupRef" 
			:isView="isDrawer"
		@confirm="handleTimeConfirm"></timePopup>
		<multipleSelect ref="multipleSelectRef" :range="multipleSelectRange" @confirm="handleMultipleConfirm"></multipleSelect>
	</view>
</template>
<!-- 名称，数量，到货方式，到货日期 -->
<script>
	import {
		getByCode
	} from '@/api/pda/common.js'
	import myCard from './myCard.vue'
	import { mapActions, mapGetters } from 'vuex'
	import { levelList, lbjtList } from '@/enum/dict'
	import fileMain from "@/pages/doc/index.vue"
	import { changeCount } from '@/utils/setProduct.js';
	import timePopup from './timePopup.vue'
	import baTreePicker from '@/components/ba-tree-picker/ba-tree-picker.vue'
	import multipleSelect from './multipleSelect.vue'

	export default {
		data() {
			return {
				tableList: [],
				multipleSelectRange: [],
				addList: [
					{ name: '选择物品清单', },
					{ name: '新增临时产品', }
				],
				arrivalWayList: [
					{ text: '一次性到货', value: 1 },
					{ text: '分批到货', value: 2 }
				],
				show: false,
				purchaseUnitShow: false,
				current: {},
				currentIndex: -1,
				date_unit: [],
				product_color_key: [],
				product_model_key: [],
				purchase_origin: [],
				allPrice: '',
				btnList: [{
					name: '删除',
					apiName: 'del',
					btnType: 'error ',
					type: '2',
					pageUrl: '',
					judge: [{
						authorities: '',
					}, {
						// key: 'status',
						// value: [0, 3],
						fn: (row) => {
								return !this.isDrawer
							},
					}],
				}],
				defaultForm: {
					key: null,
					endTime: '',
					isFirst: 0,
					name: '',
					startTime: '',
					workHour: '',
					guaranteePeriodUnitCode: '',
					technicalDrawings: [],
					files: [],
					arrivalWay: 1,
					modelKey: '',
					colorKey: ''
				},
				levelList
			}
		},
		props: {
			isDrawer: {
				default: false
			},
			pricingWay: {
				default: 1
			},
			isTemporary: {
				//临时
				type: Boolean,
				default: false
			},
			contractId: '',
		},
		components: {
			myCard,
			fileMain,
			timePopup,
			baTreePicker,
			multipleSelect
		},
		computed: {
			...mapGetters(['dict', 'getDict', 'getDictValue']),
			columns() {
				return [
					[{
						label: '名称：',
						prop: 'productName',
						slot: 'productName',
						type: 'title',
						className: 'perce100',
						isRequired: true,
					}],
					[{
						label: '编码：',
						prop: 'productCode'
					}, {
						label: '分类：',
						prop: 'productCategoryName',
					}],
					[{
						label: '数量：',
						prop: 'purchaseCount',
						slot: 'purchaseCount',
						className: 'perce100',
						isRequired: true,
						// formatter: (item) => {
						// 	if (item.purchaseCount) {
						// 		return item.purchaseCount + ' ' + (item.purchaseUnit || '');
						// 	}
						// }
					}],
					[
						{
							label: '计量数量：',
							prop: 'totalCount',
							formatter: (item) => {
								if (item.totalCount) {
									return item.totalCount + ' ' + (item.measuringUnit || '');
								}
							}
						},
						{
							label: '包装规格：',
							prop: 'packingSpecification',
						}
					],
					[{
						label: '物品级别：',
						prop: 'goodsLevel',
						slot: 'goodsLevel',
						// formatter: (item) => {
						// return levelList.find((i) => i.value == item.goodsLevel)
						// 	?.label;
						// },
					},
					{
						label: '库存数量：',
						prop: 'availableCountBase',
					}],
					[{
						label: '已采数量：',
						prop: 'doneTotalCount',
						formatter: (item) => {
							if (item.doneTotalCount) {
								return item.doneTotalCount + ' ' + (item.measuringUnit || '');
							}
						}
					}, {
						label: '待采数量：',
						prop: 'waitTotalCount',
						formatter: (item) => {
							if (item.waitTotalCount) {
								return item.waitTotalCount + ' ' + (item.measuringUnit || '');
							}
						}
					}],
					[{
						label: '工序：',
						prop: 'taskName',
						slot: 'taskName',
						className: 'perce100',
					}], 
					[{
						label: '批次号：',
						prop: 'batchNo',
					}],
					[{
						label: '供应商：',
						prop: 'supplierName',
						slot: 'supplierName'
					}, {
						label: '产地：',
						prop: 'provenance',
						slot: 'provenance',
						// formatter: (item) => {
						// 	// return item.provenance
						// 	return item.provenance && item.provenance.length
						// 		? item.provenance
						// 			.map((item) => this.getDictValue('产地', item))
						// 			.join(',')
						// 		: '';
						// }
					}],
					[{
						label: '型号：',
						prop: 'modelType',
						className: 'perce100',
					}],
					[{
						label: '规格：',
						prop: 'specification',
					}, {
						label: '品牌：',
						prop: 'brand',
						slot: 'brand'
					}],
					[{
						label: '机型：',
						prop: 'modelKey',
						slot: 'modelKey'
					}, {
						label: '颜色：',
						prop: 'colorKey',
						slot: 'colorKey'
					}],
					[{
						label: '到货方式：',
						prop: 'arrivalWay',
						slot: 'arrivalWay',
						isRequired: true,
						// formatter: (item) => {
						// 	return item.arrivalWay == 1 ? '一次性到货' : '分批到货';
						// },
					}],
					[{
						label: '到货日期：',
						prop: 'expectReceiveDate',
						slot: 'expectReceiveDate',
						isRequired: true,
					}, {
						label: '属性类型：',
						prop: 'produceType',
						formatter: (item) => {
							if (item.produceType) {
								return item.produceType
								.map((i) => {
									return lbjtList[i];
								})
								.toString();
							}
						}
					}],
					[{
						label: '图纸附件：',
						prop: 'technicalDrawings',
						slot: 'technicalDrawings',
					}, {
						label: '附件：',
						prop: 'files',
						slot: 'files',
					}],
					[{
						label: '备注：',
						prop: 'remark',
						slot: 'remark',
						className: 'perce100',
					}],
					[{
						label: '操作：',
						prop: 'action',
						type: 'action',
						className: 'perce100',
					}],

				]
			},
		},
		created() {
			this.getByCode()
			// this.requestDict('产地')
			uni.$off('setProduceList')
			uni.$on('setProduceList', (data) => {
				console.log('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.map(i => {
						return {
							...i,
							text: i.conversionUnit,
							value: i.id
						}
					})

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

					}

				})
				console.log(this.currentIndex, this.current)
				if(this.currentIndex > -1) {
						console.log(111)
						// 使用this.$set更新数组项
						if (data && data.length > 0) {
							this.$set(this.tableList, this.currentIndex, data[0]);
						}
						this.currentIndex = -1;
						this.current = {};
				} else {
					console.log(222)
					this.tableList.push(...data)
				}
				
			})

			uni.$off('setTaskName')
			uni.$on('setTaskName', (data) => {
				console.log('setTaskName~~', data)
				
				console.log(this.currentIndex, this.current)
				if(this.currentIndex > -1) {
						console.log(111)
						// 使用this.$set更新数组项
						if (data && data.length > 0) {
							this.$set(this.tableList[this.currentIndex], 'taskId', data[0].id);
							this.$set(this.tableList[this.currentIndex], 'taskName', data[0].name);
							this.$set(
								this.tableList[this.currentIndex],
								'routingId',
								data[0].produceRoutingId
							);
						}
						
						this.currentIndex = -1;
						this.current = {};
				}
			})

			uni.$off('setPBomList')
			uni.$on('setPBomList', (data, idx = -1) => {
				console.log('setPBomList~~', data)
				data.forEach((item, index) => {
					let i = idx == -1 ? index : idx;
					let row = JSON.parse(JSON.stringify(this.defaultForm));
					row.key = this.tableList.length + 1;
					let parasm = idx == -1 ? row : this.tableList[i];
					this.$set(parasm, 'productId', item.id);
					// this.$set(parasm, 'id', item.id);
					this.$set(parasm, 'categoryName', item.name);
					this.$set(parasm, 'productCategoryId', item.categoryLevelId);
					this.$set(parasm, 'productBrand', item.brandNum);
					this.$set(
						parasm,
						'productCategoryName',
						item.category.categoryLevelPath
					);
					this.$set(parasm, 'totalCount', item.dosage);
					this.$set(parasm, 'productCode', item.code);
					this.$set(parasm, 'productName', item.name);
					this.$set(parasm, 'availableCountBase', item.availableCountBase);
					this.$set(parasm, 'modelType', item.modelType);
					this.$set(parasm, 'weightUnit', item.unit);
					this.$set(parasm, 'measuringUnit', item.unit);
					this.$set(parasm, 'specification', item.specification);
					this.$set(parasm, 'remark', '');
					this.$set(parasm, 'imgCode', item.imgCode);
					this.$set(parasm, 'produceType', item.componentAttribute);
					this.$set(parasm, 'approvalNumber', item.extField?.approvalNumber);
					this.$set(parasm, 'goodsLevel', item.goodsLevel);
					this.$set(parasm, 'supplierList', item.supplierList);
					this.$set(parasm, 'supplierCode', item.supplierCode);
					this.$set(parasm, 'supplierId', item.supplierId);
					this.$set(parasm, 'supplierName', item.supplierName);
					// if (item.modelKey) {
					// 	this.$set(parasm, 'modelKey', item.modelKey.split(','));
					// }
					// if (item.colorKey) {
					// 	this.$set(parasm, 'colorKey', item.colorKey.split(','));
					// }
					this.$set(
						parasm,
						'packageDispositionList',
						item.packageDispositionList?.map(i => {
							return {
								...i,
								text: i.conversionUnit,
								value: i.id
							}
						}) || []
					);
					if (item.packageDispositionList?.length) {
						this.$set(
						parasm,
						'purchaseUnitId',
						item.packageDispositionList[0].id
						);
						this.$set(
						parasm,
						'purchaseUnit',
						item.packageDispositionList[0].conversionUnit
						);
					}
					this.$set(
						parasm,
						'packingSpecification',
						item.extField?.packingSpecification
					);
					this.$set(parasm, 'provenance', item.purchaseOrigins || '');
					this.$set(parasm, 'provenanceName', this.getProvenance(item.provenance));

					if (idx == -1) {
						this.tableList.push(row);
					}
				});
			})
		},
		onUnload() {
			uni.$off('setProduceList')
			uni.$off('setTaskName')
			uni.$off('setPBomList')
		},
		watch: {
			contractId(val) {
				if (val) {
					this.btnList = []
				}
			}
		},
		methods: {
			...mapActions('dict', ['requestDict']),
			openPicker() {
				this.$refs.treePicker._show()
			},
			getGoodsLevelVal(val) {
				const goodsLevel = this.levelList.find(item => item.value == val)
				return goodsLevel?.text || ''
			},
			getProvenance(item) {
				console.log('getProvenance~~~~~', item)
				// try {
					// 检查item和provenance是否存在
					if (!item) {
						return '';
					}

					let arr = item;

					if(!Array.isArray(arr)) {
						console.log('arr is not array, convert to array')
						arr = arr.split(',');
					}

				    return arr && arr.length ? arr.map((i) => {
						return this.purchase_origin.find(p => p.value == i)?.text
					}).join(',') : '';
			},
			changeMultiple(item, index, key, range) {
				console.log(item, index)
				this.current = item;
				this.currentIndex = index;
				this.multipleSelectRange = range
				this.$refs.multipleSelectRef.open(item, index, key)
			},
			handleMultipleConfirm(data, key) {
				this.$set(this.tableList[this.currentIndex], key, data)
				if(key == 'provenance'){
					this.$set(this.tableList[this.currentIndex], 'provenanceName', this.getProvenance(data))
				}
			},
			change(e){
				console.log('e:',e);
			},
			settingDate(item, index) {
				console.log(item, index)
				this.current = item;
				this.currentIndex = index;
				this.$refs.timePopupRef.open(item, index)
			},
			handleTimeConfirm(data) {
				this.$set(this.tableList[this.currentIndex], 'arrivalBatch', data)
			},
			add() {
				this.currentIndex = -1;
				this.current = {};
				this.c
				if (this.isTemporary) {
					this.show = true
				} else {
					uni.navigateTo({
						url: '/pages/purchasingManage/components/selectProduce?isAll=' + 1
					})
				}
			},
			select({
				name
			}) {
				if (name == '选择物品清单') {
					uni.navigateTo({
						url: '/pages/purchasingManage/components/selectProduce?isAll=' + 1
					})
				} else {
					this.handlAdd()
				}
			},
			selectProduct(item, index) {
				this.current = item;
				this.currentIndex = index;
				uni.navigateTo({
					url: '/pages/purchasingManage/components/selectProduce?isAll=' + 2
				})
			},
			selectTaskName(item, index) {
				console.log(item, index)
				this.current = item;
				this.currentIndex = index;
				uni.navigateTo({
					url: '/pages/purchasingManage/components/selectTaskName?isAll=' + 2
				})
			},
			// 添加
			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 = ['product_model_key', 'product_color_key', 'purchase_origin']
				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]
						}
					})
					console.log(code, this[code])
				})
				console.log('1111~~~~~~~~~', this.purchase_origin)
			},
			save() {
				uni.$emit('setBusinessOpportunity')
			},
			//改变数量
			changeCount(row, index) {
				// this.singleWeightChange(row, index);
				// this.getTotalPrice();
				this.$set(
					this.tableList,
					index,
					changeCount(row, {
						countKey: 'purchaseCount',
						unitKey: 'purchaseUnit',
						unitIdKey: 'purchaseUnitId'
					})
				);
				this.$forceUpdate();
			},
			//计算总金额
			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;
	}

	.slot-box {
		display: flex;
	}

	.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>