<template>
	<view class="app-wrap">
		<w-navbar title="物料申请" navbar-color="#FFFFFF" />
		<view class="content">
			<view class="card parts">
				<view class="title" v-if="isEmptyParts">物料信息</view>
				<view class="u-flex u-row-between title" v-else>
					<view>选择物料</view>
					<u-icon name="arrow-right" size="24" color="#2272FF" 
						@click="$u.throttle(addParts, 500)" label="添加物料" 
						label-pos="left" label-color="#2272FF" label-size="26"/>
				</view>
				<view class="body">
					<view v-if="isEmptyParts" class="u-flex-col u-col-center list">
						<view class="sold-out">
							<u-image :src="qnFile('SoldOut.png')" width="374" mode="widthFix">
								<view slot="error" style="font-size: 24rpx;">加载失败</view>
							</u-image>
						</view>
						<view class="message">当前还未选择物料，请点击添加，添加后在'我的->物料订单'查看</view>
						<button class="add-button" plain="true" @click="$u.throttle(addParts, 500)">去添加</button>
					</view>
					<view v-else class="list">
						<view v-for="(row, index) in parts" :key="index">
							<select-parts
							  :info="row"
							  :show-checked="false"
							  @change="numChange($event, index)"
								@minusValue="minusValue($event, index)"
							></select-parts>
						</view>
					</view>
					<u-gap height="40"></u-gap>
					<u-input type="textarea" v-model="remark" placeholder="请补充详细说明" class="desc" height="200" :border="true"  />
				</view>
			</view>
			<view class="card address">
				<view class="u-flex u-row-between">	
					<view class="title">收件信息</view>
					<view class="more" @click="toAddress">更多地址></view>
				</view>
				<view class="body">
					<w-address v-if="addressInfo.id" :info="addressInfo" @editSite="editSite" @selectSite="editSite" siteType="view" />
					<view class="u-flex-col u-col-center list" v-if="!addressInfo.id">
						<button class="add-button" plain="true" @click="$u.throttle(toAddSite, 500)">填写地址</button>
					</view>
				</view>
			</view>
		</view>
		<view class="bottom">
			<u-button shape="circle" :disabled="isEmptyParts && $u.test.isEmpty(remark)"
				:hair-line="false" :custom-style="customStyle" 
				hover-class="none" @click="submitParts">提交</u-button>
		</view>
	</view>
</template>

<script>
import SelectParts from '@/components/select-parts/adjust.vue'
export default {
	components: {
		SelectParts
	},
	data() {
		return {
			orderId: 0,
			applyType: 0,
			order: {},
			parts: [],
			disabled: false,
			remark: '',
			curType: 0,
			addressInfo: {
				id: '', name: '', mobile: '', address: '', region: []
			},
		};
	},
	computed: {
		isEmptyParts() {
			return this.$u.test.isEmpty(this.parts)
		},
		customStyle() {
			return {
				height: "104rpx",
				border: "none",
				backgroundColor: "#2272FF",
				color: "#FFFFFF",
				fontSize: "32rpx",
				fontWeight: 600,
			}
		},
		selectedParts() {
			return this.parts.filter((item) => {
				return item.quantity > 0
			})
		}
	},
	onLoad(e) {
		getApp().trackPage('物料申请页')
		this.orderId = e && Number(e.orderId) || 0
		this.applyType = e && Number(e.applyType) || 0
		this.initData()
	},
	onShow() {
		if (!this.addressInfo.id) {
			this.loadAddress()
		}
	},
	methods: {
		initData() {
			this.loadAddress()
			this.loadOrderInfo()
		},
		loadAddress() {
			this.$u.api.getDefaultAddress().then((res) => {
				if(res.code == 200 && res.data) {
					this.addressInfo.id = res.data.id
					this.addressInfo.name = res.data.name
					this.addressInfo.mobile = res.data.mobile
					this.addressInfo.address = res.data.address
					this.addressInfo.region = [
						res.data.provinceName, 
						res.data.cityName, 
						res.data.districtName
					]
				}
			})
		},
		loadOrderInfo() {
			if(this.orderId) {
				this.$u.api.orderDetail({}, this.orderId).then((res) => {
					if (res.code == 200) {
						this.order = res.data
					} else {
						console.log(res.message, "获取订单详情失败！");
					}
				});
			}
		},
		qnFile(src) {
			return process.uniEnv.qn_base_url + src
		},
		editSite() {
			this.$u.route({
				url: "pages/mine/address/addSite",
				params: {
					type: 'select',
					id: this.addressInfo.id,
					name: this.addressInfo.name,
					mobile: this.addressInfo.mobile,
					address: this.addressInfo.address,
					region: this.addressInfo.region.join('-'),
				}
			})
		},
		toAddSite() {
			this.$u.route({
				url: 'pages/mine/address/addSite',
				params: {
					type: 'select'
				}
			})
		},
		toAddress() {
			this.$u.route({
				url: "pages/parts/address"
			})
		},
		updateSite(site) {
			this.addressInfo = site
		},
		addParts() {
			let data = {}
			if(this.$u.test.isEmpty(this.order)) {
				data = {type: 2}
			} else {
				data = {
					type: 1, 
					brandId: this.order.lianbaoBrandId, 
					categaryId: this.order.categoryId
				}
			}
			this.$u.route({
				url: "pages/parts/addParts",
				params: data,
			})
		},
		numChange(val, index) {
		  this.$set(this.parts[index], 'quantity', val)
		},
		minusValue(val, index) {
			if (val === 0) {
        uni.showModal({
          title: '温馨提示',
          content: '确定要删除该物料？',
          success: (res) => {
            if (res.confirm) {
              this.parts.splice(index, 1)
            } else if (res.cancel) {
							this.$set(this.parts[index], 'quantity', 1)
            }
          },
        })
      } 
		},
		updateParts(parts) {
			// if(this.$u.test.isEmpty(parts)) {
			// 	this.parts = []
			// } else {
			// 	this.parts = parts
			// }
			if(!this.$u.test.isEmpty(parts)) {
				for(var val of parts) {
					var has = false
					for(var item of this.parts) {
						if (item.part_id == val.part_id) {
							has = true
							item.quantity += val.quantity
							break
						}
					}
					if (!has) {
						this.parts.push(val)
					}
				}
			}
		},
		validateForm() {
			if(this.applyType == 0 && this.$u.test.isEmpty(this.orderId)) {
				this.$u.toast('保内申请时必须指定工单ID')
				return false
			}
			if(this.applyType != 0 && this.$u.test.isEmpty(this.applyType)) {
				this.$u.toast('申请类型不能为空')
				return false
			}
			if(this.isEmptyParts && this.$u.test.isEmpty(this.remark)) {
				this.$u.toast('配件明细和备注不能同时为空')
				return false
			}
			if (this.$u.test.isEmpty(this.selectedParts)) {
				this.$u.toast('请添加配件数量')
				return false
			}
			return true
		},
		/**
		 * workOrderId 工单ID，保内申请时必须指定
		 * applyType 申请类型：0 保内，1 物料，2 购买，10 使用物料
		 * remark 申请备注
		 * parts 申请的配件明细，JSON 格式，指定多条要申请的配件信息，
		 * 数组中的每个对象需要 part_id（配件ID）和 quantity（申请数量）两个字段。
		 * 如果没有选择明细，请保持空。此时必须填写备注
		 * barcode 产品条码
		 * measures 服务措施
		 * name 收件人姓名
		 * phoneNumber 收件人电话号码
		 * province 收件地址：省
		 * city 收件地址：市
		 * district 收件地址：区
		 * street 收件地址：街道
		 * address 收件详细地址
		 * images 申请图片文件、可以传多张
		 */
		submitParts() {
			if(!this.validateForm()) {
				return false
			}
			getApp().track("parts_application_submitParts", {})
			const address = this.addressInfo
			let params = {
				applyType: '1',
				remark: this.remark,
				parts: JSON.stringify(this.selectedParts),
				name: address.name,
				phoneNumber: address.mobile,
				province: address.region[0],
				city: address.region[1],
				district: address.region[2],
				address: address.address,
				images: null,
			}
			this.$u.api.createParts(params).then((res) => {
				if (res.code == 200 && res.data) {
					this.$u.route({
						type: 'redirect',
						url: "pages/parts/nodes",
					})
				} else {
					console.log(res.message, "配件申请失败！");
				}
			});
		}
	}
};
</script>

<style lang="scss" scoped>
.app-wrap {
	width: 750rpx;
	height: 100vh;
	overflow: auto;
	background-color: #f4f5f7;
	background-image: linear-gradient(to top, #f4f5f7 0%, #2272ff 50%);
	background-size: 750rpx 600rpx;
	background-repeat: no-repeat;
	display: flex;
	flex-direction: column;
	.content {
		margin-bottom: 240rpx;
		height: 100%;
		overflow-y: auto;
		.card {
			margin: 20rpx 30rpx;
			padding: 30rpx;
			padding-top: 0;
			border-radius: 12rpx;
			background-color: #FFFFFF;
			.title {
				line-height: 106rpx;
				font-size: 32rpx;
				font-weight: bold;
				color: #333333;
			}
			.more {
				color: #2272FF;
    		font-size: 28rpx;
			}
			.body {
				.list {
					.sold-out {
						margin-top: 20rpx;
					}
					.message {
						font-size: 26rpx;
						font-weight: 400;
						color: #999999;
						line-height: 36rpx;
						text-align: center;
					}
					.add-button {
						margin: 42rpx 0 20rpx 0;
						width: 200rpx;
						height: 80rpx;
						border-radius: 52rpx;
						border: 2rpx solid #2272FF;
						font-size: 32rpx;
						font-weight: 500;
						color: #2272FF;
						line-height: 80rpx;
					}
				}
				.desc {
					height: 200rpx;
				}
			}
		}
		.parts {
		}
		.address {
			.body {
				border-top: 2rpx solid #F4F5F7;
				padding-top: 10rpx;
				padding-bottom: 52rpx;
			}
		}
	}
	.bottom {
		position: absolute;
		left: 76rpx;
		right: 76rpx;
		bottom: 68rpx;
		
		/deep/ button[disabled]:not([type]) {
		    background-color: #D1D4D4 !important;
		}
	}
}
</style>
