<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 :span="scanColSpan">
							<el-form-item label="扫码：">
								<el-input
									class="inputWrap"
									ref="codeInput"
									v-model="wm_in"
									clearable
									@change="formWminChange(wm_in)"
									style="width: 100%;ime-mode:active"
								></el-input>
								<span style="color: red;line-height: 12px;font-size: 14px;">*请扫同一批次的物料码</span>
							</el-form-item>
						</el-col>
						<el-col :span="2" v-if="project_code!=='bxerp'">
							<scScanner style="top: -7px" @scanResult="codeTextChange"></scScanner>
						</el-col>
						<el-col :span="4" v-if="route_code=='niuzhuan'">
							<el-button type="success" @click="digital" style="margin-top: 3px;margin-left: 5px;">数字识别</el-button>
						</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="base_code=='tcerp'||route_code=='ladansi'||route_code=='yicifusi'||route_code=='ercifusi'||route_code=='zlybcl'||route_code=='djg'||route_code=='cnc'">
							<el-form-item label="生产设备" :prop="base_code!=='tcerp' ? 'equipment' : null">
								<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" v-for="item in testitems" :key="item.id">
							<el-form-item :label="item.name">
								<el-input-number
									v-if="item.field_type=='input-number'"
									v-model="item.value"
									:min="0"
									class="width-100"
									controls-position="right"
								>
								</el-input-number>
								<el-input-number
									v-if="item.field_type=='input-int'"
									v-model="item.value"
									:min="0"
									class="width-100"
									controls-position="right"
								>
								</el-input-number>
								<el-input
									v-if="item.field_type=='input-text'"
									v-model="item.value"
									class="width-100"
								>
								</el-input>
								<el-select
									v-if="item.field_type=='select-text'"
									v-model="item.value"
									clearable
									class="width-100"
								>
									<el-option
										v-for="item0 in item.choices"
										:key="item0"
										:label="item0"
										:value="item0"
									>
									</el-option>
								</el-select>
								<el-select
									v-if="item.field_type=='selects-text'"
									v-model="item.value"
									clearable
									multiple
									class="width-100"
								>
									<el-option
										v-for="item1 in item.choices"
										:key="item1"
										:label="item1"
										:value="item1"
									>
									</el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :md="12" :sm="12" :xs="24">
							<el-form-item label="工艺路线：" prop="route">
								<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-col :md="12" :sm="12" :xs="24">
							<el-form-item label="绑定任务：">
								<el-select
									v-model="form.mtask"
									placeholder="绑定任务"
									clearable
									style="width: 100%"
								>
									<el-option
										v-for="item in mtaskOptions"
										:key="item.id"
										:label="item.number"
										:value="item.id"
									></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :md="12" :sm="12" :xs="24" v-if="route_code=='paiyicibang'&&imageUrl!==''">
							<el-form-item label="工艺图纸">
								<el-image
									style="width: 100px; height: 100px"
									:src="imageUrl"
									fit="fill"
								/>
							</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"],
	computed: {
		scanColSpan(){
			let span = this.project_code!=='bxerp' ? 22 : 24;
			if(this.route_code=='niuzhuan'){
				span -= 4;
			}
			return span;
		},
	},
	data() {
		return {
			loading: false,
			mode: "add",
			//表单数据
			form: Object.assign({}, defaultForm),
			//验证规则
			rules: {
				supplier: [
					{
						required: true,
						message: "请选择供应商",
						trigger: "blur",
					},
				],
				equipment: [
					{
						required: true,
						message: "请选择生产设备",
						trigger: "blur",
					},
				],
				route: [
					{
						required: true,
						message: "请选择工艺路线",
						trigger: "blur",
					},
				],
			},
			wm_in: "",
			route_code:"",
			imageUrl:'',
			test_file:'',
			project_code:'',
			ocr_ip:"",
			ocr_port:"",
			ocr_unit:"",
			visible: false,
			isSaveing: false,
			batchCountCando:0,
			materialTracking:10,
			fileList:[],
			testitems:[],
			options: [],
			mtaskOptions:[],
			bwItemForms: [],
			routeOptions: [],
			materialOptions: [],
			routeOriginOptions: [],
			base_code: this.$TOOL.data.get('BASE_INFO').base.base_code,
		};
	},
	mounted() {
		let that = this;
		let config_base = that.$TOOL.data.get("BASE_INFO").base;
		that.project_code = config_base.base_code;
		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();
		this.gettestitem();
		this.getMtask();
		if(that.route_code=='tuomoceliang'){
			//获取指定工序的切分数量
		}
		if(that.mode=='add'){
			that.$API.ops.server_time.get.req().then((res) => {
				that.form.work_start_time = res.server_time;
			})
		}
		setTimeout(()=>{
		    let inputDom = document.querySelectorAll('.inputWrap .el-input__wrapper .el-input__inner');
			inputDom.forEach(function(input) {
				input.addEventListener("compositionstart", function() {
					that.$message.warning("您的输入法为中文，请切换到英文输入法");
				});
			});
		},500)
		that.ocr_ip = localStorage.getItem("ocr_ip") || "";
		that.ocr_port = localStorage.getItem("ocr_port") || "";
		that.ocr_unit = localStorage.getItem("ocr_unit") || "";
	},
	methods: {
		//获取工艺步骤
		getRoute() {
			let that = this;
			this.$API.mtm.route.list.req({ process: that.process, page: 0, routepack__state: 30 ,from_route__isnull:true }).then((res) => {
				this.routeOriginOptions = res;
			});
		},
		getMtask(){
			let that = this;
			this.$API.pm.mtask.list.req({ page: 0, mgroup: that.mgroup, state: 20 }).then((res) => {
				that.mtaskOptions = res;
			});
		},
		//获取班组设备
		getEquipment() {
			let that = this;
			this.$API.em.equipment.list.req({ page: 0, type: 10,belong_dept:that.dept}).then((res) => {
				res.forEach((item) => {
					let obj = {};
					Object.assign(obj, item);
					obj.label = item.name+'-'+item.number;
					that.options.push(obj);
				});
			});
		},
		gettestitem(){
			let that = this;
			that.$API.qm.testitem.list.req({ process: that.process,type:20 }).then((res) => {
				res.results.forEach((item) => {
					let obj = {};
					Object.assign(obj, item);
					obj.value = null;
				    that.testitems.push(obj);
				})
			});
		},
		codeTextChange(text){
			this.wm_in = text;
			this.formWminChange(text);
		},
		digital(){
			let that = this;
			if(!that.ocr_ip || !that.ocr_port || !that.ocr_unit){
				that.$message.warning('请先在右上角"数字识别设置"配置IP、端口号和位号');
				return;
			}
			that.$API.em.equipment.get_svs_char.req({
				host: that.ocr_ip,
				port: that.ocr_port,
				flow_unit: that.ocr_unit
			}).then((res) => {
				if(res.char){
					that.wm_in = res.char;
					that.formWminChange(res.char);
				}
			}).catch((err) => {
				that.$notify.error({
					title: '数字识别获取失败',
					message: err.data
				})
				return err;
			});
		},
		//显示
		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){
			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;
										that.routeChange();
									}
								}
							}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;
								that.routeChange();
							}
						}
						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("该物料不存在");
					}
				})
			}
		},
		routeChange(){
			let that = this;
			if(that.route_code=='paiyicibang'){
				that.$API.mtm.route.item.req(that.form.route).then((res) => {
					let json = res.params_json;
					if(json.fileurl){
						let fileurl = JSON.parse(json.fileurl);
						that.imageUrl = fileurl[0].path;
					}
				})		
			}
		},
		//表单提交方法
		submit() {
			let that = this;
			that.$refs.dialogForm.validate(async (valid) => {
				if (valid) {
					that.isSaveing = true;
					that.form.mgroup = that.mgroup;
					if(that.testitems.length>0){
						let oinfo_json = {};
						that.testitems.forEach((item) => {
							oinfo_json[item.id] = item.value;
						})
						that.form.oinfo_json = oinfo_json;
					}
					if(that.bwItemForms.length>0){
						let wprs_in = [];
						that.bwItemForms.forEach(item=>{
							wprs_in.push(item.wpr);
						})
						that.form.wprs_in = wprs_in;
					}
					that.$API.wpm.mlog.quick.req(that.form).then((res) => {
						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>
