<template>
	<el-drawer
		v-model="visible"
		title="出入库记录"
		:size="'95%'"
		destroy-on-close
		@closed="$emit('closed')"
	>
		<div style="padding: 8px">
			<div>
				<el-card style="width: 100%" header="基本信息" shadow="hover">
					<el-button type="primary" @click="handlePrint" style="position: absolute;right: 40px;">打印</el-button>
					<el-descriptions>
						<el-descriptions-item label="编号">{{mioObj.number}}</el-descriptions-item>
						<el-descriptions-item label="出入库类型">{{typeDict[mioObj.type]}}</el-descriptions-item>
						<el-descriptions-item label="状态">{{stateDict[mioObj.state]}}</el-descriptions-item>
						<el-descriptions-item label="部门/车间">{{mioObj.belong_dept_name}}-{{ mioObj.mgroup_name }}</el-descriptions-item>
						<el-descriptions-item label="执行人">
							<span v-if="mioObj.do_user_name!==null">{{mioObj.do_user_name}}</span>
							<span v-if="mioObj.mio_user_name!==null">{{mioObj.mio_user_name}}</span>
						</el-descriptions-item>
						<el-descriptions-item label="创建时间">{{mioObj.create_time}}</el-descriptions-item>
						<el-descriptions-item
							label="采购订单"
							v-if="mioObj.type == 'pur_in'"
							>{{ mioObj.pu_order_number }}</el-descriptions-item
						>
						<el-descriptions-item
							label="供应商"
							v-if="mioObj.type == 'pur_in'"
							>{{ mioObj.supplier_name }}</el-descriptions-item
						>
						<el-descriptions-item
							label="销售订单"
							v-if="mioObj.type == 'sale_out'"
							>{{ mioObj.order_number }}</el-descriptions-item
						>
						<el-descriptions-item
							label="客户"
							v-if="mioObj.type == 'sale_out'"
							>{{ mioObj.customer_name }}</el-descriptions-item
						>
					</el-descriptions>
					<div v-if="mioObj.type == 'sale_out'&&project_code=='bxerp'">
						<span v-if="indexArr.length>0" style="font-size: 14px;">大箱标签：</span>
						<el-button type="primary" line v-for="item in indexArr" :key="item" @click="printSaleOut(mioObj,'out',item)">第{{ item }}箱</el-button>
					</div>
				</el-card>
			</div>
			<div style="height: 8px"></div>
			<div>
				<el-card style="width: 100%" header="物料明细" shadow="hover">
					<div>
						<el-button
							type="primary"
							icon="el-icon-plus"
							@click="table_add"
							v-if="mioObj.state == 10&&mode!=='show'"
						>新增</el-button>
						<el-button
							type="primary"
							icon="el-icon-message-box"
							@click="table_pack"
							v-if="mioObj.state == 10&&mode!=='show'&&type=='sale_out'&&project_code=='bxerp'"
						>装箱</el-button>
						<scFileImport
							v-if="mioObj.state == 10&&mode!=='show'"
							:templateUrl="mioitemT"
							:name = "'导入明细'"
							accept=".xlsx"
							:apiObj="$API.common.upload"
							@success="upSuccess1"
						>
						</scFileImport>
					</div>
					<div style="height: 8px"></div>
					<scTable
						ref="table"
						:apiObj="apiObj"
						row-key="id"
						stripe
						:params="params"
						hidePagination
						hideDo
						@row-click="rowClick"
						@selection-change="selectionChange"
						:summary-method="getSummaries" 
						show-summary
					>
						<el-table-column type="selection" width="50" />
						<el-table-column type="index" width="50" />
						<el-table-column label="物料" prop="material" show-overflow-tooltip>
							<template #default="scope">{{ scope.row.material_name }}</template>
						</el-table-column>
						<el-table-column label="批次号" prop="batch">
						</el-table-column>
						<el-table-column label="大箱序号" prop="pack_index" v-if="project_code=='bxerp'&&mioObj.type == 'sale_out'">
						</el-table-column>
						<el-table-column label="仓库" prop="warehouse_name">
						</el-table-column>
						<el-table-column label="数量">
							<template #default="scope">
								<span v-if="scope.row.material_&&scope.row.material_.tracking==10">{{ project_code=='gx'?Math.round(scope.row.count):scope.row.count }}</span>
								<el-link v-else :underline="false" type="primary" @click="showWpr(scope.row)">{{scope.row.count}}</el-link>
							</template>
						</el-table-column>
						<el-table-column label="检验" prop="count_tested" v-if="cate=='mainso'&&project_code=='gzerp'">
						</el-table-column>
						<el-table-column label="发出数量" prop="count_send" v-if="mioObj.type == 'sale_out'&&project_code=='gx'">
						</el-table-column>
						<el-table-column label="样品数量" v-if="mioObj.type == 'sale_out'&&project_code=='gx'">
							<template #default="scope">
								{{ Number(scope.row.count) - Number(scope.row.count_send) }}
							</template>
						</el-table-column>
						<el-table-column
							label="组合件信息"
							v-if="cate == 'good'"
							width="300"
						>
							<template #default="scope">
								<div v-if="scope.row.assemb.length > 0">
									<div
										v-for="item in scope.row.assemb"
										:key="item.id"
									>
										<div>
											{{ item.material_name }}
											<span
												style="
													color: gray;
													font-size: 12px;
												"
												>批:</span
											>{{ item.batch }}
											<span
												style="
													color: gray;
													font-size: 12px;
												"
												>比:</span
											>{{ item.rate }}
										</div>
									</div>
								</div>
							</template>
						</el-table-column>
						<el-table-column label="检验" prop="count_tested" v-if="cate=='mainso'">
						</el-table-column>
						<el-table-column label="不合格数量" prop="count_notok" v-if="cate!=='helpso'">
						</el-table-column>
						<el-table-column label="创建时间" prop="create_time" show-overflow-tooltip>
						</el-table-column>
						<el-table-column label="操作"
							fixed="right"
							align="center"
							width="150px"
							v-if=" mode!=='show'"
						>
							<template #default="scope">
								<el-button
									link
									type="primary"
									@click="table_check(scope.row)"
									v-if="project_code=='bxerp'&&mioObj.state == 10 &&
										(type == 'pur_in' ||type == 'do_in' ||type == 'other_in')"
									v-auth="'mioitem.test'"
								>检验</el-button>
								<scFileImport
									v-if="project_code=='bxerp'&&mioObj.state == 10 &&(type == 'pur_in' ||type == 'do_in' ||type == 'other_in')"
									:templateUrl="checkTemplate"
									accept=".xlsx"
									:apiObj="$API.common.upload"
									@success="upSuccess"
								></scFileImport>
								<el-button
									link
									type="primary"
									@click="table_check(scope.row)"
									v-if="scope.row.test_date == null &&mioObj.state == 20 &&(type == 'pur_in' ||type == 'do_in' ||type == 'other_in')"
									v-auth="'mioitem.test'"
								>检验</el-button>
								<el-button
									link
									type="primary"
									@click="check_Show(scope.row)"
									v-if="scope.row.test_date !== null"
								>查看</el-button>
								<el-button
									link
									type="danger"
									@click="check_reSet(scope.row)"
									v-if="scope.row.test_date !== null"
								>检验作废</el-button>
								<el-button
									link
									type="danger"
									@click="table_del(scope.row)"
									v-if="mioObj.state == 10"
								>删除</el-button>
								<el-link
									type="primary"
									v-if="mioObj.type == 'do_out'"
									@click="printMaterial(scope.row,'mioitem')"
								>物料标签</el-link>
								<el-link
									type="primary"
									v-if="mioObj.state == 20&&mioObj.type == 'sale_out'"
									@click="printSaleOut(scope.row,'in')"
								>发货标签</el-link>
								<el-button
									link
									type="danger"
									@click="check_revert(scope.row)"
									v-if="mioObj.state == 20&&(mioObj.type=='do_out'||mioObj.type=='other_in'||mioObj.type=='pur_in')"
									v-auth="'mio.update'"
								>撤回</el-button>
							</template>
						</el-table-column>
					</scTable>
				</el-card>
			</div>
		</div>
	</el-drawer>
	<save-dialog
		v-if="dialog.save"
		ref="saveDialog"
		:mioId="mioId"
		:mgroup="mioObj.mgroup"
		:belongDeptId="belongDeptId"
		:belongDeptName="mioObj.belong_dept_name"
		:mioObj="mioObj"
		:tableDatas="tableDatas"
		:cate="cate"
		@success="handleSaveSuccess"
		@closed="dialog.save = false"
	>
	</save-dialog>
	<pack-dialog
		v-if="dialog.pack"
		ref="packDialog"
		:mioObj="mioitemObj"
		:type="packType"
		@success="handlePackSuccess"
		@closed="dialog.pack = false"
	>
	</pack-dialog>
	<check-dialog
		v-if="dialog.check"
		ref="checkDialog"
		:mioitemId="mioitemId"
		:cate="cate"
		:type="type"
		:objitem="objitem"
		@success="handleCheckSuccess"
		@closed="checkDialogClose"
	>
	</check-dialog>
	<el-dialog v-model="printVisible" width="1200px">
		<print :baseData="mioObj" :tableData="tableData" :type="mioObj.type" @closePrint="printVisible=false"/>
	</el-dialog>
	<el-drawer v-model="wprVisibleDrawer" :size="'70%'">
		<template #header>
			<h4>关联产品</h4>
		</template>
		<template #default>
			<scTable ref="wprTable" hidePagination :data="wprList">
				<el-table-column label="产品编号" prop="number" min-width="100px"></el-table-column>
				<el-table-column v-if="project_code=='bxerp'&&mioObj.type == 'sale_out'" label="发货编号" prop="number_out" min-width="100px"></el-table-column>
				<el-table-column
					label="操作"
					fixed="right"
					align="center"
					width="120"
				>
					<template #default="scope">
						<el-link :underline="false" v-if="mioObj.type == 'do_out'" @click="printMaterial(scope.row,'wpr')" type="primary">打印标签</el-link>
					</template>
				</el-table-column>
			</scTable>
		</template>
		<template #footer>
		<div style="flex: auto">
			<el-button @click="wprVisibleDrawer=false">关闭</el-button>
		</div>
		</template>
	</el-drawer>
	<el-dialog title="发货装箱" v-model="showPack">
		<el-form label-width="80px">
			<el-form-item label="大箱序号">
				<el-input-number  precision="0" v-model="pack_index"></el-input-number>
			</el-form-item>
		</el-form>
		<template #footer>
			<el-button @click="packSure">确定</el-button>
		</template>
	</el-dialog>
	<el-dialog title="打印机设置" v-model="setNameVisible" width="600px">
		<el-form label-width="100px">
			<el-form-item label="打印机名称">
				<el-input v-model="printer_name"></el-input>
			</el-form-item>
		</el-form>
		<el-footer>
			<el-button type="primary" @click="savePrinter">保存</el-button>
		</el-footer>
	</el-dialog>
</template>
<script>
import { ElLoading } from "element-plus";
import saveDialog from "./mioitem_form.vue";
import packDialog from "./packPrint_form.vue";
import checkDialog from "./mioitem_check.vue";
import print from "./../setting/print/A4.vue";
import scFileImport from "@/components/scFileImport";
export default {
	name: "mioitem",
	components: {
		saveDialog,
		packDialog,
		checkDialog,
		scFileImport,
		print
	},
	props: {
		type: {
			type: String,
			default: "",
		},
		cate: {
			type: String,
			default: "",
		},
		mioId: {
			type: String,
			default: "",
		},
	},
	data() {
		return {
			mode:"add",
			dialog: {
				check: false,
				save: false,
				pack: false,
			},
			apiObj: null,
			params: {},
			mioObj: {},
			mioitemObj: {},
			wprList:[],
			indexArr:[],
			selection: [],
			tableData:[],
			tableDatas:[],
			mioitemIds:[],
			stateDict: {
				10: "创建中",
				20: "已提交",
			},
			typeDict: {
				do_out: "生产领料",
				sale_out: "销售发货",
				pur_in: "采购入库",
				do_in: "生产入库",
				other_in: "其他入库",
				other_out: "其他出库",
			},
			showPack:false,
			visible: false,
			printVisible:false,
			mioitemId: "",
			packType: "in",
			// type: "",
			// cate: "",
			objitem: {},
			mtype:10,
			pack_index:1,
			mioType:'',
			project_code:'',
			setNameVisible:false,
			wprVisibleDrawer:false,
			printer_name:localStorage.getItem("printer_name"),
			checkTemplate: " /media/default/template/mioitemw_t.xlsx",
			mioitemT: "/media/default/template/出入库明细.xlsx"
		};
	},
	mounted() {
		let url1 = window.location.hash;
		this.url_code = url1.split('/')[2];
		this.checkTemplate = this.checkTemplate+"?t=" + new Date().getTime();
		this.project_code = this.$TOOL.data.get("BASE_INFO").base.base_code;
		this.params.mio = this.mioId;
		this.apiObj = this.$API.inm.mioitem.list;
		this.getMio();
		sessionStorage.removeItem('mioitemSelecObj');
	},
	methods: {
		printSetting(){
			this.setNameVisible = true;
		},
		savePrinter() {
			let that = this;
			localStorage.setItem("printer_name", that.printer_name);
			that.setNameVisible = false;
			that.$message.success("打印机设置成功，请重新进行打印操作。");
		},
		open(mode='add') {
			this.mode = mode;
			this.visible = true;
		},
		getMio() {
			let that = this;
			that.$API.inm.mio.item.req(that.mioId).then((res) => {
				that.mioObj = res;
				that.mioType = res.type;
				that.belongDeptId = res.belong_dept;
				let items = res.items;
				let indexArr = [];
				items.forEach((item)=>{
					if(indexArr.indexOf(item.pack_index) == -1){
						indexArr.push(item.pack_index);
					}
				})
				that.indexArr = indexArr;
			});
		},
		//添加
		table_add() {
			let that = this;
			let tableData = this.$refs.table.tableData;
			let datas = [];
			tableData.forEach(item => {
				let obj = {};
				obj.batch = item.batch;
				obj.count = Number(item.count);
				datas.push(obj);
			});
			that.tableDatas = datas;
			this.dialog.save = true;
			this.$nextTick(() => {
				this.$refs.saveDialog.open("add", that.mioType);
			});
		},
		//表格选择后回调事件
		selectionChange(selection) {
			let that = this;
			that.mioitemIds = [];
			that.selection = selection;
			selection.forEach((item)=>{
				that.mioitemIds.push(item.id);
			});
		},
		//装箱
		table_pack(){
			let that = this;
			that.showPack = true;
		},
		packSure(){
			let that = this;
			let params = {
			    mioitems: that.mioitemIds,
				pack_index:that.pack_index,
			}
			that.$API.inm.mio.packmioitem.req(that.mioObj.id,params).then((res) => {
				that.$message.success("装箱成功");
				that.showPack = false;
				that.getMio();
				that.$refs.table.refresh();
			});
		},
		//删除
		table_del(row) {
			this.$confirm(`确定删除吗？`, "提示", {
				type: "warning",
			}).then(() => {
				this.$API.inm.mioitem.delete.req(row.id).then((res) => {
					this.$message.success("删除成功");
					this.$refs.table.refresh();
					return res;
				}).catch((err) => {
					return err;
				});
			}).catch(() => {});
		},
		//撤回并删除
		check_revert(row){
			let that = this;
			that.$confirm(`该记录已提交，确定撤回吗？`, "提示", {
				type: "warning",
			}).then(() => {
				console.log('确定删除');
				that.$API.inm.mioitem.revertDel.req(row.id).then((res) => {
					that.$message.success("撤回成功");
					that.$refs.table.refresh();
				}).catch((err) => {
					return err;
				});
			}).catch(() => {});
		},
		//检验
		table_check(row) {
			this.mioitemId = row.id;
			this.objitem = row;
			this.dialog.check = true;
			this.$nextTick(() => {
				this.$refs.checkDialog.open("add").setData(row);
			});
		},
		//查看
		check_Show(row) {
			this.mioitemId = row.id;
			this.objitem = row;
			this.dialog.check = true;
			this.$nextTick(() => {
				this.$refs.checkDialog.open("show").setData(row);
			});
		},
		//编辑
		check_edit(row) {
			this.mioitemId = row.id;
			this.objitem = row;
			this.dialog.check = true;
			this.$nextTick(() => {
				this.$refs.checkDialog.open("edit").setData(row);
			});
		},
		//撤回
		check_reSet(row) {
			this.$confirm(`确定撤回吗？`, "提示", {
				type: "warning",
			}).then(() => {
				this.$API.inm.mioitem.test_revert.req(row.id).then((res) => {
					this.$message.success("撤回成功");
					this.$refs.table.refresh();
				});
			});
		},
		//本地更新数据
		handleSaveSuccess(data, mode) {
			this.getMio();
			this.$refs.table.refresh();
		},
		handlePackSuccess(){},
		handleCheckSuccess() {
			this.$refs.table.refresh();
			this.dialog.check = false;
		},
		handleQuery() {
			this.$refs.table.queryData(this.query);
		},
		resetQuery() {
			this.query = {};
		},
		mioSubmit() {
			this.$API.inm.mio.submit.req(this.mioObj.id).then((res) => {
				this.$message.success("提交成功");
				this.mioObj = res;
			});
		},
		checkDialogClose(){
			let that = this;
			that.dialog.check = false;
			that.$refs.table.refresh();
		},
		handlePrint(){
			let that = this;
			let params = {
				mio: that.mioId,
				page:0
			}
			that.$API.inm.mioitem.list.req(params).then((res) => {
				that.tableData = res;
				that.printVisible = true;
			})
		},//打印
		showWpr(row){
			let that = this;
			that.printMaterialName = row.material_name;
			that.wprList = row.mioitemw;
			that.wprVisibleDrawer = true;
		},
		rowClick(row){
			this.mioitemId = row.id;
		},
		upSuccess(res, close) {
			let that = this;
			close();
			const loading = ElLoading.service({
				fullscreen: true,
				text: "解析中...请稍等",
			});
			console.log(res);
			this.$API.inm.mioitem.test_daoru.req(that.mioitemId,{ path: res.path }).then((res) => {
					loading.close();
					this.$message.success("导入成功");
					this.$refs.table.queryData(this.query);
				}).catch((err) => {
					loading.close();
					this.$message.error("导入失败，请重新尝试");
				});
		},
		//打印物料标签
		printMaterial(row,type){
			console.log('打印物料标签',row);
			let that = this;
			let is_mainso = this.url_code.includes('mainso');
			if(that.printer_name!==''&&that.printer_name!==null&&that.printer_name!==undefined){
				if(type=='mioitem'){
					let params = {};
					params.tid = row.id;
					params.extra_data={count:row.count};
					params.label_template_name = '库存标签模板';
					that.$API.cm.labelmat.fromMioitem.req(params).then((res) => {
						let obj = {};
						obj.printer_commands = res.commands;
						obj.printer_name = that.printer_name;
						that.$API.wpm.prints.req(obj).then((response) => {
							that.$message.success("打印成功");
						});
					})
				}else{
					let params = {};
					let name = that.printMaterialName.split('|')[0];
					params.label_template_name = is_mainso?'原料单件打印模板': '单件打印模板';
					params.data = {number:row.number,name:name,oname:that.printMaterialName};
					that.$API.cm.labeltemplate.commands.req(params).then((res) => {
						let obj = {};
						obj.printer_commands = res.commands;
						obj.printer_name = that.printer_name;
						that.$API.wpm.prints.req(obj).then((response) => {
							that.$message.success("打印成功");
						});
					});
				}
			}else{
				that.printSetting();
			}
		},
		printSaleOut(row,type,index){
			let that = this;
			that.packType = type;
			that.mioitemObj = row;
			this.dialog.pack = true;
			that.$nextTick(() => {
				let total = that.indexArr.length;
				that.$refs.packDialog.open(index,total);
			});
		},
		upSuccess1(res, close) {
			var that = this;
			close();
			const loading = ElLoading.service({
				fullscreen: true,
				text: "解析中...请稍等",
			});
			this.$API.inm.mio.daorumioitem.req(that.mioId, { path: res.path }).then((res) => {
				loading.close();
				this.$message.success("导入成功");
				this.$refs.table.queryData(this.query);
			}).catch((err) => {
				loading.close();
			});
		},
		getSummaries({ columns, data }) {
			const sums = [];
			columns.forEach((column, index) => {
				if (index === 0) {
					sums[index] = "合计";
					return;
				}
				let propert = '';
				//尺寸检验
				if(index == 6){
					propert = 'count';
				}else if(index == 7&&this.mioObj.type == 'sale_out'&&this.project_code=='gx'){
					propert = 'count_send';
				}else if((index == 7||index == 8)&&column.label=='不合格数量'){
					propert = 'count_notok';
				}
				if (propert!=='') {
					const values = data.map((item) =>
						Number(item[propert])
					);
					if (!values.every((value) => Number.isNaN(value))) {
						sums[index] = values.reduce((prev, curr) => {
							const value = Number(curr);
							let sum = Number(Number(prev) + Number(curr));
							if (!isNaN(value)) {
								return sum;
							} else {
								return prev;
							}
						}, 0);
					} 
				}
				if(index==8&&this.mioObj.type == 'sale_out'&&this.project_code=='gx'){
					if(sums[6]){
						if(sums[7]){
							sums[index] = sums[6]-sums[7];
						}else{
							sums[index] = sums[6];
						}
					}
				}
			});
			return sums;
		},
	},
};
</script>
