<template>
	<view>
		<view class="head">
			<view class="list">
				<view class="lf-row-between">
					<view>供应商</view>
					<view class="lf-icon" @click="$url('/pages/classification/supplier')">
						<u-icon name="plus-circle" size="42"></u-icon>
					</view>
				</view>
			</view>
			<view class="list" v-if="show_material">
				<view class="lf-row-between">
					<view>采购清单</view>
					<view class="lf-icon" @click="$url('/pages/classification/material?type=1')">
						<u-icon name="plus-circle" size="42"></u-icon>
					</view>
				</view>
				<view class="lf-font-24 lf-color-gray">添加物资后可以编辑数量</view>
			</view>
		</view>
		<!-- 修饰条 -->
		<self-line></self-line>
		<!-- 收货时间 -->
		<view class="lf-row-between lf-p-30 lf-p-l-32 lf-p-r-32 lf-font-28">
			<view class="lf-color-black">收货时间</view>
			<picker mode="date" :value="date" @change="pickerChange">
				<view class="lf-color-555 lf-text-right" style="width: 400rpx;">{{ date || '请选择收货时间...' }}</view>
			</picker>
		</view>
		<self-line></self-line>
		<!-- 物料table -->
		<view class="lf-p-32 lf-p-t-30 lf-p-b-30 lf-w-100 lf-h-maxcontent lf-border-box">
			<view class="lf-font-32 lf-font-bold">物资明细</view>
			<view v-for="(value, key) in render_material_list" :key="key" class="lf-m-t-20" v-if="value.material_list.length">
				<view class="lf-m-b-10 lf-row-between">
					<text>{{ value.supplier_name }}</text>
					<text @click="removeSupplier(key)" class="lf-color-price">删除</text>
				</view>
				<wyb-table :headers="value.headers" 
					:contents="value.material_list" 
					contentBgColor="#ecfaf5" 
					:first-line-fixed="true" 
					@onInputChange="onInputChange" 
					width="max-content" height="800rpx"
					@onButtonClick="onButtonClick"></wyb-table>
			</view>
		</view>
		<!-- 操作按钮 -->
		<view style="height: 100rpx;"></view>
		<view class="fixed-bottom">
			<button class="btn btn1" @click="save(0)">临时保存</button>
			<button class="btn btn2" @click="save(1)">保存并发单</button>
		</view>
	</view>
</template>

<script>
	import wybTable from '@/components/wyb-table/wyb-table';
	
	export default {
		components: {
			wybTable
		},
		data(){
			return {
				// date: this.$shared.recordTime(new Date(), '-', 'date'), // 选择时间, 默认今天
				date: '',
				material_list: {}, // 供应商，物资列表，不被渲染，在底层逻辑运作
				show_material: false, // 是否显示采购清单按钮
				render_material_list: {}, // 渲染出来的物资列表
				show_count: 0, // 页面显示次数
				p_sn: '', // 订单号，如果有
				type: 0 // 类型
			}
		},
		onLoad(options){
			// TODO 采购单编辑时保存
			// todo 采购单复用ok，还差 编辑 采购单保存
			
			// 监听MaterialList被操作
			uni.$on('addMaterialList', res => {
				this.material_list = res;
			})
			
			// /pages/purchase/launch?p_sn=P162771908650053&enter_type=2
			if(options){
				this.p_sn = options.p_sn || '';
				this.type = options.enter_type || 0;
				if(options.enter_type == 2){
					this.copyMaterialList(); // 复用采购单
				}
			}
			
			var test = {
				"2": {
					address: "",
					admin_uid: 2,
					area_id: 0,
					checked: true,
					city_id: 0,
					corporate_account: "",
					corporate_account_name: "",
					corporate_bank: "",
					corporate_bank_sub: "",
					corporate_name: "",
					corporate_phone: "",
					created_at: "2021-07-31 10:23:47",
					created_uid: 1,
					ctl_man: "张大拿",
					ctl_phone: "13177889965",
					deleted_at: null,
					deleted_uid: 0,
					id: 2,
					license_number: "",
					license_pic: "https://gxskyimg.lanzulive.com/",
					logo: "admin_images/89897b012083b738b5792079368e73b9.jpeg",
					material_list: {
						"1": {
							brand: "",
							checked: true,
							item_id: 1,
							m_sn: "M162769768826400",
							material_id: 1,
							material_name: "上林丝苗米",
							non_tax_price: "1.00",
							purchase_limit: 1,
							quality_level: "",
							spec_id: 1,
							spec_name: "-",
							supplier_id: 2,
							supplier_name: "食品类供应商001",
							tax_price: "2.00"
						}
					},
					private_account: "",
					private_account_name: "",
					private_bank: "",
					private_bank_sub: "",
					province_id: 0,
					qualification_pic: "https://gxskyimg.lanzulive.com/",
					remark: "",
					s_cate_id: 1,
					state: "启用",
					subject_name: "",
					subject_type: "公司",
					supplier_name: "食品类供应商001",
					updated_at: "2021-07-31 10:24:03",
					updated_uid: 1
				}
			}
			
			console.log("options", options);
			
		},
		onShow(){
			this.show_count++;
			if(this.show_count > 1){
				this.transformList();
			}
		},
		methods: {
			// 物资列表转换成页面可渲染的格式，material_list => render_material_list
			transformList(){
				let material_list = JSON.stringify(this.material_list);
				material_list = JSON.parse(material_list);
				for(let i in material_list){
					// table 标题处理
					material_list[i].headers = [{
						key: 'material_name',
						label: '物资名称'
					},{
						key: 'spec_name',
						label: '规格'
					},{
						key: 'brand',
						label: '品牌'
					},{
						key: 'quality_level',
						label: '品级'
					},{
						label: '编号',
						key: 'm_sn'
					},{
						label: '供应商',
						key: 'supplier_name'
					},{
						key: 'tax_price',
						label: '含税价'
					},{
						key: 'non_tax_price',
						label: '不含税价'
					},{
						key: 'purchase_limit',
						label: '起购数'
					},{
						key: 'purchase_number',
						label: '采购数量'
					},{
						key: 'operation',
						label: '操作'
					}];
					// table 内容处理
					let list_arr = [];
					for(let j in material_list[i].material_list){
						material_list[i].material_list[j].purchase_number = {edit: true, value: ''};
						material_list[i].material_list[j].operation = {button: true, key: 'delete', value: '删除'};
						material_list[i].material_list[j].supplier_name = material_list[i].supplier_name;
						material_list[i].material_list[j].tax_price = material_list[i].material_list[j].tax_price;
						material_list[i].material_list[j].non_tax_price = material_list[i].material_list[j].non_tax_price;
						list_arr.push(material_list[i].material_list[j]);
					}
					material_list[i].material_list = list_arr;
				}
				this.render_material_list = material_list;
				this.show_material = Object.keys(this.material_list).length > 0;
				console.log("transform..material_list", this.material_list);
				console.log("transform...render_material_list", this.render_material_list)
			},
			// 复用采购单
			copyMaterialList(){
				this.$http(this.API.API_BUYREUSE, {
					p_sn: this.p_sn
				}).then(res => {
					let list = res.data || [];
					let material_list = {};
					list.map(item => {
						let items = item.purchase[0].items;
						let items_obj = {};
						items.map(i_item => {
							items_obj[i_item.quotation_item_id] = {
								brand: i_item.material.brand,
								checked: true,
								item_id: i_item.quotation_item_id,
								m_sn: i_item.material.m_sn,
								material_id: i_item.material.id,
								material_name: i_item.material.m_name,
								non_tax_price: i_item.non_tax_price,
								purchase_limit: i_item.p_order_item.purchase_limit,
								quality_level: i_item.material.quality_level,
								spec_id: i_item.spec.id,
								spec_name: i_item.spec.name,
								supplier_id: item.id,
								supplier_name: item.supplier_name,
								tax_price: i_item.tax_price
							};
						});
						item.material_list = items_obj;
						material_list[item.id] = item;
					})
					this.material_list = material_list;
					this.transformList();
					console.log("yes", material_list);
				})
			},
			// table-input值被改变
			onInputChange(event){
				console.log("检测到table input被更改", event);
				let supplier_id = event.lineData.supplier_id; // 取出第一层，供应商id
				let material_index = event.contentIndex; // 取出第二层，物资下标
				let detailValue = event.detailValue; // 取出table input被输入的值
				let supplier_item = this.render_material_list[supplier_id]; // 取出所在供应商
				let material_item = supplier_item.material_list[material_index]; // 取出物资
				if(material_item.purchase_limit <= detailValue){
					material_item.purchase_number.value = detailValue; // 将输入的值赋值给物资
				}else{
					this.$msg('采购数量须大于起购数量');
					material_item.purchase_number.value = material_item.purchase_limit;
					
					// uni.showModal({
					// 	title: '温馨提示',
					// 	content: '采购数量必须大于起购数量',
					// 	showCancel: false,
					// 	success: result => {
					// 		material_item.purchase_number.value = material_item.purchase_limit;
					// 	}
					// })
				}
				console.log("render_material_list_change", this.render_material_list);
			},
			// table 操作按钮被点击
			onButtonClick(event){
				console.log("event", event);
				if(event.content.key == 'delete'){
					let supplier_id = event.lineData.supplier_id; // 取出第一层，供应商id
					let item_id = event.lineData.item_id; // 取出第二层，item_id
					let material_index = event.lineData.contentIndex; // 取出第二层，物资下标
					this.render_material_list[supplier_id].material_list.splice(material_index, 1);
					delete this.material_list[supplier_id].material_list[item_id];
				}
			},
			// 时间选择
			pickerChange(event){
				this.date = event.detail.value;
			},
			// 移除供应商
			removeSupplier(key){
				uni.showModal({
					title: '温馨提示',
					content: '删除供应商后所添加的物资将随之移除，确定继续吗？',
					confirmColor: '#FF0000',
					cancelColor: '#11D189',
					success: result => {
						if(result.confirm){
							// 移除render_material_list
							let render_material_list = {...this.render_material_list};
							delete render_material_list[key];
							this.render_material_list = render_material_list;
							// 移除material_list
							delete this.material_list[key];
							// 校验还有没有供应商，没有则不能显示选择物资按钮
							this.show_material = Object.keys(this.material_list).length > 0;
						}
					}
				})
			},
			// 保存并发单
			save(_t){
				let material_list = this.render_material_list;
				let list = [];
				let is_empty = true; // 物资数据是否为空
				let is_right = true; // 采购份数为正常的情况
				for(let i in material_list){
					if(Object.keys(material_list[i].material_list).length){
						is_empty = false;
						let material = material_list[i].material_list;
						// 数组写法
						let arr = material.map(item => {
							if(item.purchase_limit > item.purchase_number.value){
								is_right = false;
							};
							return {
								m_id: item.material_id,
								quotation_item_id: item.item_id,
								m_spec_id: item.spec_id,
								tax_price: item.tax_price,
								non_tax_price: item.non_tax_price,
								purchase_number: Number(item.purchase_number.value) || item.purchase_limit
							}
						});
						// 对象写法: 
						// let arr = [];
						// for(let j in material){
						// 	arr.push({
						// 		m_id: material[j].material_id,
						// 		m_spec_id: material[j].spec_id,
						// 		tax_price: material[j].tax_price,
						// 		non_tax_price: material[j].non_tax_price,
						// 		purchase_number: material[j].purchase_number.value || 0
						// 	});
						// }
						list.push({
							supplier_id: material_list[i].id,
							material: arr
						})
					}
				}
				
				console.log("list", list)
				let deadline = this.date;
				if(!deadline){
					this.$msg('请选择收货时间');
					return;
				}
				if(is_empty){
					this.$msg('您未选择物资');
					return;
				}
				if(!is_right){
					this.$msg('采购数量需大于起购数量');
					return;
				}
				// let state = ['待发单', '待审核'][_t];
				this.$http(this.API.API_CANTEEN_PURCHASEAPPLY, {
					order: list,
					state: _t,
					deadline: deadline
				}).then(res => {
					console.log("save", res);
					this.$msg('操作成功').then(()=>{this.$toBack()});
				})
			}
		}
	}
</script>

<style lang="scss" scoped="scoped">
	.lf-m-t-5{
		margin-top: 5rpx;
	}
	.head{
		width: 750rpx;
		height: max-content;
		padding: 0 32rpx;
		box-sizing: border-box;
		.list{
			width: 100%;
			border-bottom: 1rpx solid #e5e5e5;
			padding: 30rpx 0;
			font-size: 28rpx;
			&:last-child{
				border-bottom: none;
			}
			.lf-icon{
				padding: 2rpx 10rpx;
				display: flex;
				align-items: center;
				justify-content: center;
			}
		}
	}
	.fixed-bottom{
		position: fixed;
		bottom: 0rpx;
		left: 0rpx;
		z-index: 99;
		width: 750rpx;
		height: 98rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		border-top: 1rpx solid #E5E5E5;
		background-color: #FFFFFF;
		.btn{
			width: 320rpx;
			height: 82rpx;
			border-radius: 41rpx;
			margin: 0;
			padding: 0;
			font-size: 32rpx;
			display: flex;
			justify-content: center;
			align-items: center;
		}
		.btn1{
			border: 2rpx solid #555555;
			opacity: .5;
		}
		.btn2{
			background: #11D189;
			color: #FFFFFF;
			margin-left: 50rpx;
		}
	}
</style>
