<template>
	<view>
		<view class="box">
			<view class="title">报价清单</view>
			<view class="lf-font-24 lf-color-gray lf-m-t-5">请在以下物资信息表内填写报价</view>
		</view>
		<!-- 修饰条 -->
		<self-line></self-line>
		<view class="box lf-row-between relation">
			<view>
				<text class="title">关联食堂</text>
				<text class="lf-font-24 lf-color-555 lf-m-l-10">(多选)</text>
			</view>
			<view class="lf-font-24 lf-color-gray lf-text-right lf-row-center" style="width: 370rpx; justify-content: flex-end;" @click="switchRelation">
				<view class="lf-line-1">{{ selectName }}</view>
				<u-icon name="arrow-right" class="lf-text-vertical"></u-icon>
			</view>
			<view class="mask" :style="{top: node_top +'px'}" v-if="is_show" @click="is_show = false">
				<view class="list">
					<view class="lf-row-between item" v-for="(item, index) in relation_list" :key="index" @click.stop="selectItem(index)">
						<view>{{ item.canteen_name }}</view>
						<u-icon name="checkmark-circle" color="#1833F2" size="40" v-if="item.checked"></u-icon>
					</view>
				</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="deadline_start" @change="pickerChange($event, 'deadline_start')">
				<view class="lf-color-555 lf-text-right" style="width: 400rpx;">{{ deadline_start || '请选择...' }}</view>
			</picker>
		</view>
		<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="deadline_end" @change="pickerChange($event, 'deadline_end')">
				<view class="lf-color-555 lf-text-right" style="width: 400rpx;">{{ deadline_end || '请选择...' }}</view>
			</picker>
		</view>
		<self-line></self-line>
		
		
		<!-- 物料table -->
		<view class="box">
			<view class="lf-font-32 lf-color-black lf-font-bold lf-m-b-20">报价明细</view>
			<wyb-table :first-line-fixed="true" 
				contentBgColor="#eef6fe" 
				:headers="headers" 
				:contents="contents" 
				@onInputChange="onInputChange" 
				@onButtonClick="onButtonClick"
				width="100%" height="80vh"></wyb-table>
		</view>
		<view style="height: 140rpx;"></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';
	let app = getApp();
	
	export default {
		components: {
			wybTable
		},
		data(){
			return {
				headers: [{
					label: '物资名称',
					key: 'name'
				},{
					label: '规格',
					key: 'spec'
				},{
					label: '单位',
					key: 'unit'
				},{
					label: '分类',
					key: 'category'
				},{
					label: '品牌',
					key: 'brand'
				},{
					label: '品级',
					key: 'quality_level'
				},{
					label: '编号',
					key: 'number'
				},{
					label: '起购数',
					key: 'purchase_limit'
				},{
					label: '含税价',
					key: 'tax_price'
				},{
					label: '非含税价',
					key: 'non_tax_price'
				},{
					label: '操作',
					key: 'operation'
				}],
				contents: [],
				is_show: false,
				relation_list: [], // 关联食堂列表
				node_top: 0,
				code: '', // 订单号，批次号，如果有
				type: 0,
				deadline_start: '',
				deadline_end: ''
			}
		},
		computed: {
			selectName(){
				let arr = [];
				this.relation_list.map(item => {
					if(item.checked){
						arr.push(item.canteen_name);
					}
				});
				let str = '请选择...';
				if(arr.length > 0){
					str = arr.join(',');
				}
				return str;
			}
		},
		onLoad(options){
			this.code = options.code || '';
			this.type = options.type || 0;
			if(options.type == 1){
				// 编辑，不可更换食堂
				this.materialListByOrder();
			}else if(options.type == 2){
				// 复用订单号
				this.materialListByOrder();
			}else if(options.type == 3){
				// 复用批次号
				this.materialListByBatch();
			}else{
				// 单纯发起报价
				this.getMaterialList();
			}
		},
		onReady(){
			let that = this;
			let info = uni.createSelectorQuery().select(".relation");
	　　　   info.boundingClientRect(function(data) {
				let num = app.globalData.customBarH;
				num += data.height;
				num += data.top;
				that.node_top = num;
	　　    }).exec()
		},
		onPageScroll(){
			if(this.is_show){
				this.is_show = false;
			}
		},
		methods: {
			// 日期选择器值被改变
			pickerChange(event, current_name){
				console.log(current_name)
				if(current_name == 'deadline_start') {
					// PS 获取30天后日期
					var date1 = new Date(event.detail.value);
					var date2 = new Date(date1);
					date2.setDate(date1.getDate() + 30);
					console.log(this.$shared.recordTime(date2, '-', 'date'))
					this[current_name] = event.detail.value;
					this.deadline_end = this.$shared.recordTime(date2, '-', 'date')
				}else {
					this[current_name] = event.detail.value;
				}
				
			},
			// 获取物资列表
			getMaterialList(){
				this.$http(this.API.API_SUPPLIER_MATERIALLIST).then(res => {
					let list = res.data.spec || [];
					let contents = list.map(item => {
						return {
							name: item?.material?.m_name || '',
							material_id: item?.material?.id || 0,
							spec: item.name,
							spec_id: item.id,
							brand: item?.material?.brand || '',
							quality_level: item?.material?.quality_level || '',
							number: item?.material?.m_sn || '',
							purchase_limit: {edit: true, value: 1},
							tax_price: {edit: true, value: ''},
							non_tax_price: {edit: true, value: ''},
							operation: {button: true, key: 'delete', value: '删除'},
							unit: item?.material?.unit?.unit_name || '',
							category: item?.material?.category?.m_cate_name || ''
						}
					})
					this.contents = contents;
					this.getCanteenList();
				})
			},
			// 复用报价订单号 & 编辑共用
			materialListByOrder(){
				this.$http(this.API.API_SUPPLIER_QUOTATIONREUSEBYORDER, {
					q_sn: this.code
				}).then(res => {
					let list = res.data.order || [];
					let canteen = res.data.canteen || [];
					// 处理表格显示
					let contents = list.map(item => {
						let obj = {
							name: item?.material?.m_name || '',
							material_id: item?.material?.id || 0,
							spec: item.name,
							spec_id: item.id,
							brand: item?.material?.brand || '',
							quality_level: item?.material?.quality_level || '',
							number: item?.material?.m_sn || '',
							purchase_limit: {edit: true, value: item?.quotation_item?.purchase_limit || ''},
							tax_price: {edit: true, value: item?.quotation_item?.tax_price || ''},
							non_tax_price: {edit: true, value: item?.quotation_item?.non_tax_price || ''},
							quotation_id: item?.quotation_item?.id || 0,
							operation: {button: true, key: 'delete', value: '删除'},
							unit: item?.material?.unit?.unit_name || '',
							category: item?.material?.category?.m_cate_name || ''
						}
						if(item?.material?.state && item?.material?.state != '启用'){
							obj.disabled = true;
						}
						return obj;
					})
					this.contents = contents;
					// 处理报价生效、失效时间
					let deadline_start = '';
					let deadline_end = '';
					if(list[0] && list[0]?.quotation_item?.quotation){
						let quotation = list[0]?.quotation_item?.quotation || {};
						if(quotation.deadline_start){
							deadline_start = quotation.deadline_start.split(' ')[0];
						}
						if(quotation.deadline){
							deadline_end = quotation.deadline.split(' ')[0];
						}
					}
					this.deadline_start = deadline_start;
					this.deadline_end = deadline_end;
					this.getCanteenList(canteen);
				})
			},
			// 复用批次号
			materialListByBatch(){
				this.$http(this.API.API_SUPPLIER_QUOTATIONREUSEBYBATCH, {
					batch_sn: this.code
				}).then(res => {
					console.log("materialListByBatch", res);
					let list = res.data.order || [];
					let canteen = res.data.canteen || [];
					// 处理表格显示
					let contents = list.map(item => {
						return {
							name: item?.material?.m_name || '',
							material_id: item?.material?.id || 0,
							spec: item.name,
							spec_id: item.id,
							brand: item?.material?.brand || '',
							quality_level: item?.material?.quality_level || '',
							number: item?.material?.m_sn || '',
							purchase_limit: {edit: true, value: item?.quotation?.purchase_limit || ''},
							tax_price: {edit: true, value: item?.quotation?.tax_price || ''},
							non_tax_price: {edit: true, value: item?.quotation?.non_tax_price || ''}
						}
					})
					this.contents = contents;
					// 处理报价生效、失效时间
					let deadline_start = '';
					let deadline_end = '';
					if(list[0] && list[0]?.quotation_item?.quotation){
						let quotation = list[0]?.quotation_item?.quotation || {};
						if(quotation.deadline_start){
							deadline_start = quotation.deadline_start.split(' ')[0];
						}
						if(quotation.deadline){
							deadline_end = quotation.deadline.split(' ')[0];
						}
					}
					this.deadline_start = deadline_start;
					this.deadline_end = deadline_end;
					this.getCanteenList(canteen);
				})
			},
			// 关联食堂列表
			getCanteenList(canteen = []){
				this.$http(this.API.API_SUPPLIER_CANTEENLIST).then(res => {
					let list = res.data.list.map(item => {
						item.checked = false;
						canteen.map(ct => {
							if(ct == item.id){
								item.checked = true;
							}
						})
						return item;
					})
					this.relation_list = list;
				})
			},
			// 监听表格被输入
			onInputChange(event){
				this.contents[event.contentIndex][event.key].value = event.detailValue;
			},
			// table操作按钮被点击
			onButtonClick(event){
				if(event.content.key == 'delete'){
					let contentIndex = event.contentIndex;
					let name = event.lineData.name;
					let spec = event.lineData.spec;
					uni.showModal({
						title: '温馨提示',
						content: `确定删除 ${name}-${spec} 吗？`,
						confirmColor: '#1833F2',
						success: result => {
							if(result.confirm){
								this.contents.splice(contentIndex, 1);
							}
						}
					})
				}
			},
			// 切换显示关联食堂modal
			switchRelation(){
				if(this.type == 1) return this.$msg('编辑不可更换关联食堂哦');
				this.is_show = !this.is_show;
			},
			// 选择食堂
			selectItem(index){
				this.relation_list[index].checked = !this.relation_list[index].checked;
			},
			// 报价订单编辑时保存
			editMaterial(_t){
				// 物资列表
				let list = [];
				this.contents.map(item => {
					list.push({
						id: item.quotation_id,
						tax_price: item.tax_price.value,
						non_tax_price: item.non_tax_price.value,
						purchase_limit: Number(item.purchase_limit.value) || 1
					})
				});
				// 操作状态，是保存还是直接发起
				let state = ['待发起', '待审核'][_t];
				this.$http(this.API.API_SUPPLIER_QUOTATIONSAVE, {
					data: list,
					state: state,
					q_sn: this.code,
					start: this.deadline_start,
					end: this.deadline_end
				}).then(res => {
					this.$msg('操作成功').then(result => {
						this.$toBack();
					})
				})
			},
			// 保存
			save(_t){
				// 拦截是编辑的情况
				if(this.type == 1){
					this.editMaterial(_t);
					return;
				}
				// 物资列表
				let list = [];
				this.contents.map(item => {
					if(item.tax_price.value && item.non_tax_price.value){
						list.push({
							m_id: item.material_id,
							m_spec_id: item.spec_id,
							tax_price: item.tax_price.value,
							non_tax_price: item.non_tax_price.value,
							purchase_limit: Number(item.purchase_limit.value) || 1
						})
					}
				});
				// 关联食堂
				let canteen_ids = [];
				this.relation_list.map(item => {
					if(item.checked){
						canteen_ids.push(item.id);
					}
				})
				if(canteen_ids.length <= 0){
					return this.$msg('您未选择关联食堂哦')
				}
				if(!this.deadline_start){
					return this.$msg('您未选择报价生效时间哦')
				}
				if(!this.deadline_end){
					return this.$msg('您未选择报价失效时间哦')
				}
				if(list.length <= 0){
					return this.$msg('请补充完整物资报价信息')
				}
				// 操作状态，是保存还是直接发起
				let state = ['待发起', '待审核'][_t];
				this.$http(this.API.API_SUPPLIER_QUOTATIONAPPLY, {
					data: list,
					state: state,
					canteen_ids: canteen_ids,
					start: this.deadline_start,
					end: this.deadline_end
				}).then(res => {
					this.$msg(res.data).then(result => {
						this.$toBack();
					})
				})
			}
		}
	}
</script>

<style>
	page{
		overflow: hidden;
	}
</style>
<style lang="scss" scoped="scoped">
	.lf-m-t-5{
		margin-top: 5rpx;
	}
	.box{
		padding: 30rpx 32rpx;
		width: 100%;
		height: max-content;
		box-sizing: border-box;
	}
	.title{
		color: #222222;
		font-size: 28rpx;
		font-weight: bold;
	}
	.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: #fff;
		.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: #1833F2;
			color: #FFFFFF;
			margin-left: 50rpx;
		}
	}
	.relation{
		position: relative;
		border-bottom: 1rpx solid #E5E5E5;
	}
	.mask{
		position: fixed;
		background-color: rgba(0,0,0,0.4);
		width: 100%;
		// top: 149px;
		bottom: 0;
		left: 0;
		z-index: 100;
		.list{
			min-height: max-content;
			max-height: 500rpx;
			overflow: scroll;
			background-color: #FFFFFF;
			width: 100%;
			.item{
				height: 92rpx;
				padding: 0 32rpx;
				border-bottom: 1rpx solid #E5E5E5;
				color: #222222;
				font-size: 28rpx;
			}
		}
	}
</style>
