<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"
          value-format="yyyy-MM-dd"
          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="Y"></el-option>-->
      <!--          <el-option label="未同步" value="N"></el-option>-->
      <!--        </el-select>-->
      <!--      </el-form-item>-->
      <el-form-item label="同步状态">
        <el-select v-model="queryParams.syncFlag" placeholder="请选择同步状态" clearable>
          <el-option
            v-for="dict in dict.type.sys_yes_no"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </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">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.syncFlag"/>
        </template>
      </el-table-column>
      <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%"
            max-height="240"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column width="60" align="center" label="序号" type="index"></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="bucketName1" label="料罐"></el-table-column>
            <el-table-column prop="materialName1" 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="7">
            <el-form-item size="small" label="选择物料:">
              <el-input @focus="selectMateriel" readonly v-model="form.productName" placeholder="点击选择物料"/>
              <!--              <el-select v-if="false" 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 :offset="1" :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%"
            max-height="240"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column width="60" align="center" label="序号" type="index"></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-column label="操作" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="deleteSelectWork(scope.row)"
                >删除
                </el-button>
              </template>
            </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>

    <!-- 修改计划模块 -->
    <el-dialog title="修改计划模块" :visible.sync="dialogVisible" 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="wetMaterialPlanList"
            tooltip-effect="dark"
            style="width: 100%"
            max-height="240"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column width="60" align="center" label="序号" type="index"></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-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="7">
            <el-form-item size="small" label="选择物料:">
              <el-input @focus="selectMateriel" readonly v-model="form.productName" placeholder="点击选择物料"/>
              <!--              <el-select v-if="false" 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 :offset="1" :span="8">
            <el-form-item size="small" label="计划日期: ">
              <el-date-picker readonly @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="changeBatchBtn" 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%"
            max-height="240"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column width="60" align="center" label="序号" type="index"></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-column label="操作" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="deleteSelectWorkUpdate(scope.row)"
                >删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="updateForm">提 交</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      width="800px"
      title="物料选择"
      :visible.sync="innerVisible"
      append-to-body>

      <el-form :model="materielQueryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
               label-width="68px">
        <el-form-item label="物料编码" prop="productCode">
          <el-input
            v-model="materielQueryParams.productCode"
            placeholder="请输入物料编码"
            clearable
            @keyup.enter.native="handleMaterielQuery"
          />
        </el-form-item>
        <el-form-item label="物料名称" prop="productCode">
          <el-input
            v-model="materielQueryParams.productDescZh"
            placeholder="请输入物料名称"
            clearable
            @keyup.enter.native="handleMaterielQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleMaterielQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 物料列表展示 -->
      <el-table v-loading="loading" :data="materielList" @selection-change="selectionChange">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column width="60" align="center" label="序号" type="index"></el-table-column>
        <el-table-column label="物料编码" align="center" prop="productCode"/>
        <el-table-column label="物料名称" align="center" prop="productDescZh"/>
      </el-table>

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

      <el-button @click="subMateriel" class="my-materiel-btn" type="primary">确定</el-button>

    </el-dialog>

  </div>
</template>

<script>
import {
  updatePlanDetail,
  getPlanDetailList,
  addWetPlan,
  getBMSList,
  getProductList,
  getBucketList,
  getWorkOrderList,
  listPlan,
  getPlan,
  delPlan,
  addPlan,
  updatePlan,
  checkChangePlan
} from '@/api/plan/plan'
import moment from 'moment'
import {selectMaterielList} from "@/api/plan/order";

export default {
  name: 'Plan',
  dicts: ['sys_yes_no'],
  data() {
    return {
      // 修改校验
      checkUpdate: true,
      // 新增-物料list
      materiel: [],
      materielList: [],
      // 物料查询数据实体
      materielQueryParams: {
        mtart: 'material_type1',
        productCode: undefined,
        productDescZh: undefined,
        pageNum: 1,
        pageSize: 10,
      },
      // 内层弹窗-新增订单
      innerVisible: false,
      // 湿料计划详情list
      wetMaterialPlanList: [],
      // 修改计划弹出框
      dialogVisible: false,
      // 校验是否能提交
      checkSelect: true,
      // selectList
      selectList: null,
      // 当前计划日期下的BMS
      bmsList: [],
      // 新增下方的工单表
      newWorkOrderList: [],
      // 物料的选择list
      selectProductList: null,
      // 料罐的选择list
      selectBucketList: null,
      // 上工单遮罩层
      workLoading: false,
      // 上工单渲染
      refreshWorkTable: true,
      // 工单新增工单list
      workOrderList: [],
      // 新增-查询-工单日期
      workOrderTime: null,
      // 首日期查询
      timeList: [],
      // 遮罩层
      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,
        productName: null
      },
      // 表单校验
      rules: {}
    }
  },
  created() {
    this.timeList = [new Date(), new Date()]
    this.queryParams.startTime = moment(this.timeList[0]).format('YYYY-MM-DD')
    this.queryParams.endTime = moment(this.timeList[1]).format('YYYY-MM-DD')
    this.getList()
  },
  methods: {
    // 新增-删除选好的工单
    deleteSelectWork(e) {
      // 清除下方数据
      for (let i =0; i < this.newWorkOrderList.length; i++) {
        if (e.workorderCode == this.newWorkOrderList[i].workorderCode) {
          this.newWorkOrderList.splice(i,1);
        }
      }

      // 清除上方数据
      let newMaterialName1 = "";
      let newBucketName1 = "";
      for (let i =0; i < this.workOrderList.length; i++) {
        if (e.workorderCode == this.workOrderList[i].workorderCode) {
          // 物料
          let materialNameArray = this.workOrderList[i].materialName1.split(',');
          let materialFlag = true;
          for (let j = materialNameArray.length - 2; j >= 0; j--) {
            if (e.materialName == materialNameArray[j] && materialFlag) {
              materialNameArray.splice(j,1);
              materialFlag = false;
            }else {
              newMaterialName1 += materialNameArray[j]+",";
            }
          }

          // 料罐
          let bucketArray = this.workOrderList[i].bucketName1.split(',');
          let bucketFlag = true;
          for (let j = bucketArray.length - 2; j >= 0; j--) {
            if (e.bucketName == bucketArray[j] && bucketFlag) {
              bucketArray.splice(j,1);
              bucketFlag = false;
            }else {
              newBucketName1 += bucketArray[j]+",";
            }
          }

          this.workOrderList[i].materialName1 = newMaterialName1;
          this.workOrderList[i].bucketName1 = newBucketName1;

        }
      }
    },
    // 修改-删除选好的工单
    deleteSelectWorkUpdate(e) {
      // 清除下方数据
      for (let i =0; i < this.newWorkOrderList.length; i++) {
        if (e.workorderCode == this.newWorkOrderList[i].workorderCode) {
          this.newWorkOrderList.splice(i,1);
        }
      }

      // 清除上方数据
      let newMaterialName1 = "";
      let newBucketName1 = "";
      for (let i =0; i < this.wetMaterialPlanList.length; i++) {
        if (e.workorderCode == this.wetMaterialPlanList[i].workorderCode) {
          // 物料
          let materialNameArray = this.wetMaterialPlanList[i].materialName.split(',');
          let materialFlag = true;
          for (let j = materialNameArray.length - 2; j >= 0; j--) {
            if (e.materialName == materialNameArray[j] && materialFlag) {
              materialNameArray.splice(j,1);
              materialFlag = false;
            }else {
              newMaterialName1 += materialNameArray[j]+",";
            }
          }

          // 料罐
          let bucketArray = this.wetMaterialPlanList[i].bucketName.split(',');
          let bucketFlag = true;
          for (let j = bucketArray.length - 2; j >= 0; j--) {
            if (e.bucketName == bucketArray[j] && bucketFlag) {
              bucketArray.splice(j,1);
              bucketFlag = false;
            }else {
              newBucketName1 += bucketArray[j]+",";
            }
          }

          this.wetMaterialPlanList[i].materialName = newMaterialName1;
          this.wetMaterialPlanList[i].bucketName = newBucketName1;

        }
      }
    },
    // 新增-物料搜索
    handleMaterielQuery() {
      this.materielQueryParams.pageNum = 1;
      this.getMaterielList();
    },
    // 选中物料信息
    selectionChange(e) {
      this.materiel = e;
    },
    // 新增-确认选择物料
    subMateriel() {
      if (this.materiel.length == 0) {
        this.$message({
          message: '请选择物料！',
          type: 'warning'
        })
        return
      }
      if (this.materiel.length > 1) {
        this.$message({
          message: '物料只能选择一个！',
          type: 'warning'
        })
        return
      }
      this.form.productId = this.materiel[0].productId;
      this.form.prodCode = this.materiel[0].productCode;
      this.form.prodDesc = this.materiel[0].productDescZh;

      this.form.productName = this.materiel[0].productDescZh;

      this.innerVisible = false;
    },
    // 新增-查询物料列表
    getMaterielList() {
      this.loading = true;
      selectMaterielList(this.materielQueryParams).then(response => {
          this.materielList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    // 新增-打开选择物料窗口
    selectMateriel() {
      // 清除搜索缓存
      this.materielQueryParams.productCode = null;
      this.materielQueryParams.productDescZh = null;
      this.innerVisible = true;
      this.getMaterielList();
    },
    /** 修改-确定按钮 */
    changeBatchBtn() {
      // 数据判空
      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 bms = {
        bucketId: this.form.bucketId,
        materialId: this.form.productId,
        shiftId: this.selectList[0].shiftId
      }
      if (this.bmsList != null || this.bmsList === undefined) {
        for (let i = 0; i < this.bmsList.length; i++) {
          if (bms.shiftId == this.bmsList[i].shiftId && bms.bucketId == this.bmsList[i].bucketId && bms.materialId != this.bmsList[i].materialId) {
            this.$message({
              message: '同班次同料罐下不能混料！',
              type: 'warning'
            })
            return
          }
        }
      }

      //   清空
      if (this.checkUpdate) {
        for (let i = 0; i < this.wetMaterialPlanList.length; i++){
          this.wetMaterialPlanList[i].materialName = null;
          this.wetMaterialPlanList[i].bucketName = null;
        }
        this.checkUpdate = false;
      }

      // 数据保存（仅前端）
      // 创建料罐对象
      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]
        }
      }

      //   检验工单-物料-料罐
      for (let i = 0; i < this.selectList.length; i++) {
        for (let j = 0; j < this.wetMaterialPlanList.length; j++) {
          if (this.selectList[i].workorderCode == this.wetMaterialPlanList[j].workorderCode) {
            // 物料
            if (this.wetMaterialPlanList[j].materialName != null) {
              let materialNameArray = this.wetMaterialPlanList[j].materialName.split(',');
              for (let i = materialNameArray.length - 2; i >= 0; i--) {
                if (material.productDesc != materialNameArray[i]) {
                  this.$message({
                    message: '同一工单只能选一个物料！',
                    type: 'warning'
                  })
                  return
                }
              }
            }

            // 料罐
            if (this.wetMaterialPlanList[j].bucketName != null) {
              let bucketArray = this.wetMaterialPlanList[j].bucketName.split(',');
              for (let i = bucketArray.length - 1; i >= 0; i--) {
                if (bucket.bucketName == bucketArray[i]) {
                  this.$message({
                    message: '料罐重复！',
                    type: 'warning'
                  })
                  return
                }
              }
            }
          }
        }
      }

      this.bmsList.push(bms)


      //   将选择的信息放入newList
      for (let i = 0; i < this.selectList.length; i++) {

        // 创建一个新工单对象
        var workOrder = {
          productName: null,
          factoryCode: null,
          workorderId: null,
          workorderCode: null,
          bucketId: null,
          bucketCode: null,
          bucketName: null,
          materialId: null,
          materialCode: null,
          materialName: null,
          shiftId: null,
          shiftDesc: null,
          planTime: null,
          productDate: null,
        };

        workOrder.bucketCode = bucket.bucketCode;
        workOrder.bucketId = bucket.bucketId;
        workOrder.bucketName = bucket.bucketName;
        workOrder.materialId = material.productId;
        workOrder.materialCode = material.productCode;
        workOrder.materialName = material.productDesc;
        workOrder.shiftId = this.selectList[i].shiftId;
        workOrder.shiftDesc = this.selectList[i].shiftDesc;
        workOrder.planTime = this.form.planTime;
        workOrder.productDate = this.selectList[i].productDate;
        workOrder.productName = this.selectList[i].productName;
        workOrder.workorderId = this.selectList[i].workorderId;
        workOrder.workorderCode = this.selectList[i].workorderCode;

        // 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(workOrder)
      }

      // //   将选择的数据在上方的列表中删除
      for (let i = 0; i < this.selectList.length; i++) {
        for (let j = 0; j < this.wetMaterialPlanList.length; j++) {
          if (this.selectList[i].workorderCode == this.wetMaterialPlanList[j].workorderCode) {
            if (this.wetMaterialPlanList[j].bucketName == null) {
              this.wetMaterialPlanList[j].bucketName = "";
            }
            this.wetMaterialPlanList[j].bucketName += bucket.bucketName + ",";
            if (this.wetMaterialPlanList[j].materialName == null) {
              this.wetMaterialPlanList[j].materialName = "";
            }
            this.wetMaterialPlanList[j].materialName += material.productDesc + ",";
          }
        }
      }
      // const selectedCodes = this.selectList.map(item => item.workorderCode)
      // this.wetMaterialPlanList = this.wetMaterialPlanList.filter(item => !selectedCodes.includes(item.workorderCode))

      // 重置数据
      this.form.bucketId = null
      this.form.productId = null
      this.form.productName = null
    },
    /** 新增-确定按钮 */
    batchBtn() {
      // 数据判空
      if (this.selectList == null || this.selectList === undefined) {
        this.$message({
          message: '请选择工单！',
          type: 'warning'
        })
        return
      }
      if (this.form.bucketId == null) {
        this.$message({
          message: '请选择料管！',
          type: 'warning'
        })
        return
      }
      if (this.form.productId == null) {
        this.$message({
          message: '请选择物料！',
          type: 'warning'
        })
        return
      }
      // 数据校验班次冲突问题
      if (this.checkSelect === false) {
        this.$message({
          message: '班次冲突请重新选择！',
          type: 'warning'
        })
        return
      }

      // 校验数据班次、物料、料罐
      var bms = {
        bucketId: this.form.bucketId,
        materialId: this.form.productId,
        shiftId: this.selectList[0].shiftId
      }
      if (this.bmsList != null || this.bmsList === undefined) {
        for (let i = 0; i < this.bmsList.length; i++) {
          if (bms.shiftId == this.bmsList[i].shiftId && bms.bucketId == this.bmsList[i].bucketId && bms.materialId != this.bmsList[i].materialId) {
            this.$message({
              message: '同班次同料罐下不能混料！',
              type: 'warning'
            })
            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]
        }
      }

      // 检验工单-物料-料罐
      for (let i = 0; i < this.selectList.length; i++) {
        for (let j = 0; j < this.workOrderList.length; j++) {
          if (this.selectList[i].workorderCode == this.workOrderList[j].workorderCode) {
            // 物料
            if (this.workOrderList[j].materialName1 != null) {
              let materialNameArray = this.workOrderList[j].materialName1.split(',');
              for (let i = materialNameArray.length - 2; i >= 0; i--) {
                if (material.productDesc != materialNameArray[i]) {
                  this.$message({
                    message: '同一工单只能选一个物料！',
                    type: 'warning'
                  })
                  return
                }
              }
            }
            // 料罐
            if (this.workOrderList[j].bucketName1 != null) {
              let bucketArray = this.workOrderList[j].bucketName1.split(',');
              for (let i = bucketArray.length - 1; i >= 0; i--) {
                if (bucket.bucketName == bucketArray[i]) {
                  this.$message({
                    message: '料罐重复！',
                    type: 'warning'
                  })
                  return
                }
              }
            }
          }
        }
      }

      this.bmsList.push(bms)


      // 将选择的信息放入newList
      for (let i = 0; i < this.selectList.length; i++) {

        // 创建一个新工单对象
        var workOrder = {
          productName: null,
          factoryCode: null,
          workorderId: null,
          workorderCode: null,
          bucketId: null,
          bucketCode: null,
          bucketName: null,
          materialId: null,
          materialCode: null,
          materialName: null,
          shiftId: null,
          shiftDesc: null,
          planTime: null,
          productDate: null,
        };

        workOrder.bucketCode = bucket.bucketCode;
        workOrder.bucketId = bucket.bucketId;
        workOrder.bucketName = bucket.bucketName;
        workOrder.materialId = material.productId;
        workOrder.materialCode = material.productCode;
        workOrder.materialName = material.productDesc;
        workOrder.shiftId = this.selectList[i].shiftId;
        workOrder.shiftDesc = this.selectList[i].shiftDesc;
        workOrder.planTime = this.form.planTime;
        workOrder.productDate = this.selectList[i].productDate;
        workOrder.productName = this.selectList[i].productName;
        workOrder.workorderId = this.selectList[i].workorderId;
        workOrder.workorderCode = this.selectList[i].workorderCode;

        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(workOrder)
      }

      // 将选择的数据在上方的列表中删除
      // const selectedCodes = this.selectList.map(item => item.workorderCode)
      for (let i = 0; i < this.selectList.length; i++) {
        for (let j = 0; j < this.workOrderList.length; j++) {
          if (this.selectList[i].workorderCode == this.workOrderList[j].workorderCode) {
            if (this.workOrderList[j].bucketName1 == null) {
              this.workOrderList[j].bucketName1 = "";
            }
            this.workOrderList[j].bucketName1 += this.selectList[i].bucketName + ",";
            if (this.workOrderList[j].materialName1 == null) {
              this.workOrderList[j].materialName1 = "";
            }
            this.workOrderList[j].materialName1 += this.selectList[i].materialName + ",";
          }
        }
      }
      // this.workOrderList = this.workOrderList.filter(item => !selectedCodes.includes(item.workorderCode))

      // 重置数据
      this.form.bucketId = null
      this.form.productId = null
      this.form.productName = null
    },
    /** 校验计划日期 */
    checkDate: function (e) {
      if (this.newWorkOrderList.length > 0) {
        this.$message({
          message: '您已生成数据不能更改日期!',
          type: 'warning'
        })
        return
      }
      var now = new Date()
      if (e < now) {
        this.$message({
          message: '日期不得早于今天',
          type: 'warning'
        })
        e = now
        this.form.planTime = now
      }
      // 获取计划日期下已分配的班次、料罐、物料信息list
      var planTime = moment(this.form.planTime).format('YYYY-MM-DD')
      getBMSList(planTime).then(response => {
        if (response.data !== undefined) {
          this.bmsList = response.data
        }
      })
    },
    /** 新增-选择工单日期 */
    workOrderTimeChange(e) {
      // 校验日期并进行计划日期同步
      var now = new Date()
      if (e < now) {
        this.form.planTime = now
      } else {
        this.form.planTime = e
      }
      // 转换日期格式
      var productDate = moment(e).format('YYYY-MM-DD')

      // 在获取到新的数据后执行以下代码
      this.workLoading = true // 设置加载状态为true，表示正在加载
      getWorkOrderList(productDate).then(response => {
        this.workOrderList = response.data
        // 刷新表格
        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.dialogVisible = 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 > 0) {
        this.queryParams.startTime = moment(this.timeList[0]).format('YYYY-MM-DD')
        this.queryParams.endTime = moment(this.timeList[1]).format('YYYY-MM-DD')
      }
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 首-重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.timeList = []
      this.queryParams.syncFlag = null
      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
      var productDate = moment(this.workOrderTime).format('YYYY-MM-DD')

      // 在获取到新的数据后执行以下代码
      this.workLoading = true // 设置加载状态为true，表示正在加载
      getWorkOrderList(productDate).then(response => {
        this.workOrderList = response.data
        // 刷新表格

        this.refreshWorkTable = false // 先将refreshProTable设置为false，隐藏表格
        this.$nextTick(() => {
          // 使用$nextTick来等待DOM更新完成
          this.refreshWorkTable = true // 立即将refreshProTable设置为true，显示表格
          this.workLoading = false // 设置加载状态为false，表示加载完成
        })
      })
      // 获取今天已分配的班次、料罐、物料信息list
      getBMSList(productDate).then(response => {
        if (response.data !== undefined) {
          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.checkUpdate = true;
      checkChangePlan(row.id).then(response => {
        if (response.code == 500) {

        } else {
          // 清除缓存
          this.reset()
          this.selectBucketList = null
          this.workOrderTime = null
          this.workOrderList = []
          this.selectProductList = null
          this.newWorkOrderList = []
          this.bmsList = []
          this.bmapId = null
          // 初始化数据
          this.form.planTime = new Date()
          // 在获取到新的数据后执行以下代码
          this.workLoading = true // 设置加载状态为true，表示正在加载
          // 获取订单详情list
          getPlanDetailList(row.id).then(response => {
            if (response.data !== undefined) {
              this.wetMaterialPlanList = response.data

              this.refreshWorkTable = false // 先将refreshProTable设置为false，隐藏表格
              this.$nextTick(() => {
                // 使用$nextTick来等待DOM更新完成
                this.refreshWorkTable = true // 立即将refreshProTable设置为true，显示表格
                this.workLoading = false // 设置加载状态为false，表示加载完成
              })
            }
          })
          // 获取料罐list
          getBucketList().then(response => {
            this.selectBucketList = response.data
          })
          // 获取物料信息list
          getProductList().then(response => {
            this.selectProductList = response.data
          })

          this.dialogVisible = true
        }
      })

    },
    /** 修改-提交按钮 */
    updateForm() {
      //   必须全部修改
      for (let i = 0; i < this.wetMaterialPlanList.length; i++) {
        if (this.wetMaterialPlanList[i].bucketName == null) {
          this.$message({
            message: '计划要全部重新分配完！',
            type: 'warning'
          })
          return
        }
      }
      // 校验数据判断newList是否为空
      if (this.newWorkOrderList == [] || this.newWorkOrderList.length == 0 || this.newWorkOrderList == null) {
        this.$message({
          message: '提交数据不能为空！',
          type: 'warning'
        })
        return
      }

      // 更新表数据
      updatePlanDetail(this.newWorkOrderList).then(response => {
        if (response.code === 200) {
          this.$message({
            message: '提交成功',
            type: 'success'
          })
        }
      })

      this.dialogVisible = false
      this.getList()
    },
    /** 新增-提交按钮 */
    addSubmitForm() {
      // 校验数据判断newList是否为空
      if (this.newWorkOrderList == [] || this.newWorkOrderList.length == 0 || this.newWorkOrderList == null) {
        this.$message({
          message: '提交数据不能为空！',
          type: 'warning'
        })
        return
      }

      addWetPlan(this.newWorkOrderList).then(response => {
        if (response.code === 200) {
          this.$message({
            message: '提交成功',
            type: 'success'
          })
        }
      })
      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('plan/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;
}

.my-margin {
  margin-top: 40px;
  margin-bottom: 10px;
}

.my-materiel-btn {
  margin-top: 20px;
  margin-left: 650px;
}
</style>
