<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-form :model="form" ref="dynamicForm" label-width="80px">
        <!-- 选择工单生产日期 -->
        <el-row>
          <el-col :span="8">
            <el-form-item size="small" label="工单日期: ">
              <el-date-picker
                @change="workOrderTimeChange"
                v-model="workOrderTime"
                type="date"
                placeholder="工单日期">
              </el-date-picker>
            </el-form-item>
          </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 width="140" align="center" prop="workorderCode" label="工单编码"></el-table-column>
            <el-table-column width="230" align="center" prop="productName" label="产品名称"></el-table-column>
            <el-table-column width="150" align="center" prop="productDate" label="工单日期" show-overflow-tooltip></el-table-column>
            <el-table-column prop="shiftDesc" label="班次"></el-table-column>
            <el-table-column prop="" label="料罐"></el-table-column>
            <el-table-column prop="" label="物料"></el-table-column>
          </el-table>
        </el-row>
        <!-- 料罐-物料-计划日期的选择 -->
        <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-col :span="8">
            <el-form-item size="small" label="选择物料:">
              <el-select v-model="form.productId" placeholder="请选择物料">
                <el-option v-for="item in selectProductList" :key="item.productId" :label="item.productDesc"
                           :value="item.productId"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- 选择日期 -->
          <el-col :span="8">
            <el-form-item size="small" label="计划日期: ">
              <el-date-picker @change="checkDate" v-model="form.planTime" type="date" placeholder="选择日期"></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 确定按钮 -->
        <el-row>
          <el-col :offset="11" :span="8">
            <el-button @click="batchBtn" type="primary">确定</el-button>
          </el-col>
        </el-row>
        <!-- 变化的工单表 -->
        <el-row>
          <el-table
            ref="multipleTable"
            v-if="refreshWorkTable"
            v-loading="workLoading"
            :data="newWorkOrderList"
            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 width="140" align="center" prop="workorderCode" label="工单编码"></el-table-column>
            <el-table-column width="230" align="center" prop="productName" label="产品名称"></el-table-column>
            <el-table-column width="150" align="center" prop="productDate" label="工单日期" show-overflow-tooltip></el-table-column>
            <el-table-column prop="shiftDesc" label="班次"></el-table-column>
            <el-table-column prop="bucketName" label="料罐"></el-table-column>
            <el-table-column prop="materialName" label="物料"></el-table-column>
          </el-table>
        </el-row>
      </el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="addSubmitForm">提 交</el-button>
				<el-button @click="cancel">取 消</el-button>
			</div>
		</el-dialog>
	</div>
</template>

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

export default {
	name: "Plan",
	data() {
		return {
		  // 校验是否能提交
      checkSelect: true,
		  // selectList
      selectList: null,
		  // 当前计划日期下的BMS
      bmsList: null,
		  // 新增下方的工单表
      newWorkOrderList: [],
		  // 物料的选择list
      selectProductList: null,
		  // 料罐的选择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,
        productId: null,
        planTime: null,
      },
			// 表单校验
			rules: {
			}
		};
	},
	created() {
		this.getList();
	},
	methods: {
	  /** 新增-提交按钮 */
    batchBtn() {
      // 数据判空
      if (this.selectList == null || this.selectList === undefined){
        this.$message({
          message: '请选择工单！',
          type: 'warning'
        })
        return;
      }
      if (this.form.bucketId == null || this.form.productId == null){
        this.$message({
          message: '数据不能为空！',
          type: 'warning'
        })
        return;
      }
      // 数据校验班次冲突问题
      if (this.checkSelect === false){
        this.$message({
          message: '班次冲突请重新选择！',
          type: 'warning'
        })
        return;
      }
      // 校验数据班次、物料、料罐
      var bmsList = this.bmsList;
      bmsList.push({
        bucketId: this.form.bucketId,
        materialId: this.form.productId,
        shiftId: this.selectList[0].shiftId,
      });
      if (this.bmsList != 0){
        for (let i = 0;i<bmsList.length;i++){
          for (let j = i;j < bmsList.length;j++){
            if (bmsList[i].shiftId == bmsList[j].shiftId && bmsList[i].bucketId == bmsList[j].bucketId && bmsList[i].materialId != bmsList[j].materialId){
              this.$message({
                message: '同班次下-同料罐下:不能混料！',
                type: 'warning'
              })
              this.bmsList.pop();
              return;
            }
          }
        }
      }

      // 数据保存（仅前端）
      // 创建料罐对象
      var bucket;
      for (let i = 0;i < this.selectBucketList.length;i++){
        if (this.form.bucketId == this.selectBucketList[i].bucketId){
          bucket = this.selectBucketList[i];
        }
      }
      // 创建物料对象
      var material;
      for (let i = 0;i < this.selectProductList.length;i++){
        if (this.form.productId == this.selectProductList[i].productId){
          material = this.selectProductList[i];
        }
      }

      // 将选择的信息放入newList
      for (let i = 0;i < this.selectList.length;i++){
        this.selectList[i].bucketName = bucket.bucketName;
        this.selectList[i].bucketId = bucket.bucketId;
        this.selectList[i].bucketCode = bucket.bucketCode;
        this.selectList[i].materialId = material.productId;
        this.selectList[i].materialCode = material.productCode;
        this.selectList[i].materialName = material.productDesc;
        this.selectList[i].planTime = this.form.planTime;
        this.newWorkOrderList.push(this.selectList[i]);
      }

      // 将选择的数据在上方的列表中删除
      var list = [];
      for (let i = 0; i < this.workOrderList.length; i++){
        for (let j = 0;j < this.selectList.length; j++){
          if (this.workOrderList[i].workorderCode != this.selectList[j].workorderCode){
            list.push(this.workOrderList[i]);
          }
        }
      }
      // 重新赋值worklist
      this.workOrderList = list;

      this.$message('点击了提交按钮！');

      // 重置数据
      this.bmsList = bmsList;
      this.form.bucketId = null;
      this.form.productId = null;

    },
	  /** 校验计划日期 */
    checkDate(e){
      var now = new Date();
      if (e < now){
        this.$message({
          message: '日期不得早于今天',
          type: 'warning'
        })
        e = now;
        this.form.planTime = now;
      }
    },
	  /** 新增-选择工单日期 */
    workOrderTimeChange(e) {
      // 校验日期并进行计划日期同步
      var now = new Date();
      if (e < now){
        this.form.planTime = now;
      }else {
        this.form.planTime = 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() {
      if (this.timeList.length-1>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.checkSelect = true;
      // 如果选择中班次冲突
      for (let i = 0; i < selection.length; i++){
        if (selection[0].shiftId != selection[i].shiftId){
          this.$message({
            message: '班次冲突！',
            type: 'warning'
          });
          this.checkSelect = false;
        }
      }
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
      // 将选择的信息放入selectList
      this.selectList = selection;
		},
		/** 新增按钮操作 */
		handleAdd() {
		  // 刷新缓存
			this.reset();
			this.selectBucketList = null;
			this.workOrderTime = null;
			this.workOrderList = [];
			this.selectProductList = null;
			this.newWorkOrderList = [];
			this.bmapId = null;
			// 数据初始化
      this.workOrderTime = new Date();
      this.form.planTime = new Date();
      // 获取当前日期下的未被分配的工单list
      // 转换日期格式
      const year = this.workOrderTime.getFullYear(); // 获取年份
      const month = String(this.workOrderTime.getMonth() + 1).padStart(2, '0'); // 获取月份
      const day = String(this.workOrderTime.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，表示加载完成
        });
      })
      getBMSList(productDate).then(response => {
        this.bmsList = response.data;
      })
      // 一会完成下方数据同步
			// 获取料罐list
      getBucketList().then(response => {
        this.selectBucketList = response.data;
      })
      // 获取物料信息list
      getProductList().then(response => {
        this.selectProductList = 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 = "修改湿料计划管理";
			});
		},
		/** 新增-提交按钮 */
		addSubmitForm() {
		  // 校验数据判断newList是否为空
      if (this.newWorkOrderList == [] || this.newWorkOrderList.length == 0 || this.newWorkOrderList == null){
        this.$message({
          message:'提交数据不能为空！',
          type:'warning'
        })
        return;
      }


      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>
