<template>
	<view class="page-container">
		<view class="page-body">
			<u--form label-width="auto" labelAlign="left"
				ref="uForm"
				:model="model"
				:rules="rules"
				:labelStyle="{
					fontSize: '28rpx',
					fontWeight: '500',
				}"
			>
				<u-cell-group :border="false">
					<view class="box">
						
						<template>
							<u-cell title="申领人" :border="true" :isLink="false" :clickable="false"
								@click="$refs.userChooseRef.show()"
							>
								<view slot="value">
									<u-form-item label="">
										{{renderItem(model.form,'outflowUser','--')}}
									</u-form-item>
								</view>	
							</u-cell>
							
							<tq-car-user ref="userChooseRef"
								:isGetIcon="false"
								:queryType="1"
								@confirm="(data) => {
									model.form.outflowUserId = data.id
									model.form.outflowUser = data.label
									model.form.deptId = data.deptId
									model.form.deptName = data.deptName
								}"
							>
							</tq-car-user>
						</template>
						
						<u-cell title="申领部门" :border="true" :isLink="false" :clickable="false">
							<view slot="value" class="value">
								<u-form-item label="">
									{{renderItem(model.form,'deptName','--')}}
								</u-form-item>
							</view>	
						</u-cell>
	
						<template>
							<u-cell :border="true" :isLink="true" :clickable="true" class="hidde-cell-title"
								@click="$refs.selectRef.show()"
							>
								<view slot="value" class="value">
									<u-form-item label="申领类型" prop="form.outflowType" :required="true">
										<u--input
											:value="model.form.outflowTypeName" 
											placeholder="请选择" 
											border="none"
											inputAlign="right"
											:disabled="true"
											disabledColor="none"
											:customStyle="{
												pointerEvents: 'none',
											}"
										>
										</u--input>
									</u-form-item>
								</view>	
							</u-cell>
							
							<tq-dict-select ref="selectRef"
								dictType="get_type_type"
								@confirm="(data) => {
									model.form.outflowType = data.dictValue
									model.form.outflowTypeName = data.dictLabel
									$refs.uForm.validateField('form.outflowType')
								}"
							>
							</tq-dict-select>
							
						</template>
						
						<template v-if="model.form.outflowType==1">
							<u-cell :border="true" :isLink="true" class="hidde-cell-title"
								@click="$refs.backDateRef.show()"
							>
								<view slot="value" class="value">
									<u-form-item label="预计归还日期" prop="form.backDate" :required="true">
										<u--input
											:value="model.form.backDate" 
											placeholder="请选择" 
											border="none"
											inputAlign="right"
											:disabled="true"
											disabledColor="none"
											:customStyle="{
												pointerEvents: 'none',
											}"
										>
										</u--input>
									</u-form-item>
								</view>	
							</u-cell>
							<tq-date-time ref="backDateRef"
								mode="date"
								format="YYYY-MM-DD"
								@confirm="(data) => {
									model.form.backDate = data
									$refs.uForm.validateField('form.backDate')
								}"
							>
							</tq-date-time>
						</template>
						
						<u-cell :border="false" :isLink="false" :clickable="false" class="hidde-cell-title">
							<view slot="value" class="value">
								<u-form-item label="备注" labelPosition="top" prop="form.remark" :required="false">
									<u--textarea
										v-model="model.form.remark" 
										placeholder="请输入备注" 
										border="none"
										:count="true"
										maxlength="200"
									>
									</u--textarea>
								</u-form-item>
							</view>	
						</u-cell> 
					</view>
					
					<view class="box">
						<template>
							<u-cell :border="true" :isLink="true" :clickable="true" class="hidde-cell-title"
								@click="$refs.materialListRef.show()"
							>
								<view slot="value" class="value">
									<u-form-item label="选择物品" prop="form.outList" :required="true">
										<u--input
											:value="model.form.materialName" 
											placeholder="" 
											border="none"
											inputAlign="right"
											:disabled="true"
											disabledColor="none"
											:customStyle="{
												pointerEvents: 'none',
											}"
										>
										</u--input>
									</u-form-item>
								</view>	
							</u-cell>
							
							<tq-search-select ref="materialListRef"
								:multiple="true"
								:dataList = "materialList"
								@confirm="updateMeterial"
								:objMap="{
									label: 'materialName',
									value: 'materialId',
								}"
								:hasTip="true"
							>
								
							</tq-search-select>
						</template>			
					</view>			
						
					<template v-for="(sitem,index) in model.form.outList">
				
						<u-form :model="sitem" :ref="`outListRef`" :key="index" label-width="auto" labelAlign="left">
								<view class="box">
									<u-row>
										<u-col :span="10">
											<u-cell :border="true" :isLink="false" :clickable="false" class="hidde-cell-title">
												<view slot="value" class="value">
													<u-form-item label="物品名称:" prop="" :required="false">
														<view class="disflex-right" style="width:100%;">{{sitem.materialName}}</view>
														
													</u-form-item>
												</view>	
											</u-cell> 
											
											<u-cell :border="true" :isLink="false" :clickable="false" class="hidde-cell-title">
												<view slot="value" class="value">
													<u-form-item label="申领数量:" prop="num" :required="true">
														<u--input
															v-model="sitem.num" 
															placeholder="请输入" 
															border="none"
															type="number"
															:clearable="true"
															inputAlign="right"
															maxlength="10"
															@change="handleNumChange(sitem,index)"
														>
														</u--input>
													</u-form-item>
												</view>	
											</u-cell> 	
										</u-col>
										<u-col :span="2">
											<view class="disflex-center" @click="deleteItem(index)">
												<u-icon name="minus-circle-fill" color="red" size="28"></u-icon>
											</view>
										</u-col>
									</u-row>
									
																	
								</view>
						</u-form>
					</template>
				</u-cell-group>
				
			</u--form>
		</view>
		
		<view class="page-footer">
			<u-row style="margin-top: 40rpx;">
				<u-col :span="6">
		
					<u-button type="info" shape="" :hairline="false" :custom-style="{
							width: '100%',
							borderRadius: '0',
							background: '#FFF',
							height: '100rpx',
							fontSize: '32rpx',
							fontWeight: '500',
						  }" @click="handleClear">清空
					</u-button>
					
				</u-col>	
				<u-col :span="6">
					
					
					<u-button type="primary" shape="" :hairline="false" 
            :custom-style="{
							width: '100%',
							borderRadius: '0',
							height: '100rpx',
							fontSize: '32rpx',
							fontWeight: '500',
              background:'linear-gradient(to right, #41B5FF, #4573FC)'
						  }" @click="handleSubmit">提交
					</u-button>
				</u-col>
			</u-row>
		</view>
	</view>
</template>

<script>
import {userProfile} from '@/api/common/user.js'
import {addMaterialApply,queryOneById,queryMaterialList} from '@/api/system/material.js'
import {clearProps,copyProps} from '@/utils/gdtq.js'
import {isEmpty} from 'lodash'

export default {
	components: {
	},
	data() {
		return {
			model: {
				  form: {
					outflowUserId: "",
					outflowUser: "",		
					deptId: "",
					deptName: "",
					outflowType: "",
					outflowTypeName: "",
					backDate: "",
					remark: "",
				
					// materialId: "",
					// materialName: "",
					
					outList: [
						/* {
							materialId: 1,
							materialName: 'testest',
							amountTotal: 0,
							num: ''
						} */
					],
				  }
			},
			rules: {
				
				'form.outflowType': [
					{
						type: 'string',
						required: true,
						message: '请选择',
						trigger: ['blur', 'change']
					},	
				],
				'form.backDate': {
					type: 'string',
					required: true,
					message: '请选择',
					trigger: ['blur', 'change']
				},
				'form.outList': {
					type: 'array',
					required: true,
					message: '请选择',
					trigger: ['blur', 'change']
				},	
			},
			
			/* 物品数组校验规则 start */
			outListRules: {
				
				num: [
					{
						type: 'number' ,
						required: true,
						message: '请输入',
						trigger: ['blur', 'change']
					},	
					{
						pattern: /^[1-9]\d*$/g,
						// 正则检验前先将值转为字符串
						transform(value) {
							return String(value);
						},
						message: '请输入大于0的正整数',
						// 触发器可以同时用blur和change
						trigger: ['change','blur'],
					}
				],
			},
			
			materialList: [],
			userInfo: null,
		}
	},
	onLoad({id}) {
		// console.log(id,'id')
		this.queryMaterialListData()
		if(id) {
			this.getInfo(id)
		} else {
			this.getUserInfo()
		}
		
	},
	onShow() {
		
	},
	onHide() {
		
	},
	onReady() {	
		this.resetRules()
	},
	methods: {
		
		resetRules() {
			this.$refs.uForm.setRules(this.rules)		
			
			for (let i in this.model.form.outList) {
				this.$refs.outListRef[i].setRules(this.outListRules);
			}
			
		},
		
		async queryMaterialListData() {
			let {code,data} = await queryMaterialList({})
			if(code == 0) {
				this.materialList = data.map((e) => {
					return {
						...e,
						tip: `(可用库存${e.amountTotal})`,
						disabled: !(e.amountTotal>0)
					}
				})
			}
		},
		async getInfo(id) {
			let {code,data} = await queryOneById({id})
			if(code == 0) {
				copyProps(this.model.form,data)
			}
		},
		getUserInfo() {
			userProfile().then((res) => {
				this.userInfo = res.data
				this.model.form.outflowUserId = res.data.userId
				this.model.form.outflowUser = res.data.nickName
	
				this.model.form.deptId = res.data.deptId
				this.model.form.deptName = res.data.deptName
			})
		},
		// 提交
		async handleSubmit() {
			
			for (let i in this.model.form.outList) {
				this.$refs.outListRef[i].validate(valid => {
					if (!valid) return
				})
			}
			  this.$refs.uForm.validate().then(async res => {
				  
					  
					  for (let i in this.model.form.outList) {
					  		await this.$refs.outListRef[i].validate()						
					  }
				  
					  let ajaxData = {
						  ...this.model.form,
					  }

					  let { data, code,msg } = await addMaterialApply(ajaxData) 
					  
					  if (code == 0) {
							
							uni.showModal({
								title: '提示',
								content: `提交成功~`,
								showCancel:false,
								confirmText: '好的',
								success: function(res) {
									if (res.confirm) {
										uni.switchTab({url: '/pages/index/index'})
									}
								}
							})
							
					  }	
				  
			  }).catch(errors => {
				  console.log('校验失败',errors)
			  })
		},
		handleClear() {
			
			clearProps(this.model.form,['outflowUserId','outflowUser','deptId','deptName'])
		},
		updateMeterial(data) {
			// console.log(data,'data')
			if(!isEmpty(data)) {
				this.model.form.outList = data.map((e) => {
					return {
						materialId: e.materialId,
						materialName: e.materialName,
						amountTotal: e.amountTotal,
						num: ''
					}
				})
			} else {
				this.model.form.outList = []
			}
			this.model.form.materialId = data.materialId
			this.model.form.materialName = data.materialName
			
			this.$refs.uForm.validateField('form.outList')
			
			this.$nextTick(() => {
				this.resetRules()
			})
		},
		deleteItem(index) {
			this.model.form.outList.splice(index, 1)
			this.$nextTick(() => {
				this.resetRules()
			})
		},
		handleNumChange(row,index) {
		    if(row.materialId) {
		        if(row.num > row.amountTotal) {
		            this.$modal.msg(`已超过可用申领数${row.amountTotal}`)
		            // row.num = row.amountTotal
	
		        }
		    } else {
		        this.$modal.msg('请先选择物品')
		        row.num = ''
		    }
		   
		}
	}
}
</script>

<style lang="scss" scoped>
	.disflex-center {
		display: flex;
		justify-content: center;
		align-items: center;
	}
	.disflex-right {
		display: flex;
		justify-content: right;
		align-items: center;
	}
.page-container {
	
	font-size: 28rpx;
	min-height: 100%;
	position: relative;
	// padding-bottom: 60rpx;
	
	.box {
		margin: 20rpx;
		border-radius: 10rpx;
		background: #fff;
	}
	.page-body {
		padding-bottom: 120rpx;
	}
	.page-footer {
		padding: 0rpx 0;
		position: fixed;
		width: 100%;
		left: 0;
		bottom: 0;
	}
}	


::v-deep {
	
	.u-form-item__body {
		padding: 0;
	}
	.hidde-cell-title {
		
		.u-cell__body__content {
			width: auto;
			flex: none;
			
		}
		.u-cell__body {
			.value {
				flex: 1;
			}
		}
		
	}
	
}
</style>
