<template>
	<view>
		<view class="cu-modal" :class="show?'show':''">
			<view class="cu-dialog" style="margin-top: 180rpx;vertical-align: initial;">
				<view class="cu-bar bg-white justify-end solid-bottom">
					<view class="content">申请订单加价/预付款</view>
					<view class="action" data-modal="applyExtraChargeModal" @click="hideModal">
						<text class="cuIcon-close text-red"></text>
					</view>
				</view>
				<view class="bg-white padding text-left">
					<view class="text-lg padding-top flex justify-start align-center">
						<text class="title-input">加价金额：</text>
						<input type="digit" class="radius-input inline-input" placeholder="请输入加价总金额" v-model="moneyAmount"></input>
					</view>
					<view class="text-lg padding-top flex justify-start align-center">
						<text class="title-input">加价原因：</text>
						<picker style="width: 75%;" @change="bindPickerChange" :value="chooseIndex" :range="array">
							<view class="flex justify-between align-center radius-input inline-input custom-input">
								<view>{{array[chooseIndex]}}</view>
								<text class="cuIcon-right"></text>
							</view>
						</picker>
					</view>
					<view class="text-lg padding-top flex justify-start align-center" v-if="array[chooseIndex].indexOf('含') > -1">
						<text class="title-input">{{array[chooseIndex].split('含')[1]}}：</text>
						<input type="digit" class="radius-input inline-input" placeholder="请输入该费用实际金额" v-model="extraAmount"></input>
					</view>
					<view>
						<view class="padding-tb-sm">凭证上传</view>
						<view class="grid col-3 grid-square">
							<view class="bg-img" v-for="(item,index) in imgList" :key="index"
								@tap="viewImage($event, imgList)" :data-url="item">
								<image :src="item" mode="aspectFill"></image>
								<view class="cu-tag bg-red" @tap.stop="delImg($event, imgList)" :data-index="index">
									<text class='cuIcon-close'></text>
								</view>
							</view>
							<view class="solids" @tap="chooseImage" v-if="imgList.length < 6">
								<text class='cuIcon-cameraadd'></text>
							</view>
						</view>
					</view>
					<view>
						<view class="padding-tb-sm">申请原因</view>
						<view class="solid">
							<textarea style="width: 100%; height: 150rpx;" fixed="true" class="radius text-left padding-sm"
								v-model="remark" maxlength="-1" :placeholder="`请输入理由或备注`"></textarea>
						</view>
					</view>
					<view style="padding-top: 10px;">
						<view style="font-size: 24rpx;color: #666;white-space: pre-wrap;">
							加价提示\n1、加价所有费用需经系统支付！加价报价以双方约定输入总价。含配件类物料类的全额到你帐户（银行手续费自付）；\n2、申请加价时，客户端仅看到加价总额，总额内的配件类物料类金额与凭证均看不到（网点与商家可见）；
						</view>
					</view>
					<view class="cu-btn line-main-color margin-top-sm long-btn" v-if="hasReacord" @click="clearCurAddedPrice">
						清空加价</view>
				</view>
				<view class="cu-bar bg-white solid-top">
					<view class="action margin-0 flex-sub text-black" data-modal="applyChargeModal"
						@click="hideModal">{{ hasReacord ? '退出/待二次上门' : '取消'}}</view>
					<view class="action margin-0 flex-sub text-main-color solid-left" data-modal="applyChargeModal" v-if="!hasReacord"
						@click="submit">确认</view>
					<view class="action margin-0 flex-sub text-main-color solid-left" data-modal="applyChargeModal" v-else
						@click="makePayQrcode">请客户支付</view>
				</view>
			</view>
		</view>
		
		<pay-qrcode ref="payQrcode" :show="showPayQrcodeModal" :data="data" @finishQrPay="finishQrPay"></pay-qrcode>
	</view>
</template>

<script>
	import payQrcode from '@/pages/order-manage/modal/pay-qrcode.vue';
	export default {
		components: {payQrcode},
		name: 'applyCharge',
		props: {
			show: {
				type: Boolean,
				default: false
			},
			data: {
				type: Object,
				default: () => {}
			}
		},
		data() {
			return {
				// array: ['加单加价','加急费','拆机/拆换费','搬运费','清理费','远程费','施工费','垫付金','奖励金','质保金','客户押金','工具押金','物品押金'],
				array: ['加单加价', '加急费', '加时费', '奖励金', '拆机/换机费', '搬运费', '打孔费', '额外服务费', '检查检测费', '清理费', '运输吊装费', '加价含物料费', '加价含垫付金', '加价含配件费', '加价含好评费', '加价含远程费', '加价含高空费', '加价含质保金', '加价含客户押金', '加价含工具押金', '加价含物品押金'],
				chooseIndex: 0,
				imgList: [],
				moneyAmount: '',
				reason: '1',
				extraAmount: '',
				remark: '',
				hasReacord: false,
				showPayQrcodeModal: false
			}
		},
		methods: {
			async initPriceData() {
				const cur_reacord = await this.resetPriceChangedInfo()
				if(cur_reacord) {
					this.hasReacord = true
					this.init(cur_reacord);
				} else {
					this.hasReacord = false
				}
			},
			init(priceObj) {
				console.log(priceObj);	
				if (!priceObj || priceObj.payStatus == 1) {
					return;
				}
				this.moneyAmount = priceObj.changeMoney + (priceObj.attachmentMoney || 0) 
				this.extraAmount = priceObj.attachmentMoney;
				this.remark = priceObj.remark;
				this.chooseIndex = priceObj.reason ? this.array.findIndex(i => i == priceObj.reason) : 0;
				this.imgList = priceObj.urls ? priceObj.urls.split(',') : []
				this.priceObj = priceObj;
			},
			bindPickerChange(e) {
				this.chooseIndex = parseInt(e.detail.value)
			},
			hideModal(e) {
				this.$emit('close', e);
			},
			chooseImage(e) {
				uni.chooseMedia({
					count: 1, //默认9
					mediaType: ['image'],
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'], //从相册选择
					success: (res) => {
						uni.showLoading({
							title: '上传中',
							mask: true
						});
						res.tempFiles.forEach((fileObj, index) => {
							this.$request.uploadFile(fileObj.tempFilePath).then((url) => {
								this.imgList.push(url);
								if (index === res.tempFiles.length - 1) {
									uni.hideLoading();
								}
							});
						});
					}
				});
			},
			viewImage(e, imgList) {
				uni.previewImage({
					urls: imgList,
					current: e.currentTarget.dataset.url
				});
			},
			delImg(e, imgList) {
				uni.showModal({
					title: '',
					content: '确定要删除这张图片吗？',
					cancelText: '取消',
					confirmText: '确定',
					success: res => {
						if (res.confirm) {
							imgList.splice(e.currentTarget.dataset.index, 1)
						}
					}
				})
			},
			async resetPriceChangedInfo() {
				let res = await this.$request.getChangeOrderPrice(this.data);
				if (res && res.code === 0) {
					return res.data
				}
			},
			resetData() {
				this.chooseIndex = 0
				this.imgList = []
				this.moneyAmount = ''
				this.extraAmount = ''
				this.remark = ''
				this.hasReacord = false
			},
			async submit(e) {
				const res = await this.resetPriceChangedInfo()
				if (res && res.type != 1) {
					uni.showToast({
						icon: 'none',
						title: '你有加价未付款，请客户支付后再加或在原加价上增加金额！',
						duration: 2500
					})
					return;
				}
				
				if (!this.moneyAmount) {
					uni.showToast({
						title: '请输入本次加价总金额',
						icon: 'none'
					});
					return;
				}
				if (this.array[this.chooseIndex].indexOf('含') > -1 && !this.extraAmount) {
					uni.showToast({
						title: '请输入该费用实际金额',
						icon: 'none'
					});
					return;
				}
				if(this.array[this.chooseIndex].indexOf('含') > -1 && this.imgList.length === 0) {
					uni.showToast({
						title: '请上传凭证，至少一张',
						icon: 'none'
					});
					return;
				}
				const num_moneyAmount = parseInt(this.moneyAmount)
				const num_extraAmount = parseInt(this.extraAmount)
				if(this.array[this.chooseIndex].indexOf('含') > -1 && num_extraAmount > num_moneyAmount) {
					uni.showToast({
						title: '费用实际金额不能大于本次加价总金额',
						icon: 'none'
					});
					return;
				}
				if(this.array[this.chooseIndex].indexOf('含') === -1) {
					console.log('调用详情接口',{
						orderDetailId: this.data.orderDetailId,
						attachMoney: this.moneyAmount,
						type: '01'
					});
					// 调用后端接口，添加附加费
					let res = await this.$request.changeOrderPrice({
						orderDetailId: this.data.orderDetailId,
						changeMoney: this.moneyAmount,
						type: 1,
						remark: this.remark,
						urls: this.imgList.toString(),
						reason: this.array[this.chooseIndex]
					});
					if (res.code === 0) {
						uni.showToast({
							title: '操作成功',
							icon: 'success'
						});
						// this.$emit('callAgain')
						this.initPriceData()
					}
				} else {
					// 直接修改配件费
					let type1_price, type2_price;
					type2_price = num_extraAmount
					type1_price = num_moneyAmount - num_extraAmount
					console.log('调用列表接口',{
						orderDetailId: this.data.orderDetailId,
						changeMoney: type1_price,
						type: 1,
						remark: this.remark,
						urls: this.imgList.toString()
					});
					let res2 = await this.$request.changeOrderPrice({
						orderDetailId: this.data.orderDetailId,
						changeMoney: type1_price,
						type: 1,
						remark: this.remark,
						urls: this.imgList.toString(),
						reason: this.array[this.chooseIndex]
					});
					if (res2.code != 0) return
					const newData = await this.resetPriceChangedInfo()
					console.log('调用详情接口',{
						orderDetailId: this.data.orderDetailId,
						attachMoney: type2_price,
						type: '01'
					});
					let res1 = await this.$request.addOrderAttach({
						orderDetailId: this.data.orderDetailId,
						attachMoney: type2_price,
						type: '01',
						financialChangeRecordId: newData.id,
						remark: this.remark,
					});
					if (res1.code != 0) return
					uni.showToast({
						icon: 'success',
						title: '操作成功'
					})
					// this.$emit('callAgain')
					this.initPriceData()
				}
			},
			async makePayQrcode(e) {
				let res = await this.$request.priceAddedQrPay(this.data);
				if (res && res.code === 0) {
					this.showPayQrcodeModal = true;
					this.$refs.payQrcode.showQrcode(res.data.expend.qrcode_url);
				}
			},
			finishQrPay(e) {
				this.showPayQrcodeModal = false;
				// this.$emit('callAgain')
				this.initPriceData()
			},
			async clearCurAddedPrice() {
				await this.$request.deleteAttachPrice({
					orderDetailId: this.data.orderDetailId
				})
				let res = await this.$request.changeOrderPrice({
					orderDetailId: this.data.orderDetailId,
					changeMoney: 0,
					type: 1,
					remark: '客户清空加价',
					urls: '',
					reason: ''
				});
				if (res && res.code === 0) {
					uni.showToast({
						icon: 'success',
						title: '操作成功'
					})
					// this.$emit('callAgain')
					this.initPriceData()
				}
			}
		}
	}
</script>

<style scoped>
	.grid.col-3.grid-square>view {
		padding-bottom: calc((100% - 40rpx)/3);
		height: 0;
		width: calc((100% - 40rpx)/3);
	}
	
	.inline-input {
		flex-basis: 70%;
	}
	.title-input {
		display: inline-block;
		width: 165rpx;
	}
	.custom-input {
		height: 1.4rem;
		min-height: 1.4rem;
	}
</style>
