<!--
 * @Descripttion: (物料记录表/wm_material)
 * @version: (1.0)
 * @Author: (admin)
 * @Date: (2024-03-16)
 * @LastEditors: (admin)
 * @LastEditTime: (2024-03-16)
-->
<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="partnumber">
				<el-input v-model="queryParams.partnumber" placeholder="请输入物料号（零件号）" :clearable="true" />
			</el-form-item>
			<el-form-item label="库存编码" prop="u8InventoryCode">
				<el-input v-model="queryParams.u8InventoryCode" placeholder="请输入U8库存编码" :clearable="true" />
			</el-form-item>
			<el-form-item label="毛坯号" prop="blankNum">
				<el-input v-model="queryParams.blankNum" placeholder="请输入毛坯号" :clearable="true" />
			</el-form-item>
			<el-form-item label="产品描述" prop="productName">
				<el-input v-model="queryParams.productName" placeholder="产品描述（产品名称）" :clearable="true" />
			</el-form-item>
			<el-form-item label="产品颜色" prop="color">
				<el-input v-model="queryParams.color" placeholder="请输入产品颜色" :clearable="true" />
			</el-form-item>
			<el-form-item label="规格" prop="specification">
				<el-input v-model="queryParams.specification" placeholder="请输入规格（左右脚）" :clearable="true" />
			</el-form-item>
			<el-form-item label="显示描述" prop="description">
				<el-input v-model="queryParams.description" placeholder="显示描述(产品描述+颜色+规格)" :clearable="true" />
			</el-form-item>
			<el-form-item label="物料类别" prop="type">
				<el-select v-model="queryParams.type" placeholder="请选择物料类别" @change="handleQuery">
					<el-option label="全部" :value="0" />
					<el-option v-for="item in typeList" :key="item.value" :label="item.label" :value="item.value" />
				</el-select>
			</el-form-item>
			<el-form-item label="状态" prop="status">
				<el-radio-group v-model="queryParams.status" @change="handleQuery">
					<el-radio-button v-for="item in statusOptions" :key="item.dictValue" :label="parseInt(item.dictValue)">{{
            item.dictLabel
          }}</el-radio-button>
				</el-radio-group>
			</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="['wms:wmmaterial:add']" plain icon="el-icon-plus" size="medium" @click="handleAdd">新增物料记录</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button type="warning" v-hasPermi="['wms:wmmaterial:add']" plain icon="el-icon-download" size="medium" @click="importmaterial">批量导入</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button type="success" :disabled="single" v-hasPermi="['wms:wmmaterial:edit']" plain icon="el-icon-edit" size="medium" @click="handleUpdate">批量修改</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button type="danger" :disabled="multiple" v-hasPermi="['wms:wmmaterial:delete']" plain icon="el-icon-delete" size="medium" @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="partnumber" label="物料号" align="center" :show-overflow-tooltip="true" />
			<el-table-column prop="u8InventoryCode" label="库存编码" align="center" :show-overflow-tooltip="true" />
			<el-table-column prop="blankNum" label="毛坯号" align="center" :show-overflow-tooltip="true" />
			<el-table-column prop="unit" label="单位" align="center" :show-overflow-tooltip="true" />
			<el-table-column prop="productName" label="产品描述" align="center" :show-overflow-tooltip="true" />
			<el-table-column prop="color" label="产品颜色" align="center" :show-overflow-tooltip="true" />
			<el-table-column prop="specification" label="规格" align="center" :show-overflow-tooltip="true" />
			<el-table-column prop="description" label="显示描述" align="center" :show-overflow-tooltip="true" />
			<el-table-column prop="version" 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 type="primary" v-if="scope.row.type === 1">成品</el-tag>
					<el-tag type="warning" v-if="scope.row.type === 2">毛坯</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="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" width="140">
				<template slot-scope="scope">
					<el-button size="mini" v-hasPermi="['wms:wmmaterial:edit']" type="success" icon="el-icon-edit" title="编辑" @click="handleUpdate(scope.row)"></el-button>
					<el-button size="mini" v-hasPermi="['wms:wmmaterial:delete']" type="danger" icon="el-icon-delete" title="删除" @click="handleDelete(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="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
			<el-upload name="file" ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
				<i class="el-icon-upload"></i>
				<div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
				<div class="el-upload__tip text-center" slot="tip">
					<!-- <div class="el-upload__tip" slot="tip"><el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的生产计划</div> -->
					<span>仅允许导入xls、xlsx格式文件。</span>
					<el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline" @click="importTemplate">下载模板</el-link>
				</div>
			</el-upload>
			<el-tag type="warning">上次导入时间:{{ upload.time }}</el-tag>

			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="submitFileForm">确 定</el-button>
				<el-button @click="upload.open = false">取 消</el-button>
			</div>
		</el-dialog>

		<!-- 添加或修改物料记录表对话框 -->
		<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">
				<el-row :gutter="20">
					<el-col :lg="12">
						<el-form-item label="物料号" prop="partnumber">
							<el-input v-model.trim="form.partnumber" placeholder="请输入物料号（零件号）" />
						</el-form-item>
					</el-col>

					<el-col :lg="12">
						<el-form-item label="库存编码" prop="u8InventoryCode">
							<el-input v-model.trim="form.u8InventoryCode" placeholder="请输入U8库存编码" />
						</el-form-item>
					</el-col>

					<el-col :lg="12">
						<el-form-item label="毛坯号" prop="blankNum">
							<el-input v-model.trim="form.blankNum" placeholder="请输入毛坯号" />
						</el-form-item>
					</el-col>

					<el-col :lg="12">
						<el-form-item label="单位" prop="unit">
							<el-input v-model.trim="form.unit" placeholder="请输入单位(个)" />
						</el-form-item>
					</el-col>

					<el-col :lg="12">
						<el-form-item label="产品描述" prop="productName">
							<el-input v-model.trim="form.productName" placeholder="请输入产品描述（产品名称）" />
						</el-form-item>
					</el-col>

					<el-col :lg="12">
						<el-form-item label="产品颜色" prop="color">
							<el-input v-model.trim="form.color" placeholder="请输入产品颜色" />
						</el-form-item>
					</el-col>

					<el-col :lg="12">
						<el-form-item label="规格" prop="specification">
							<el-input v-model.trim="form.specification" placeholder="请输入规格（左右脚）" />
						</el-form-item>
					</el-col>

					<el-col :lg="12">
						<el-form-item label="显示描述" prop="description">
							<el-input v-model.trim="form.description" placeholder="请输入显示描述(产品描述+颜色+规格)" />
						</el-form-item>
					</el-col>

					<el-col :lg="12">
						<el-form-item label="版本号" prop="version">
							<el-input v-model.trim="form.version" placeholder="请输入版本号" />
						</el-form-item>
					</el-col>

					<el-col :lg="12">
						<el-form-item label="备注" prop="remarks">
							<el-input v-model.trim="form.remarks" placeholder="请输入备注" />
						</el-form-item>
					</el-col>

					<el-col :lg="12">
						<el-form-item label="排序" prop="sort">
							<el-input v-model.trim="form.sort" placeholder="请输入排序(特殊排序)" />
						</el-form-item>
					</el-col>

					<el-col :lg="12">
						<el-form-item label="物料类别" prop="type">
							<el-select v-model="form.type" placeholder="请选择物料类别" clearable>
								<el-option v-for="item in typeList" :key="item.value" :label="item.label" :value="item.value" />
							</el-select>
						</el-form-item>
					</el-col>

					<!-- 					<el-col :lg="12">
						<el-form-item label="物料代号2" prop="search2">
							<el-input v-model.trim="form.search2" placeholder="请输入物料代号1" />
						</el-form-item>
					</el-col> -->

					<el-col :lg="12">
						<el-form-item label="状态" prop="status">
							<el-radio-group 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 slot="footer" class="dialog-footer">
				<el-button type="text" @click="cancel">取 消</el-button>
				<el-button type="primary" @click="submitForm">确 定</el-button>
			</div>
		</el-dialog>
	</div>
</template>
<script>
	import { listWmMaterial, addWmMaterial, delWmMaterial, updateWmMaterial, getWmMaterial } from '@/api/wmsManagement/wmMaterial.js'
	import { getToken } from '@/utils/auth'
	import { formatDate } from '@/utils/index'
	export default {
		name: 'wmmaterial',
		data() {
			return {
				labelWidth: '100px',
				formLabelWidth: '100px',
				// 选中id数组
				ids: [],
				// 非单个禁用
				single: true,
				// 非多个禁用
				multiple: true,
				// 遮罩层
				loading: false,
				// 显示搜索条件
				showSearch: true,
				// 查询参数
				queryParams: {
					pageNum: 1,
					pageSize: 10,
					status: 1,
					type: 0,
				},
				// 弹出层标题
				title: '',
				// 操作类型 1、add 2、edit
				opertype: 0,
				// 是否显示弹出层
				open: false,
				// 表单参数
				form: {
					status: 1,
					type: 1,
				},
				columns: [
					{ index: 1, key: 'partnumber', label: `物料号（零件号）`, checked: true },
					{ index: 2, key: 'u8InventoryCode', label: `U8库存编码`, checked: true },
					{ index: 3, key: 'blankNum', label: `毛坯号`, checked: true },
					{ index: 4, key: 'unit', label: `单位`, checked: true },
					{ index: 5, key: 'productName', label: `产品描述（产品名称）`, checked: true },
					{ index: 6, key: 'color', label: `产品颜色`, checked: true },
					{ index: 7, key: 'specification', label: `规格（左右脚）`, checked: true },
					{ index: 8, key: 'description', label: `显示描述(产品描述+颜色+规格)`, checked: true },
					{ index: 9, key: 'version', label: `版本号`, checked: false },
					{ index: 10, key: 'remarks', label: `备注`, checked: false },
					{ index: 14, key: 'status', label: `状态`, checked: false },
				],
				// 状态（0-不可见 1-可见）选项列表 格式 eg:{ dictLabel: '标签', dictValue: '0'}
				statusOptions: [
				{
					dictLabel: '正常',
					dictValue: 1,
				},
				{
					dictLabel: '弃用',
					dictValue: 0,
				}, ],
				typeList: [
				{
					label: '成品',
					value: 1
				},
				{
					label: '毛坯',
					value: 2
				}, ],
				// 数据列表
				dataList: [],
				// 总记录数
				total: 0,
				// 提交按钮是否显示
				btnSubmitVisible: true,
				// 表单校验
				rules: {},
				pickerOptions: {
					shortcuts: [
					{
						text: '最近一周',
						onClick(picker) {
							const end = new Date()
							const start = new Date()
							start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
							picker.$emit('pick', [start, end])
						},
					},
					{
						text: '最近一个月',
						onClick(picker) {
							const end = new Date()
							const start = new Date()
							start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
							picker.$emit('pick', [start, end])
						},
					},
					{
						text: '最近三个月',
						onClick(picker) {
							const end = new Date()
							const start = new Date()
							start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
							picker.$emit('pick', [start, end])
						},
					}, ],
				},
				upload: {
					time: null,
					// 用户导入参数
					// 是否显示弹出层（用户导入）
					open: false,
					// 弹出层标题（用户导入）
					title: '',
					// 是否禁用上传
					isUploading: false,
					// 是否更新已经存在的用户数据
					updateSupport: false,
					// 设置上传的请求头部
					headers: { Authorization: 'Bearer ' + getToken() },
					// 上传的地址
					url: process.env.VUE_APP_BASE_API + '/mes/wm/WmMaterial/importData',
				},

				fullloading: null,
			}
		},
		created() {
			// 列表数据查询
			this.getList()

			var dictParams = []
		},
		mounted() {
			this.upload.time = formatDate(localStorage.getItem('material'))
		},
		methods: {
			// 查询数据
			getList() {
				this.loading = true
				listWmMaterial(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 = {
					id: undefined,
					partnumber: undefined,
					u8InventoryCode: undefined,
					blankNum: undefined,
					unit: undefined,
					productName: undefined,
					color: undefined,
					specification: undefined,
					description: undefined,
					version: undefined,
					remarks: undefined,
					sort: undefined,
					search1: '',
					search2: undefined,
					type: 1,
					status: 1,
					createdBy: undefined,
					createdTime: undefined,
					updatedBy: undefined,
					updatedTime: undefined,
				}
				this.resetForm('form')
			},
			// 重置查询操作
			resetQuery() {
				this.timeRange = []
				this.resetForm('queryForm')
				this.handleQuery()
			},
			// 多选框选中数据
			handleSelectionChange(selection) {
				this.ids = selection.map((item) => item.id)
				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.opertype = 1
			},
			/** 删除按钮操作 */
			handleDelete(row) {
				const Ids = row.id || this.ids

				this.$confirm('是否确认删除数据项？')
					.then(function () {
						return delWmMaterial(Ids)
					})
					.then(() => {
						this.handleQuery()
						this.msgSuccess('删除成功')
					})
					.catch(() => {})
			},
			/** 修改按钮操作 */
			handleUpdate(row) {
				this.reset()
				const id = row.id || this.ids
				getWmMaterial(id).then((res) => {
					const { code, data } = res
					if (code == 200) {
						this.open = true
						this.title = '修改数据'
						this.opertype = 2

						this.form = {
							...data,
						}
					}
				})
			},
			// 状态（0-不可见 1-可见）字典翻译
			statusFormat(row, column) {
				return this.selectDictLabel(this.statusOptions, row.status)
			},
			/** 提交按钮 */
			submitForm: function () {
				this.$refs['form'].validate((valid) => {
					if (valid) {
						console.log(JSON.stringify(this.form))

						if (this.form.id != undefined && this.opertype === 2) {
							updateWmMaterial(this.form)
								.then((res) => {
									this.msgSuccess('修改成功')
									this.open = false
									this.getList()
								})
								.catch((err) => {
									//TODO 错误逻辑
								})
						} else {
							addWmMaterial(this.form)
								.then((res) => {
									this.msgSuccess('新增成功')
									this.open = false
									this.getList()
								})
								.catch((err) => {
									//TODO 错误逻辑
								})
						}
					}
				})
			},

			//todo 导入文件
			importmaterial() {
				this.upload.open = true
				this.upload.title = '物料清单批量导入'
			},
			//todo 下载模板
			importTemplate() {
				//  @/utils/ruoyi"
				this.download('/mes/wm/WmMaterial/download_template', '物料清单导入模板')
			},

			// todo 文件上传中处理
			handleFileUploadProgress(event, file, fileList) {
				this.upload.isUploading = true
			},
			//todo  提交上传文件
			submitFileForm() {
				this.$refs.upload.submit()
				this.fullloading = this.$loading({
					lock: true,
					text: 'Loading',
					spinner: 'el-icon-loading',
					background: 'rgba(0, 0, 0, 0.7)',
				})
				//保存数据
				window.localStorage.setItem('material', new Date())
			},
			//todo 文件上传成功处理
			handleFileSuccess(response, file, fileList) {
				this.upload.open = false
				this.upload.isUploading = false
				this.$refs.upload.clearFiles()
				this.fullloading.close()
				if (response.code == 200) {
					this.$alert(response.data, '导入结果', { dangerouslyUseHTMLString: true })
				} else {
					this.$alert(response.msg, '导入结果', {
						dangerouslyUseHTMLString: true,
						type: 'error',
					})
				}
				this.upload.time = new Date()

				this.getList()
			},
		},
	}
</script>