<!--
 * @Descripttion: (出货单（物料+客户）/wm_out_order)
 * @version: (1.0)
 * @Author: (admin)
 * @Date: (2024-03-18)
 * @LastEditors: (admin)
 * @LastEditTime: (2024-03-18)
-->
<template>
	<div class="app-container">
		<!-- :model属性用于表单验证使用 比如下面的el-form-item 的 prop属性用于对表单值进行验证操作 -->
		<el-form :model="queryParams" size="small" label-position="right" inline ref="queryForm" :label-width="labelWidth" v-show="showSearch" @submit.native.prevent>
			<el-form-item label="年" prop="year">
				<el-input v-model="queryParams.year" placeholder="请输入年" />
			</el-form-item>
			<el-form-item label="月" prop="week">
				<el-input v-model="queryParams.week" placeholder="请输入月" />
			</el-form-item>
			<el-form-item label="日" prop="date">
				<el-input v-model="queryParams.date" placeholder="请输入日" />
			</el-form-item>
			<el-form-item label="出库单号" prop="shipmentNum">
				<el-input v-model="queryParams.shipmentNum" placeholder="请输入出库单号" />
			</el-form-item>
			<el-form-item label="客户代码" prop="customNo">
				<el-input v-model="queryParams.customNo" placeholder="请输入客户代码" />
			</el-form-item>
			<el-form-item label=" ">
				<el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
				<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
			</el-form-item>
		</el-form>
		<!-- 工具区域 -->
		<el-row :gutter="10" class="mb8">
			<el-col :span="1.5">
				<el-button type="primary" v-hasPermi="['business:wmoutorder:add']" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增出库单</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button type="success" :disabled="single" v-hasPermi="['business:wmoutorder:edit']" plain icon="el-icon-edit" size="mini" @click="handleUpdate">批量修改</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button type="danger" :disabled="multiple" v-hasPermi="['business:wmoutorder:delete']" plain icon="el-icon-delete" size="mini" @click="handleDelete">批量删除</el-button>
			</el-col>
			<right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
		</el-row>

		<!-- 数据区域 -->
		<el-table :data="dataList" v-loading="loading" ref="table" border highlight-current-row @sort-change="sortChange" @selection-change="handleSelectionChange">
			<el-table-column type="selection" width="50" align="center" />
			<el-table-column prop="shipmentNum" label="出库单号" align="center" :show-overflow-tooltip="true" min-width="120" />
			<el-table-column prop="customNo" label="客户代码" align="center" :show-overflow-tooltip="true" />
			<el-table-column prop="customName" label="客户名称" align="center" :show-overflow-tooltip="true" min-width="240" />
			<el-table-column prop="customAddress" label="客户地址" align="center" :show-overflow-tooltip="true" />
			<el-table-column prop="remarks" label="备注" align="center" :show-overflow-tooltip="true" />
			<el-table-column prop="type" label="出库状态" align="center">
				<template slot-scope="scope">
					<el-tag v-if="scope.row.type === 1">出库中</el-tag>
					<el-tag type="success" v-if="scope.row.type === 2">出库完成</el-tag>
					<el-tag type="info" v-if="scope.row.type === 3">弃用</el-tag>
				</template>
			</el-table-column>
			<el-table-column prop="status" label="出库计划" align="center">
				<template slot-scope="scope">
					<el-tag type="success" v-if="scope.row.status === 1">启用</el-tag>
					<el-tag type="info" v-if="scope.row.status === 0">停用</el-tag>
				</template>
			</el-table-column>
			<el-table-column prop="year" label="年月日" align="center" min-width="100">
				<template slot-scope="scope">
					<span v-if="scope.row.year">{{ scope.row.year + '-' + scope.row.week + '-' + scope.row.date }}</span>
				</template>
			</el-table-column>
			<el-table-column prop="createdBy" label="创建人" align="center" :show-overflow-tooltip="true" />
			<el-table-column prop="createdTime" label="创建时间" align="center" :show-overflow-tooltip="true" />

			<el-table-column label="操作" align="center" fixed="right" width="280">
				<template slot-scope="scope">
					<el-button size="mini" v-hasPermi="['business:wmoutorder:print']" type="primary" icon="el-icon-printer" title="打印" :disabled="scope.row.status === 3" @click="handlePrint(scope.row)"></el-button>
					<el-button size="mini" v-hasPermi="['business:wmoutorder:edit']" type="success" icon="el-icon-edit" title="编辑" @click="handleUpdate(scope.row)"></el-button>
					<el-button size="mini" v-hasPermi="['business:wmoutorder:delete']" type="danger" icon="el-icon-delete" title="删除" @click="handleDelete(scope.row)"></el-button>
					<el-button size="mini" type="warning" @click="handlePlan(scope.row)">出库详情</el-button>
				</template>
			</el-table-column>
		</el-table>
		<pagination class="mt10" background :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

		<!-- 添加或修改出货单对话框 -->
		<el-dialog :title="title" :lock-scroll="false" :visible.sync="open" :close-on-click-modal="false">
			<el-form ref="form" :model="form" :rules="rules" :label-width="formLabelWidth" size="mini">
				<!-- 时间信息 -->
				<el-row :gutter="10">
					<el-col :lg="8">
						<el-form-item label="年" prop="year">
							<el-input v-model="form.year" placeholder="请输入年" :disabled="form.type === 2" />
						</el-form-item>
					</el-col>
					<el-col :lg="8">
						<el-form-item label="月" prop="week">
							<el-input v-model="form.week" placeholder="请输入月" :disabled="form.type === 2" />
						</el-form-item>
					</el-col>
					<el-col :lg="8">
						<el-form-item label="日" prop="date">
							<el-input v-model="form.date" placeholder="请输入日" :disabled="form.type === 2" />
						</el-form-item>
					</el-col>
				</el-row>
				<!-- 客户信息 -->
				<el-row :gutter="20">
					<el-col :lg="12">
						<el-form-item label="客户选择" prop="customId">
							<el-select :disabled="form.type === 2" v-model="selectCustomInfo" filterable placeholder="请选择一个客户" @change="handleCustomSelectChange" value-key="customNo">
								<el-option v-for="(item, index) in customOptions" :key="index" :label="item.customNo + '-' + item.customName" :value="item">
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :lg="12">
						<el-form-item label="客户代码" prop="customNo">
							<el-input :disabled="form.type === 2" v-model="form.customNo" placeholder="请输入客户代码" />
						</el-form-item>
					</el-col>
					<el-col :lg="12">
						<el-form-item label="客户名称" prop="customName">
							<el-input :disabled="form.type === 2" v-model="form.customName" placeholder="请输入客户名称" />
						</el-form-item>
					</el-col>
					<el-col :lg="12">
						<el-form-item label="客户地址" prop="customAddress">
							<el-input :disabled="form.type === 2" v-model="form.customAddress" placeholder="请输入客户地址" />
						</el-form-item>
					</el-col>
				</el-row>
				<!-- 其他信息 -->
				<el-row :gutter="20">
					<el-col :lg="12">
						<el-form-item label="备注" prop="remarks">
							<el-input :disabled="form.type === 2" v-model="form.remarks" placeholder="请输入备注" />
						</el-form-item>
					</el-col>
					<el-col :lg="12">
						<el-form-item label="出库状态" prop="type">
							<el-select v-model="form.type" placeholder="请选择出库状态">
								<el-option v-for="item in typeOptions" :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :lg="12">
						<el-form-item label="出库计划" prop="status">
							<el-radio-group :disabled="form.type === 2" v-model="form.status">
								<el-radio v-for="item in statusOptions" :key="item.dictValue" :label="parseInt(item.dictValue)">{{
									item.dictLabel
								}}</el-radio>
							</el-radio-group>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<!-- 物料信息 -->
			<div>
				<div class="action-box flex-row flex-row-right">
					<el-button :disabled="opertype === 2" size="medium" type="success" icon="el-icon-plus" @click="handlerOpenChouseMaterial">添加物料</el-button>
					<!-- <el-button
						size="medium"
						type="danger"
						icon="el-icon-delete"
						@click="handlerDeleteMaterial(null)"
						:disabled="materialIds.length === 0 || form.type === 2"
						>批量移除</el-button
					> -->
				</div>
				<div>
					<el-table :disabled="opertype === 2" :data="form.materialList" v-loading="materialLoading" ref="table" border highlight-current-row @selection-change="handleMaterialSelectionChange">
						<!-- <el-table-column type="selection" width="50" align="center" /> -->
						<el-table-column prop="partnumber" label="物料号" align="center" :show-overflow-tooltip="true" min-width="120" />
						<el-table-column label="需求量" prop="requireOutNum" align="center" width="100">
							<template slot-scope="scope">
								<el-input :disabled="opertype === 2" v-model.number="scope.row.requireOutNum" placeholder="请输入物料需求量" @blur="validateRequireOutNum(scope.row)"></el-input>
							</template>
						</el-table-column>
						<el-table-column prop="stockQuantity" label="现有库存" align="center" :show-overflow-tooltip="true" min-width="100" />
						<el-table-column prop="description" label="显示描述" align="center" :show-overflow-tooltip="true" min-width="180" />
						<el-table-column label="操作" align="center" width="140">
							<template slot-scope="scope">
								<el-button :disabled="opertype === 2" size="mini" v-hasPermi="['business:wmmaterial:delete']" type="danger" icon="el-icon-delete" @click="handlerDeleteMaterial([scope.row.id])">移除此物料</el-button>
							</template>
						</el-table-column>
					</el-table>
				</div>
			</div>
			<div slot="footer" class="dialog-footer">
				<el-button type="info" @click="cancel">取消</el-button>
				<el-button type="primary" @click="submitForm">确定</el-button>
			</div>
		</el-dialog>
		<PrintView ref="printViewRef" :visible.sync="showPrintDialog" :printKey="printKey"></PrintView>
		<TheOutboundPlan :visible.sync="TheOutboundPlanDialogVisible" :planKey="planKey"></TheOutboundPlan>
		<TheChouseMaterial :visible.sync="TheChouseMaterialDialogVisible" @materialChoused="handlerMaterialChoused"></TheChouseMaterial>
	</div>
</template>
<script>
	import { listWmOutOrder, addWmOutOrder, delWmOutOrder, updateWmOutOrder, getWmOutOrder, getCustomList } from '@/api/wmsManagement/wmOutOrder.js'
	import TheChouseMaterial from './components/TheChouseMaterial/TheChouseMaterial.vue'
	import TheOutboundPlan from './components/TheOutboundPlan'
	import PrintView from '@/components/Print/出库单.vue'
	export default {
		name: 'wmoutorder',
		components: {
			TheChouseMaterial,
			TheOutboundPlan,
			PrintView,
		},
		data() {
			return {
				TheChouseMaterialDialogVisible: false,
				TheOutboundPlanDialogVisible: false,
				showPrintDialog: false,
				printKey: '',
				planKey: '',
				labelWidth: '100px',
				formLabelWidth: '100px',
				// 选中shipmentNum数组
				ids: [],
				// 非单个禁用
				single: true,
				// 非多个禁用
				multiple: true,
				// 遮罩层
				loading: false,
				materialLoading: false,
				// 显示搜索条件
				showSearch: true,
				// 查询参数
				queryParams: {
					pageNum: 1,
					pageSize: 10,
					sort: undefined,
					sortType: undefined,
				},
				// 弹出层标题
				title: '',
				// 操作类型 1、add 2、edit
				opertype: 0,
				// 是否显示弹出层
				open: false,
				// 表单参数
				form: {
					status: 1,
					type: 1,
					materialList: [],
				},
				// 缓存记录数据
				columns: [
					{ index: 0, key: 'shipmentNum', label: `出库单号(EG+时间)`, checked: true },
					{ index: 1, key: 'customId', label: `客户id`, checked: true },
					{ index: 2, key: 'customNo', label: `客户代码`, checked: true },
					{ index: 3, key: 'customName', label: `客户名称`, checked: true },
					{ index: 4, key: 'customAddress', label: `客户地址`, checked: true },
					{ index: 5, key: 'remarks', label: `备注`, checked: true },
					{ index: 6, key: 'type', label: `出库单状态（1-出库中 2-出库完成 3-弃用）`, checked: true },
					{ index: 7, key: 'status', label: `状态（0-停用 1-启用）`, checked: true },
					{ index: 8, key: 'year', label: `年`, checked: true },
					{ index: 9, key: 'week', label: `周`, checked: false },
					{ index: 10, key: 'date', label: `日`, checked: false },
					{ index: 11, key: 'createdBy', label: `创建人`, checked: false },
					{ index: 12, key: 'createdTime', label: `创建时间`, checked: false },
					{ index: 13, key: 'updatedBy', label: `更新人`, checked: false },
					{ index: 14, key: 'updatedTime', label: `更新时间`, checked: false },
				],
				// 出库单状态（1-出库中 2-出库完成 3-弃用）选项列表 格式 eg:{ dictLabel: '标签', dictValue: '0'}
				typeOptions: [
				{
					dictLabel: '出库中',
					dictValue: 1,
				},
				{
					dictLabel: '出库完成',
					dictValue: 2,
				},
				{
					dictLabel: '弃用',
					dictValue: 3,
				}, ],
				// 状态（0-停用 1-启用）选项列表 格式 eg:{ dictLabel: '标签', dictValue: '0'}
				statusOptions: [
				{
					dictLabel: '启用',
					dictValue: 1,
				},
				{
					dictLabel: '停用',
					dictValue: 0,
				}, ],
				// 数据列表
				dataList: [],
				// 总记录数
				total: 0,
				// 提交按钮是否显示
				btnSubmitVisible: true,
				// 表单校验
				rules: {},
				// 添加订单操作相关数据 ========
				customOptions: [],
				selectCustomInfo: null,
				materialIds: [],
				//出库单关联物料表数据
			}
		},
		created() {
			// 列表数据查询
			this.initDict()
			this.getList()
		},
		methods: {
			initDict() {
				// 获取客户下拉菜单
				getCustomList().then((res) => {
					if (res.code === 200) {
						this.customOptions = res.data
					}
				})
			},
			// 查询数据
			getList() {
				this.loading = true
				listWmOutOrder(this.queryParams).then((res) => {
					if (res.code == 200) {
						this.dataList = res.data.result
						this.total = res.data.totalNum
						this.loading = false
					}
				})
			},
			// 取消按钮
			cancel() {
				this.open = false
				this.reset()
			},
			// 重置数据表单
			reset() {
				this.form = {
					shipmentNum: undefined,
					customId: undefined,
					customNo: undefined,
					customName: undefined,
					customAddress: undefined,
					remarks: undefined,
					type: 1,
					status: 1,
					year: undefined,
					week: undefined,
					date: undefined,
					createdBy: undefined,
					createdTime: undefined,
					updatedBy: undefined,
					updatedTime: undefined,
					materialList: [],
				}
				// this.customOptions = []
				this.selectCustomInfo = null
				this.materialIds = []
				this.resetForm('form')
			},
			// 重置查询操作
			resetQuery() {
				this.timeRange = []
				this.resetForm('queryForm')
				this.handleQuery()
			},
			// 多选框选中数据
			handleSelectionChange(selection) {
				this.ids = selection.map((item) => item.shipmentNum)
				this.single = selection.length != 1
				this.multiple = !selection.length
			},
			// 自定义排序
			sortChange(column) {
				if (column.prop == null || column.order == null) {
					this.queryParams.sort = undefined
					this.queryParams.sortType = undefined
				} else {
					this.queryParams.sort = column.prop
					this.queryParams.sortType = column.order
				}

				this.handleQuery()
			},
			/** 搜索按钮操作 */
			handleQuery() {
				this.queryParams.pageNum = 1
				this.getList()
			},
			/** 新增按钮操作 */
			handleAdd() {
				this.reset()
				this.open = true
				this.title = '创建出库单';
				(this.form.year = new Date().getFullYear()),
				(this.form.week = new Date().getMonth() + 1),
				(this.form.date = new Date().getDate()),
				(this.opertype = 1)
			},
			/** 删除按钮操作 */
			handleDelete(row) {
				const Ids = row.shipmentNum || this.ids
				this.$confirm('是否确认删除此数据项？')
					.then(function () {
						return delWmOutOrder(Ids)
					})
					.then(() => {
						this.handleQuery()
						this.msgSuccess('删除成功')
					})
					.catch(() => {})
			},
			/** 修改按钮操作 */
			handleUpdate(row) {
				this.reset()
				const id = row.shipmentNum || this.ids
				getWmOutOrder(id).then((res) => {
					const { code, data } = res
					if (code == 200) {
						this.open = true
						this.title = '编辑出库单数据'
						this.opertype = 2
						this.form = {
							...data,
						}
					}
				})
			},
			// 出库单状态（1-出库中 2-出库完成 3-弃用）字典翻译
			typeFormat(row, column) {
				return this.selectDictLabel(this.typeOptions, row.type)
			},
			// 出库计划状态（0-停用 1-启用）字典翻译
			statusFormat(row, column) {
				return this.selectDictLabel(this.statusOptions, row.status)
			},
			// 出库单新增相关操作 ===========================
			handleCustomSelectChange(item) {
				this.form.id = item.ids
				this.form.customNo = item.customNo
				this.form.customName = item.customName
				this.form.customAddress = item.customAddress
			},
			// 出库单物料表多选框选中数据
			handleMaterialSelectionChange(selection) {
				this.materialIds = selection.map((item) => item.id)
				console.log(this.materialIds)
				// this.single = selection.length != 1
				// this.multiple = !selection.length
			},
			// 删除某项
			handlerDeleteMaterial(ids = null) {
				let that = this
				const Ids = ids || this.materialIds
				this.$confirm('是否确认移除数据项？')
					.then(() => {
						const list = JSON.parse(JSON.stringify(that.form.materialList))
						const len = list.length
						for (let index = 0; index < len; index++) {
							if (Ids.includes(list[index].id)) {
								console.log(that.form.materialList, index)
								that.form.materialList.splice(index, 1)
							}
						}
					})
					.then(() => {
						that.msgSuccess('删除成功')
					})
			},
			// 打开物料选择弹窗
			handlerOpenChouseMaterial() {
				this.TheChouseMaterialDialogVisible = true
			},
			// 物料已选择
			handlerMaterialChoused(list) {
				//TODO 需要筛选未选择的
				const _list = JSON.parse(JSON.stringify(list))
				for (let index = 0; index < _list.length; index++) {
					this.form.materialList.push(_list[index])
				}
			},
			// 打印出库单
			handlePrint(row) {
				this.printKey = row.shipmentNum
				this.showPrintDialog = true
			},
			// 配置出库计划
			handlePlan(row) {
				this.planKey = row.shipmentNum
				this.TheOutboundPlanDialogVisible = true
			},
			// ====================================================
			/** 提交按钮 */
			submitForm: function () {
				this.$refs['form'].validate((valid) => {
					if (valid) {
						if (this.form.shipmentNum != undefined && this.opertype === 2) {
							updateWmOutOrder(this.form)
								.then((res) => {
									if (res.code === 200) {
										this.msgSuccess('修改成功')
										this.open = false
										this.getList()
									} else {
										this.$message.error('修改失败' + res.msg)
									}
								})
								.catch((err) => {
									//TODO 错误逻辑
								})
						} else {
							for (let item of this.form.materialList) {
								if ((item.requireOutNum * 1) < 1) {
									this.$message.error('需求量不可为0!' + item.partnumber);
									return;
								}
							}
							// const postData = {
							// 	customNo: 'BBBB',
							// 	customName: 'BBB',
							// 	customAddress: 'BBB',
							// 	remarks: '123',
							// 	type: 1,
							// 	status: 1,
							// 	year: '123',
							// 	week: '1231',
							// 	date: '231123',
							// }
							addWmOutOrder(this.form)
								.then((res) => {
									if (res.code === 200) {
										this.msgSuccess('新增成功')
										this.open = false
										this.getList()
									} else {
										this.$message.error('新增失败' + res.msg)
									}
								})
								.catch((err) => {
									//TODO 错误逻辑
									console.log('addWmOutOrder', err)
								})
						}
					}
				})
			},
			// 验证需求量输入
			validateRequireOutNum(row) {
				if (row.requireOutNum && row.requireOutNum <= 0) {
					this.$message.error('需求量必须大于0');
					row.requireOutNum = undefined;
				} 
				// else if (row.requireOutNum && row.requireOutNum > row.stockQuantity) {
				// 	this.$message.error('需求量不能大于现有库存');
				// 	row.requireOutNum = undefined;
				// }
			},
		},
	}
</script>

<style scoped>
	.action-box {
		width: 100%;
		margin-bottom: 10px;
	}

	.flex-row {
		display: flex;
		flex-direction: row;
	}

	.flex-column {
		display: flex;
		flex-direction: column;
	}

	.flex-row-right {
		align-items: center;
		justify-content: right;
	}
</style>