<template>
	<div class="app-container">
		<el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
			<el-form-item label="计划日期" prop="planTime">
        <el-date-picker
          v-model="timeList"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
			</el-form-item>
<!--      <el-form-item label="同步状态">-->
<!--        <el-select v-model="queryParams.syncFlag" placeholder="请选择同步状态">-->
<!--          <el-option label="已同步" value="1"></el-option>-->
<!--          <el-option label="未同步" value="0"></el-option>-->
<!--        </el-select>-->
<!--      </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"
					plain
					icon="el-icon-plus"
					size="mini"
					@click="handleAdd"
					v-hasPermi="['mes:plan:add']"
				>新增</el-button>
			</el-col>
<!--			<el-col :span="1.5">-->
<!--				<el-button-->
<!--					type="success"-->
<!--					plain-->
<!--					icon="el-icon-edit"-->
<!--					size="mini"-->
<!--					:disabled="single"-->
<!--					@click="handleUpdate"-->
<!--					v-hasPermi="['mes:plan:edit']"-->
<!--				>修改</el-button>-->
<!--			</el-col>-->
			<el-col :span="1.5">
				<el-button
					type="danger"
					plain
					icon="el-icon-delete"
					size="mini"
					:disabled="multiple"
					@click="handleDelete"
					v-hasPermi="['mes:plan:remove']"
				>删除</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button
					type="warning"
					plain
					icon="el-icon-download"
					size="mini"
					@click="handleExport"
					v-hasPermi="['mes:plan:export']"
				>导出</el-button>
			</el-col>
			<right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
		</el-row>

		<el-table v-loading="loading" :data="planList" @selection-change="handleSelectionChange">
			<el-table-column type="selection" width="55" align="center" />
<!--			<el-table-column label="ID" align="center" prop="id" />-->
			<el-table-column label="计划工厂编码" align="center" prop="factoryCode" />
			<el-table-column label="计划日期" align="center" prop="planTime" width="180">
				<template slot-scope="scope">
					<span>{{ parseTime(scope.row.planTime, '{y}-{m}-{d}') }}</span>
				</template>
			</el-table-column>
			<el-table-column label="已同步" align="center" prop="syncFlag" />
			<el-table-column label="创建人" align="center" prop="createBy" />
			<el-table-column label="创建时间" align="center" prop="createTime" width="180">
				<template slot-scope="scope">
					<span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
				</template>
			</el-table-column>
			<el-table-column label="更新人" align="center" prop="updateBy" />
			<el-table-column label="更新时间" align="center" prop="updateTime" width="180">
				<template slot-scope="scope">
					<span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
				</template>
			</el-table-column>
			<el-table-column label="操作" align="center" class-name="small-padding fixed-width">
				<template slot-scope="scope">
					<el-button
						size="mini"
						type="text"
						icon="el-icon-edit"
						@click="handleUpdate(scope.row)"
						v-hasPermi="['mes:plan:edit']"
					>修改</el-button>
					<el-button
						size="mini"
						type="text"
						icon="el-icon-delete"
						@click="handleDelete(scope.row)"
						v-hasPermi="['mes:plan:remove']"
					>删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<pagination
			v-show="total>0"
			:total="total"
			:page.sync="queryParams.pageNum"
			:limit.sync="queryParams.pageSize"
			@pagination="getList"
		/>

		<!-- 添加或修改湿料计划管理对话框 -->
		<el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <!-- 选择工单生产日期 -->
      <el-row>
        <el-col :offset="8" :span="8">
          <el-date-picker
            @change="workOrderTimeChange"
            v-model="workOrderTime"
            type="date"
            placeholder="工单日期">
          </el-date-picker>
        </el-col>
      </el-row>
      <!-- 工单列表 -->
      <el-row>
        <el-table
          ref="multipleTable"
          v-if="refreshWorkTable"
          v-loading="workLoading"
          :data="workOrderList"
          tooltip-effect="dark"
          style="width: 100%"
          @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column width="60" align="center" label="序号" type="index" :index="indexMethod"></el-table-column>
          <el-table-column prop="workorderCode" label="工单编码" width="120"></el-table-column>
          <el-table-column prop="productName" label="产品名称" width="120"></el-table-column>
          <el-table-column prop="productDate" label="工单日期" show-overflow-tooltip></el-table-column>
          <el-table-column prop="shiftDesc" label="班次" show-overflow-tooltip></el-table-column>
          <el-table-column prop="" label="料罐" show-overflow-tooltip></el-table-column>
          <el-table-column prop="" label="物料" show-overflow-tooltip></el-table-column>
        </el-table>
      </el-row>
      <!-- 料罐-物料-计划日期的选择 -->
      <el-form :model="form" ref="dynamicForm" label-width="80px">
      <el-row>
        <!-- 选择料罐 -->
        <el-col :span="8">
          <el-form-item size="small" label="选择料罐:">
            <el-select v-model="form.bucketId" placeholder="请选择料罐">
              <el-option v-for="item in selectBucketList" :key="item.bucketId" :label="item.bucketName"
                         :value="item.bucketId"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      </el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="submitForm">确 定</el-button>
				<el-button @click="cancel">取 消</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
import { getBucketList,getWorkOrderList,listPlan, getPlan, delPlan, addPlan, updatePlan } from "@/api/mes/plan";

export default {
	name: "Plan",
	data() {
		return {
		  // 料罐的选择list
      selectBucketList: null,
		  // 上工单遮罩层
      workLoading: false,
		  // 上工单渲染
      refreshWorkTable: true,
		  // 工单新增工单list
      workOrderList: [],
		  // 新增-查询-工单日期
      workOrderTime: null,
		  // 首日期查询
      timeList: null,
			// 遮罩层
			loading: true,
			// 选中数组
			ids: [],
			// 非单个禁用
			single: true,
			// 非多个禁用
			multiple: true,
			// 显示搜索条件
			showSearch: true,
			// 总条数
			total: 0,
			// 湿料计划管理表格数据
			planList: [],
			// 弹出层标题
			title: "",
			// 是否显示弹出层
			open: false,
			// 查询参数
			queryParams: {
				pageNum: 1,
				pageSize: 10,
				planTime: null,
				syncFlag: null,
        startTime: null,
        endTime: null,
			},
			// 表单参数
			form: {
        bucketId: null,
      },
			// 表单校验
			rules: {
			}
		};
	},
	created() {
		this.getList();
	},
	methods: {
	  /** 新增-选择工单日期 */
    workOrderTimeChange(e) {
      // 转换日期格式
      const year = e.getFullYear(); // 获取年份
      const month = String(e.getMonth() + 1).padStart(2, '0'); // 获取月份
      const day = String(e.getDate()).padStart(2, '0'); // 获取日期
      const productDate = `${year}-${month}-${day}`;

      getWorkOrderList(productDate).then(response => {
        this.workOrderList = response.data;
        // 刷新表格
        // 在获取到新的数据后执行以下代码
        this.workLoading = true; // 设置加载状态为true，表示正在加载
        this.refreshWorkTable = false; // 先将refreshProTable设置为false，隐藏表格
        this.$nextTick(() => {
          // 使用$nextTick来等待DOM更新完成
          this.refreshWorkTable = true; // 立即将refreshProTable设置为true，显示表格
          this.workLoading = false; // 设置加载状态为false，表示加载完成
        });
      })
    },
		/** 查询湿料计划管理列表 */
		getList() {
			this.loading = true;
			listPlan(this.queryParams).then(response => {
				this.planList = response.rows;
				this.total = response.total;
				this.loading = false;
			});
		},
		// 取消按钮
		cancel() {
			this.open = false;
			this.reset();
		},
		// 表单重置
		reset() {
			this.form = {
				id: null,
				factoryCode: null,
				planTime: null,
				syncFlag: null,
				createBy: null,
				createTime: null,
				updateBy: null,
				updateTime: null,
				orderType: null,
				prodCode: null,
				prodDesc: null,
				prodSource: null,
				quantity: null,
				unit: null,
				atrr1: null,
				atrr2: null,
				atrr3: null,
				status: null,
				prodType: null,
				planCode: null
			};
			this.resetForm("form");
		},
		/** 搜索按钮操作 */
		handleQuery() {
		  console.log("这里是你要的数据");
      console.log(this.timeList);
      if (this.timeList.length>1){
        // 赋值
        const year = this.timeList[0].getFullYear(); // 获取年份
        const month = String(this.timeList[0].getMonth() + 1).padStart(2, '0'); // 获取月份
        const day = String(this.timeList[0].getDate()).padStart(2, '0'); // 获取日期
        const startTime = `${year}-${month}-${day}`;

        this.queryParams.startTime = startTime;

        const year1 = this.timeList[1].getFullYear(); // 获取年份
        const month1 = String(this.timeList[1].getMonth() + 1).padStart(2, '0'); // 获取月份
        const day1 = String(this.timeList[1].getDate()).padStart(2, '0'); // 获取日期
        const endTime = `${year1}-${month1}-${day1}`;

        this.queryParams.endTime = endTime;
      }else {
        this.queryParams.startTime = null;
        this.queryParams.endTime = null;
      }

			this.queryParams.pageNum = 1;
			this.getList();
		},
		/** 重置按钮操作 */
		resetQuery() {
			this.resetForm("queryForm");
			this.timeList = [];
			this.handleQuery();
		},
		// 多选框选中数据
		handleSelectionChange(selection) {
			this.ids = selection.map(item => item.id)
			this.single = selection.length!==1
			this.multiple = !selection.length
		},
		/** 新增按钮操作 */
		handleAdd() {
		  // 刷新缓存
			this.reset();
			this.selectBucketList = null;
			this.workOrderTime = null;
			this.workOrderList = [];
			// 数据初始化
      this.workOrderTime = new Date();
      // 一会完成下方数据同步
			// 获取料罐list
      getBucketList().then(response => {
        this.selectBucketList = response.data;
      })
			this.open = true;
			this.title = "新增湿料计划";
		},
		/** 修改按钮操作 */
		handleUpdate(row) {
			this.reset();
			const id = row.id || this.ids
			getPlan(id).then(response => {
				this.form = response.data;
				this.open = true;
				this.title = "修改湿料计划管理";
			});
		},
		/** 提交按钮 */
		submitForm() {
			this.$refs["form"].validate(valid => {
				if (valid) {
					if (this.form.id != null) {
						updatePlan(this.form).then(response => {
							this.$modal.msgSuccess("修改成功");
							this.open = false;
							this.getList();
						});
					} else {
						addPlan(this.form).then(response => {
							this.$modal.msgSuccess("新增成功");
							this.open = false;
							this.getList();
						});
					}
				}
			});
		},
		/** 删除按钮操作 */
		handleDelete(row) {
			const ids = row.id || this.ids;
			this.$modal.confirm('是否确认删除湿料计划管理编号为"' + ids + '"的数据项？').then(function() {
				return delPlan(ids);
			}).then(() => {
				this.getList();
				this.$modal.msgSuccess("删除成功");
			}).catch(() => {});
		},
		/** 导出按钮操作 */
		handleExport() {
			this.download('mes/plan/export', {
				...this.queryParams
			}, `plan_${new Date().getTime()}.xlsx`)
		}
	}
};
</script>
<style>
  .el-row {
    margin-bottom: 20px;
  &:last-child {
     margin-bottom: 0;
   }
  }
  .el-col {
    border-radius: 4px;
  }
  .bg-purple-dark {
    background: #99a9bf;
  }
  .bg-purple {
    background: #d3dce6;
  }
  .bg-purple-light {
    background: #e5e9f2;
  }
  .grid-content {
    border-radius: 4px;
    min-height: 36px;
  }
  .row-bg {
    padding: 10px 0;
    background-color: #f9fafc;
  }
</style>
