<!--
 * @Descripttion: (配料任务清单/mm_ingredient_task)
 * @version: (1.0)
 * @Author: (admin)
 * @Date: (2024-06-05)
 * @LastEditors: (admin)
 * @LastEditTime: (2024-06-05)
-->
<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>
				<el-form-item label="工单" prop="workorder">
					<el-input v-model="queryParams.workorder" placeholder="请输入工单" />
				</el-form-item>
			</el-form-item>

			<el-form-item>
				<el-form-item label="时间段" prop="agvPosition">
					<el-date-picker v-model="queryParams.timeperiod" :picker-options="pickerOptions" type="datetimerange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
					</el-date-picker>
				</el-form-item>
			</el-form-item>

			<el-form-item>
				<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="['materialManagement:mmingredienttask: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="['materialManagement:mmingredienttask: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="['materialManagement:mmingredienttask: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 :span-method="objectSpanMethod" @sort-change="sortChange" @selection-change="handleSelectionChange">
			<el-table-column prop="agvPosition" label="起点站点" align="center" :show-overflow-tooltip="true" />
			<el-table-column prop="agvPositionEnd" label="终点站点" align="center" :show-overflow-tooltip="true" />

			<el-table-column prop="workorder" label="工单号" align="center" :show-overflow-tooltip="true" />
			<el-table-column prop="blanknumber" label="毛坯号" align="center" :show-overflow-tooltip="true" />
			<el-table-column prop="isfinal" label="是否完成（0是未完成，1是完成）" align="center">
				<template slot-scope="scope">
					<!-- {{scope.row.isfinal}} -->
					<dict-tag :options="isfinalOptions" :value="scope.row.isfinal" />
				</template>
			</el-table-column>
			<el-table-column prop="previousNumber" label="需要上件数" align="center" />
			<el-table-column prop="previousNumbered" label="已经上件数" align="center" />

			<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="['materialManagement:mmingredienttask:edit']" type="success" icon="el-icon-edit" title="编辑" @click="handleUpdate(scope.row)"></el-button>
					<el-button size="mini" v-hasPermi="['materialManagement:mmingredienttask: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="title" :lock-scroll="false" :visible.sync="open">
			<el-form ref="form" :model="form" :rules="rules" :label-width="formLabelWidth">
				<el-row :gutter="20">
					<el-col :lg="12" v-if="opertype == 2">
						<el-form-item label="id">{{ form.id }}</el-form-item>
					</el-col>

					<el-col :lg="12">
						<el-form-item label="起点站点" prop="agvPosition">
							<el-input v-model="form.agvPosition" placeholder="请输入起点站点" />
						</el-form-item>
					</el-col>

					<el-col :lg="12">
						<el-form-item label="终点站点" prop="agvPositionEnd">
							<el-input v-model="form.agvPositionEnd" placeholder="请输入终点站点" />
						</el-form-item>
					</el-col>

					<el-col :lg="12">
						<el-form-item label="配料任务id" prop="taskId">
							<el-input-number v-model.number="form.taskId" controls-position="right" placeholder="请输入配料任务id" :disabled="title == '修改数据'" />
						</el-form-item>
					</el-col>

					<el-col :lg="12">
						<el-form-item label="工单id" prop="workorder">
							<el-input v-model="form.workorder" placeholder="请输入工单id" />
						</el-form-item>
					</el-col>

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

					<el-col :lg="12">
						<el-form-item label="是否完成（0是未完成，1是完成）" prop="isfinal">
							<el-radio-group v-model="form.isfinal">
								<el-radio v-for="item in isfinalOptions" :key="item.dictValue" :label="parseInt(item.dictValue)">{{ item.dictLabel }}</el-radio>
							</el-radio-group>
						</el-form-item>
					</el-col>

					<el-col :lg="12">
						<el-form-item label="需要上件数" prop="previousNumber">
							<el-input v-model="form.previousNumber" placeholder="请输入需要上件数" />
						</el-form-item>
					</el-col>

					<el-col :lg="12">
						<el-form-item label="已经上件数" prop="previousNumbered">
							<el-input v-model="form.previousNumbered" placeholder="请输入已经上件数" />
						</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 {
		listMmIngredientTask,
		addMmIngredientTask,
		delMmIngredientTask,
		updateMmIngredientTask,
		getMmIngredientTask,
	} from "@/api/materialManagement/mmIngredientTask.js";

	export default {
		name: "mmingredienttask",
		data() {
			return {
				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]);
						},
					}, ],
				},
				labelWidth: "100px",
				formLabelWidth: "100px",
				// 选中id数组
				ids: [],
				// 非单个禁用
				single: true,
				// 非多个禁用
				multiple: true,
				// 遮罩层
				loading: false,
				// 显示搜索条件
				showSearch: true,
				// 查询参数
				queryParams: {
					workorder: null,
					timeperiod: [
						new Date().setHours(0, 0, 0, 0),
						new Date().setHours(23, 59, 59, 0),
					],
					pageNum: 1,
					pageSize: 10,
					sort: undefined,
					sortType: undefined,
				},
				// 弹出层标题
				title: "",
				// 操作类型 1、add 2、edit
				opertype: 0,
				// 是否显示弹出层
				open: false,
				// 表单参数
				form: {},
				columns: [
					{ index: 0, key: "id", label: `id`, checked: true },
					{ index: 1, key: "agvPosition", label: `起点站点`, checked: true },
					{ index: 2, key: "agvPositionEnd", label: `终点站点`, checked: true },
					{ index: 3, key: "taskId", label: `配料任务id`, checked: true },
					{ index: 4, key: "workorder", label: `工单id`, checked: true },
					{ index: 5, key: "blanknumber", label: `毛坯号`, checked: true },
					{
						index: 6,
						key: "isfinal",
						label: `是否完成（0是未完成，1是完成）`,
						checked: true,
					},
					{ index: 7, key: "previousNumber", label: `需要上件数`, checked: true },
					{
						index: 8,
						key: "previousNumbered",
						label: `已经上件数`,
						checked: true,
					},
					{ index: 9, key: "createdBy", label: `创建人`, checked: false },
					{ index: 10, key: "createdTime", label: `创建时间`, checked: false },
					{ index: 11, key: "updatedBy", label: `更新人`, checked: false },
					{ index: 12, key: "updatedTime", label: `更新时间`, checked: false },
				],
				// 是否完成（0是未完成，1是完成）选项列表 格式 eg:{ dictLabel: '标签', dictValue: '0'}
				isfinalOptions: [
					{ label: "未知", value: null, raw: { listClass: 'info' } },
					{ label: "进行中", value: '0', raw: { listClass: "danger" } },
					{ label: "完成", value: 1, raw: { listClass: "success" } },
				],
				// 数据列表
				dataList: [],
				// 总记录数
				total: 0,
				// 提交按钮是否显示
				btnSubmitVisible: true,
				// 表单校验
				rules: {
					taskId: [
						{ required: true, message: "配料任务id不能为空", trigger: "blur" },
					],
				},
				spanArr: [], // 需要合并的行数

				pos: 0, // 索引
			};
		},
		created() {
			// 列表数据查询
			this.getList();

			var dictParams = [];
		},
		methods: {
			// 查询数据
			getList() {
				this.loading = true;
				let query = { ...this.queryParams };

				query.starttime = new Date(query.timeperiod[0]);
				query.endtime = new Date(query.timeperiod[1]);
				delete query.timeperiod;
				listMmIngredientTask(query).then((res) => {
					if (res.code == 200) {
						this.dataList = res.data.result;
						this.getSpanArr(this.dataList);
						this.total = res.data.totalNum;
						this.loading = false;
					}
				});
			},
			// 取消按钮
			cancel() {
				this.open = false;
				this.reset();
			},
			// 重置数据表单
			reset() {
				this.form = {
					id: undefined,
					agvPosition: undefined,
					agvPositionEnd: undefined,
					taskId: undefined,
					workorder: undefined,
					blanknumber: undefined,
					isfinal: undefined,
					previousNumber: undefined,
					previousNumbered: undefined,
					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('是否确认删除参数编号为"' + Ids + '"的数据项？')
					.then(function () {
						return delMmIngredientTask(Ids);
					})
					.then(() => {
						this.handleQuery();
						this.msgSuccess("删除成功");
					})
					.catch(() => {});
			},
			/** 修改按钮操作 */
			handleUpdate(row) {
				this.reset();
				const id = row.id || this.ids;
				getMmIngredientTask(id).then((res) => {
					const { code, data } = res;
					if (code == 200) {
						this.open = true;
						this.title = "修改数据";
						this.opertype = 2;

						this.form = {
							...data,
						};
					}
				});
			},
			// 是否完成（0是未完成，1是完成）字典翻译
			isfinalFormat(row, column) {
				return this.selectDictLabel(this.isfinalOptions, row.isfinal);
			},
			/** 提交按钮 */
			submitForm: function () {
				this.$refs["form"].validate((valid) => {
					if (valid) {
						console.log(JSON.stringify(this.form));

						if (this.form.id != undefined && this.opertype === 2) {
							updateMmIngredientTask(this.form)
								.then((res) => {
									this.msgSuccess("修改成功");
									this.open = false;
									this.getList();
								})
								.catch((err) => {
									//TODO 错误逻辑
								});
						} else {
							addMmIngredientTask(this.form)
								.then((res) => {
									this.msgSuccess("新增成功");
									this.open = false;
									this.getList();
								})
								.catch((err) => {
									//TODO 错误逻辑
								});
						}
					}
				});
			},
			//  合并单元格
			// 列表数据处理函数
			getSpanArr(data) {
				//页面展示的数据，不一定是全部的数据，所以每次都清空之前存储的 保证遍历的数据是最新的数据。以免造成数据渲染混乱
				this.spanArr = [];
				this.pos = 0;
				//遍历数据
				data.forEach((item, index) => {
					//判断是否是第一项
					if (index === 0) {
						this.spanArr.push(1);
						this.pos = 0;
					} else {
						//不是第一项时，就根据标识去存储
						if (data[index].taskId === data[index - 1].taskId) {
							// 查找到符合条件的数据时每次要把之前存储的数据+1
							this.spanArr[this.pos] += 1;
							this.spanArr.push(0);
						} else {
							// 没有符合的数据时，要记住当前的index
							this.spanArr.push(1);
							this.pos = index;
						}
					}
				});
				console.log(this.spanArr, this.pos);
			},

			// 指定合并的单元格函数
			objectSpanMethod({ row, column, rowIndex, columnIndex }) {
				// 页面列表上 表格合并行 -> 第几列(从0开始)
				// 需要合并多个单元格时 依次增加判断条件即可
				if (columnIndex === 0 || columnIndex === 1) {
					// 二维数组存储的数据 取出
					const _row = this.spanArr[rowIndex];
					const _col = _row > 0 ? 1 : 0;
					return {
						rowspan: _row,
						colspan: _col,
					};
					//不可以return {rowspan：0， colspan: 0} 会造成数据不渲染， 也可以不写else，eslint过不了的话就返回false
				} else {
					return false;
				}
			},
		},
	};
</script>