<template>
	<el-dialog
		title="新建报工"
		v-model="visible"
		style="width: 80%;"
		destroy-on-close
		:close-on-click-modal="false"
		@closed="$emit('closed')"
	>
		<el-container v-loading="loading">
			<el-main>
				<el-form
					ref="dialogForm"
					:model="form"
					:rules="rules"
					label-position="right"
					label-width="100px"
					style="padding: 0 10px"
				>
					<el-row>
						<el-col>
							<el-form-item label="扫码：">
								<el-input 
									ref="codeInput" 
									v-model="wm_in" 
									clearable 
									@change="formWminChange(wm_in)" 
									style="width: 100%;top: -7px;"
								></el-input>
								<span style="color: red;line-height: 12px;font-size: 14px;">*请扫同一批次的物料码</span>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row>
						<el-col :md="12" :sm="12" :xs="24">
							<el-form-item label="处理人：">
								{{ form.handle_user_name }}
							</el-form-item>
						</el-col>
						<el-col :md="12" :sm="12" :xs="24">
							<el-form-item label="处理时间：">
								<el-date-picker
									v-model="form.work_start_time"
									type="datetime"
									value-format="YYYY-MM-DD HH:mm:ss"
									style="width: 100%"
									popper-append-to-body
									@change="workStartTimeChange"
								/>
							</el-form-item>
						</el-col>
						<el-col :md="12" :sm="12" :xs="24">
							<el-form-item label="物料批号：">
								{{ form.batch }}
							</el-form-item>
						</el-col>
						<el-col :md="12" :sm="12" :xs="24">
							<el-form-item label="领用数量：">
								<el-input-number v-model="form.count_use" :disabled="materialTracking==20" style="width: 100%;"></el-input-number>
							</el-form-item>
						</el-col>
						<el-col :md="12" :sm="12" :xs="24" v-if="route_code=='ladansi'||route_code=='yicifusi'||route_code=='ercifusi'||route_code=='zlybcl'">
							<el-form-item label="生产设备" prop="equipment">
								<el-select
									v-model="form.equipment"
									placeholder="生产设备"
									clearable
									filterable
									style="width: 100%"
								>
									<el-option
										v-for="item in options"
										:key="item.id"
										:label="item.label"
										:value="item.id"
									>
									<span style="float:left">{{item.name}}</span>
									<span style="float:right">{{item.number}}</span>
									</el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :md="12" :sm="12" :xs="24">
							<el-form-item label="工艺路线：">
								<el-select
									v-model="form.route"
									placeholder="工艺路线"
									clearable
									style="width: 100%"
								>
									<el-option
										v-for="item in routeOptions"
										:key="item.id"
										:label="item.name"
										:value="item.id"
									></el-option>
								</el-select>
							</el-form-item>
						</el-col>
					</el-row>
				</el-form>
			</el-main>
			<el-footer>
				<el-button type="primary" :loading="isSaveing" @click="submit">保存</el-button>
				<el-button @click="visible = false">取消</el-button>
			</el-footer>
		</el-container>
	</el-dialog>
</template>

<script>
const defaultForm = {
	batch: "",
	wm_in: "",
	mgroup:'',
	count_use: "",
	handle_user: "",
	is_fix:false,
	handle_user: null,
	handle_user_name: "",
	work_start_time: "",	
};

export default {
	props: {
		process: {
			type: String,
			default: "",
		},
		mgroupName:{
			type: String,
			default: "",
		},
		mgroup: {
			type: String,
			default: "",
		},
		dept: {
			type: String,
			default: "",
		},
		mgroupMtype: {
		    type: String,
			default: "",
		}
	},
	emits: ["success", "closed"],

	data() {
		return {
			loading: false,
			mode: "add",
			//表单数据
			form: Object.assign({}, defaultForm),
			//验证规则
			rules: {
				supplier: [
					{
						required: true,
						message: "请选择供应商",
						trigger: "blur",
					},
				],
				equipment: [
					{
						required: true,
						message: "请选择生产设备",
						trigger: "blur",
					},
				],
			},
			wm_in: "",
			route_code:"",
			visible: false,
			isSaveing: false,
			batchCountCando:0,
			materialTracking:10,
			options: [],
			bwItemForms: [],
			routeOptions: [],
			materialOptions: [],
			routeOriginOptions: [],
		};
	},
	mounted() {
		this.route_code = this.$route.path.split("/")[2];
		this.form.handle_date = this.$TOOL.dateFormat2(new Date());
		this.form.work_start_time = this.$TOOL.dateFormat(new Date());
		this.form.mgroup = this.mgroup;
		this.getMaterial();
		this.getRoute();
		this.getEquipment();
	},
	methods: {
		//获取工艺步骤
		getRoute() {
			let that = this;
			this.$API.mtm.route.list.req({ process: that.process, page: 0, routepack__state: 30 }).then((res) => {
				this.routeOriginOptions = res;
			});
		},
		//获取拉丝设备
		getEquipment() {
			let that = this;
			this.$API.em.equipment.list.req({ page: 0, type: 10,mgroup:that.mgroup}).then((res) => {
				res.forEach((item) => {
					let obj = {};
					Object.assign(obj, item);
					obj.label = item.name+'-'+item.number;
					that.options.push(obj);
				});
			});
		},
		//显示
		open(mode = "add") {
			let that = this;
			this.mode = mode;
			if(mode == "add"){
				let userInfo = that.$TOOL.data.get("USER_INFO");
				this.form.handle_user = userInfo.id;
				this.form.handle_user_name = userInfo.name;
			}
			this.visible = true;
			return this;
		},
		workStartTimeChange(){
			let date = new Date(this.form.work_start_time);
			this.form.handle_date = this.$TOOL.dateFormat2(date);
		},
		//获取车间物料
		getMaterial() {
			let that = this;
			let obj = {};
			obj.mgroupx =that.mgroup;
			obj.tag = 'todo';
			obj.page =0;
			this.$API.wpm.wmaterial.list.req(obj).then((res) => {
				let arr = [];
				if(res.length>0){
					arr = res.filter((item)=>{
						return Number(item.count_cando)>0;
					})
				}
				that.materialOptions = arr;
			});
		},
		//扫描后处理方法
		// 扫描后会有两种情况，一种是扫描物料，一种是扫描用户；物料扫描后需要判断
		formWminChange(code){
			console.log('code',code);
			let that = this,codeId='',arr=[];
			code = code.replace(/(^\s*)|(\s*$)/g, "");
			if(code.indexOf("#")>-1){
				let arrs = code.split("#");
				codeId = arrs[1];
				that.scanKyes = arrs[0];
				if(that.scanKyes=="user"){
					//请求用户信息
					that.$API.system.user.item.req(codeId).then((res) => {
						that.form.handle_user = res.id;
						that.form.handle_user_name = res.name;
						that.wm_in = '';
					}).catch((err) => {
					    that.wm_in = '';
					})
				}else if(that.scanKyes=="mat"){
					//请求物料信息
					this.$API.cm.labelmat.item.req(codeId).then((res) => {
						if(res){
							arr = that.materialOptions.filter((item) => {
								return item.batch == res.batch&&item.state==res.state;
							})
							that.wm_in = '';
							if (arr.length > 0) {
								that.form.batch = arr[0].batch;
								that.form.wm_in = arr[0].id;
								that.form.count_use = arr[0].count_cando;
								that.wm_in = arr[0].batch;
								that.batchCountCando = Number(arr[0].count_cando);;
								that.materialTracking = arr[0].material_.tracking;
								if(that.routeOptions.length==0){
									that.routeOriginOptions.forEach((item)=>{
										if(item.material_in==arr[0].material){
											that.routeOptions.push(item);
										}
									})
									if(that.routeOptions.length==1){
										that.form.route = that.routeOptions[0].id;
									}
								}
							}else{
								that.$message.error("批次号不存在，或没有可操作数量");
							}
						}else{
							that.wm_in = '';
							that.$message.error("批次号不存在");
						}
					}).catch((err) => {
						that.wm_in = '';
						that.$message.error("批次号不存在");
					});
				}
			}else{
				//单个物料
				that.scanKyes = "";
				that.$API.wpm.wpr.list.req({number:code,page:0}).then((res) => {
					if(res.length>0){
						let index = res.length-1;//最后一条记录
						let bwitem = {};
						bwitem.mlogb="";
						bwitem.number=res[index].number;
						bwitem.wpr=res[index].id;
						if(that.routeOptions.length==0){
							that.routeOriginOptions.forEach((item)=>{
								if(item.material_in==res[index].material){
									that.routeOptions.push(item);
								}
							})
							if(that.routeOptions.length==1){
								that.form.route = that.routeOptions[0].id;
							}
						}
						let arr = that.materialOptions.filter((item) => {
							return item.id == res[index].wm;
						})
						if(arr.length>0){ //车间存在该物料的批次
							let batch = arr[0].batch;
							if(that.form.batch==''||that.form.batch==batch){
								that.form.batch = batch;
								that.form.wm_in = arr[0].id;
								that.batchCountCando = Number(arr[0].count_cando);
								that.materialTracking = arr[0].material_.tracking;
								let arr1 = that.bwItemForms.filter((item)=>{
									return item.number == bwitem.number;
								})
								if(arr1.length>0){
									that.wm_in = '';
									that.$message.warning("该物料已存在");
								}else{
									that.bwItemForms.push(bwitem);
									that.form.count_use += 1;
									that.wm_in = '';
								}
							}else{
								that.$message.error("请扫同一批次物料");
							}
						}else{
							that.wm_in = '';
							that.$message.error("批次号不存在");
						}
					}else{
						that.wm_in = '';
						that.$message.error("该物料不存在");
					}
				})
			}
		},
		//表单提交方法
		submit() {
			let that = this;
			that.$refs.dialogForm.validate(async (valid) => {
				if (valid) {
					that.isSaveing = true;
					that.form.mgroup = that.mgroup;
					that.$API.wpm.mlog.quick.req(that.form).then((res) => {
						if(that.bwItemForms.length>0&&that.batchCountCando!==that.bwItemForms.length){
							that.bwItemForms.forEach(item=>{
								item.mlogb = res.mlogbin;
							})
							that.$API.wpm.mlogbw.create.req(that.bwItemForms).then((res1) => {
								that.isSaveing = false;
								that.$emit("success",res.mlog);
								that.visible = false;
								that.$message.success("操作成功");
							})
						}else{
							that.isSaveing = false;
							that.$emit("success",res.mlog);
							that.visible = false;
							that.$message.success("操作成功");
						}
					}).catch(()=>{
						that.isSaveing = false;
					});
				}
			});
		},
		//设置过滤项
		setFilters(filters) {
			this.selectionFilters = filters;
		},
	},
};
</script>

<style>
</style>
