<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="factoryCode" label-width="100px">
        <el-input
          v-model="queryParams.factoryCode"
          placeholder="请输入计划工厂编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单号" prop="orderCode" label-width="100px">
        <el-input
          v-model="queryParams.orderCode"
          placeholder="请输入订单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="物料号" prop="prodCode" label-width="100px">
        <el-input
          v-model="queryParams.prodCode"
          placeholder="请输入物料号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="物料名称" prop="prodDesc" label-width="100px">
        <el-input
          v-model="queryParams.prodDesc"
          placeholder="请输入物料名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="拆分状态" prop="status" label-width="100px">
        <el-select v-model="queryParams.status" placeholder="请选择拆分状态" clearable>
          <el-option
            v-for="dict in dict.type.order_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label-width="140px" label="计划生产日期" prop="productDateArray">
        <el-date-picker
          v-model="queryParams.planDateArray"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        >
        </el-date-picker>
      </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="['plan:whiteOrder:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['mes:pro:order:import']"
        >导入
        </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:pro:order:export']"
        >导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-sort"
          size="mini"
          @click="toggleExpandAll"
        >展开/折叠
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="whiteOrderList"
      style="width: 100%"
      max-height="480"
      row-key="orderCode"
      :default-expand-all="isExpandAll"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column width="100" label="计划工厂编码" prop="factoryCode"/>
      <el-table-column width="" label="订单类型" align="center" prop="orderType" v-if="false"/>
      <el-table-column width="200" label="订单号" align="center" prop="orderCode"/>
      <el-table-column width="180" label="物料号" align="center" prop="prodCode"/>
      <el-table-column width="200" label="物料名称" align="center" prop="prodDesc"/>
      <el-table-column width="90" label="订单数量" align="center" prop="quantity"/>
      <el-table-column width="90" label="已拆分数量" align="center" prop="quantitySplit"/>
      <el-table-column width="70" label="单位" align="center" prop="unit"/>
      <el-table-column width="180" label="任务清单" align="center" prop="workerOrder" v-if="false"/>
      <el-table-column width="120" label="计划生产日期" align="center" prop="planProDate">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.planProDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column width="120" label="计划完成日期" align="center" prop="planComplete">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.planComplete, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="" align="center" prop="atrr1" v-if="false"/>
      <el-table-column label="" align="center" prop="atrr2" v-if="false"/>
      <el-table-column label="" align="center" prop="atrr3" v-if="false"/>
      <el-table-column label="订单状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.order_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="上级工单" align="center" prop="parentOrder" v-if="false"/>
      <el-table-column width="100" label="产品类型" align="center" prop="prodType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.product_type" :value="scope.row.prodType"/>
        </template>
      </el-table-column>
      <el-table-column width="120" label="创建时间" align="center" prop="createTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.planComplete, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column width="120" label="更新时间" align="center" prop="updateTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.planComplete, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" width="200" label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            v-if="scope.row.parentOrder != 0"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['plan:whiteOrder:edit']"
          >拆分
          </el-button>
          <el-button
            v-if="false"
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
            v-hasPermi="['plan:whiteOrder:add']"
          >新增
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            v-if="scope.row.parentOrder == 0"
            @click="handleDelete(scope.row)"
            v-hasPermi="['plan:whiteOrder:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增模块 -->
    <el-dialog title="新增订单" :visible.sync="dialogVisible" width="900px" append-to-body>

      <!-- 新增模块-选择物料 -->
      <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="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center"/>
          <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>

      <el-form ref="form" :model="form" :rules="addrules" label-width="80px">
        <!-- 第一行 -->
        <el-row>
          <!-- 第一列 -->
          <el-col :offset="1" :span="9">
            <el-form-item label-width="100px" label="物料号" prop="prodCode">
              <el-input @focus="selectMateriel" readonly v-model="form.prodCode" placeholder="点击选择物料"/>
            </el-form-item>
          </el-col>
          <!-- 第二列 -->
          <el-col :offset="1" :span="9">
            <el-form-item label-width="100px" label="物料名称" prop="prodDesc">
              <el-input @focus="selectMateriel" readonly v-model="form.prodDesc" placeholder="点击选择物料"/>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 第二行 -->
        <el-row>
          <!-- 第一列 -->
          <el-col :offset="1" :span="8">
            <el-form-item label-width="100px" label="计划生产日期" prop="planProDate">
              <el-date-picker clearable
                              v-model="form.planProDate"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="选择计划生产日期"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <!-- 第二列 -->
          <el-col :offset="2" :span="8">
            <el-form-item label-width="100px" label="计划完成日期" prop="planComplete">
              <el-date-picker clearable
                              v-model="form.planComplete"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="选择计划完成日期"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 第三行 -->
        <el-row>
          <!-- 第一列 -->
          <el-col :offset="1" :span="9">
            <el-form-item label-width="100px" label="订单数量" prop="quantity">
              <el-input @change="addQuantity" type="number" v-model="form.quantity" placeholder="请输入订单数量"/>
            </el-form-item>
          </el-col>
          <!-- 第二列 -->
          <el-col :offset="1" :span="9">
            <el-form-item label-width="100px" label="订单车数" prop="carNum">
              <el-input @change="changeCarNum" type="number" v-model="form.carNum" placeholder="请输入车数"/>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 第四行 -->
        <el-row>
          <el-col :offset="1" :span="9">
            <el-form-item label-width="100px" label="产品类型" prop="prodType">
              <el-select disabled v-model="form.prodType" placeholder="请选择产品类型">
                <el-option
                  v-for="dict in dict.type.product_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- 第二列 -->
          <el-col :offset="1" :span="9">
            <el-form-item label-width="100px" label="单位" prop="unit">
              <el-input v-model="form.unit" placeholder="请输入单位"/>
            </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>

    <!-- 拆分模块 -->
    <el-dialog title="拆分" :visible.sync="splitOpen" width="1000px" append-to-body>
      <!-- 拆分头pro -->
      <el-table
        border
        v-if="refreshProTable"
        v-loading="proLoading"
        :data="productData"
        row-key="orderCode"
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      >
        <el-table-column width="60" align="center" label="序号" type="index"></el-table-column>
        <el-table-column width="150" label="订单编号" prop="orderCode"/>
        <el-table-column width="380" label="产品名称" align="center" prop="prodDesc"/>
        <el-table-column width="60" label="单位" align="center" prop="unit"/>
        <el-table-column width="130" label="产品数量" align="center" prop="quantity"/>
        <el-table-column label="已拆分数量" align="center" prop="quantitySplit"/>
        <el-table-column label="拆分数量" align="center" prop="atrr1"/>
      </el-table>

      <!-- 编辑区 -->
      <el-form class="my-margin" :model="splitForm" ref="dynamicForm" label-width="80px">
        <!-- 编辑框 -->
        <!-- 第一行 -->
        <el-row>
          <el-col :span="7">
            <!-- 选择工艺 -->
            <el-form-item size="small" label="选择工艺:" class="my-select my-first">
              <el-select @change="changeRoute" v-model="splitForm.routeCode" placeholder="请选择工艺">
                <el-option v-for="item in routes" :key="item.routeCode" :label="item.routeName"
                           :value="item.routeCode"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :offset="1" :span="7">
            <el-form-item label="选择设备:">
              <el-cascader
                @focus="changeEquipment"
                :options="eRouteOptions"
                :props="eRouteProps"
                v-model="splitForm.prodLineCodeArray"
                clearable></el-cascader>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 第二行 -->
        <el-row>
          <el-col :span="7">
            <!-- 选择班次 -->
            <el-form-item size="small" label="选择班次:" class="my-select my-first">
              <el-select v-model="splitForm.shiftId" placeholder="请选择班次">
                <el-option v-for="item in workShift" :key="item.shiftId" :label="item.shiftDesc"
                           :value="item.shiftId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :offset="1" :span="7">
            <!-- 拆分数量 -->
            <el-form-item size="small" label="拆分数量:">
              <el-input required type="number" @input="splitNumChange" v-model="splitForm.splitNum"></el-input>
            </el-form-item>
          </el-col>
          <el-col :offset="1" :span="5">
            <!-- 工单日期 -->
            <el-form-item size="small" label="工单日期: ">
              <el-date-picker @change="checkDate" v-model="splitForm.productDate" type="date" placeholder="选择日期"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 第三行 -->
        <el-row v-for="(item, index) in formFields" :key="index">
          <!-- 批次编号 -->
          <el-col :span="7">
            <el-form-item size="small" label="批次编号">
              <el-input @blur="batchCodeChange" v-model="item.batchCode"></el-input>
            </el-form-item>
          </el-col>
          <!-- 批次数量 -->
          <el-col :offset="1" :span="7">
            <el-form-item size="small" label="批次数量">
              <el-input required @input="inBatch" type="number" v-model="item.batchQuantity"></el-input>
            </el-form-item>
          </el-col>
          <!-- 操作 -->
          <el-col :offset="1" :span="4">
            <el-button size="small" v-if="formFields.length > 1" @click="removeField(index)" type="danger">删除
            </el-button>
            <el-button size="small" v-if="index === formFields.length - 1" @click="addField" type="primary">添加
            </el-button>
          </el-col>
        </el-row>
      </el-form>

      <!-- 拆分尾 -->
      <el-table
        border
        :data="splitData"
        v-if="refreshWorkerTable"
        v-loading="workerLoading"
        row-key="workorderCode"
        style="width: 100%"
        max-height="240"
        default-expand-all
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      >
        <el-table-column width="60" align="center" label="序号" type="index"></el-table-column>
        <el-table-column width="200" align="center" prop="workorderCode" label="工单号"></el-table-column>
        <el-table-column width="100" align="center" prop="productDate" label="工单日期"></el-table-column>
        <el-table-column width="150" align="center" prop="prodLineCode" label="生产线体设备"></el-table-column>
        <el-table-column width="80" align="center" prop="quantitySplit" label="数量"></el-table-column>
        <el-table-column width="60" label="单位" align="center" prop="unit"/>
        <el-table-column width="90" label="工艺编码" align="center" prop="routeCode"/>
        <el-table-column width="90" label="班次" align="center" prop="shiftDesc"/>
        <el-table-column align="center" prop="batchCodeList" label="批次号"></el-table-column>
      </el-table>

      <!-- 操作按钮 -->
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="batchBtn">提 交</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>

    </el-dialog>

  </div>
</template>

<script>
import {getSplitInfo,listWhiteOrder, getWhiteOrder, delWhiteOrder, addWhiteOrder, updateWhiteOrder} from "@/api/plan/whiteOrder";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import moment from "moment";
import {getProEquipment, selectMaterielList, subSplitOrder} from "@/api/plan/order";

export default {
  name: "WhiteOrder",
  dicts: ['product_type', 'order_status'],
  components: {
    Treeselect
  },
  data() {
    return {
      // 拆分-班次
      workShift:[],
      // 拆分工艺
      routes: [],
      // 拆分-尾-工单列表加载
      refreshWorkerTable: true,
      workerLoading: false,
      // 拆分-尾-工单数据
      splitData: [],
      // 拆分-批次、批次号
      formFields: [{
        batchCode: '',
        batchQuantity: ''
      }],
      // 拆分-拆分数据
      splitForm: {
        id: null,
        prodLineCodeArray: [],
        splitNum: null,
        productDate: null,
        shiftId: null,
        routeCode: null,
        formFields: []
      },
      // 拆分-拆分订单列表加载
      refreshProTable: true,
      proLoading: false,
      // 拆分-拆分订单列表
      productData: [],
      // 拆分-弹窗
      splitOpen: false,
      // 新增-物料选中list
      selectMaterielList: [],
      // 新增-物料list
      materielList: [],
      // 新增-物料-记录总数
      total: 0,
      // 新增-物料-搜索
      materielQueryParams: {
        productCode: null,
        productDescZh: null,
        pageNum: 1,
        pageSize: 10,
      },
      // 新增-物料选择-弹出层
      innerVisible: false,
      // 新增-弹出层
      dialogVisible: false,
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 白坯订单管理表格数据
      whiteOrderList: [],
      // 白坯订单管理树选项
      whiteOrderOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 查询参数
      queryParams: {
        planDateArray: [new Date(), new Date()],
        factoryCode: null,
        orderType: null,
        orderCode: null,
        prodCode: null,
        prodDesc: null,
        quantity: null,
        quantitySplit: null,
        unit: null,
        workerOrder: null,
        planProDate: null,
        planComplete: null,
        atrr1: null,
        atrr2: null,
        atrr3: null,
        status: null,
        parentOrder: null,
        prodType: null,
        planDateStart: null,
        planDateEnd: null,
      },
      // 表单参数
      form: {
        prodCode: null,
        prodDesc: null,
        planProDate: null,
        planComplete: null,
        quantity: null,
        carNum: null,
        prodType: null,
        unit: null,
      },
      // 表单校验
      rules: {},
      // 新增-表单校验
      addrules: {},
      /**********************************/
      eRouteProps: {multiple: true},
      eRouteOptions: []
    };
  },
  created() {
    // 初始化
    this.loading = true
    this.queryParams.status = 'o0'
    this.queryParams.planDateArray = [new Date(), new Date()]
    this.queryParams.planDateStart = moment(this.queryParams.planDateArray[0]).format('YYYY-MM-DD')
    this.queryParams.planDateEnd = moment(this.queryParams.planDateArray[1]).format('YYYY-MM-DD')
    listWhiteOrder(this.queryParams).then(response => {
      this.whiteOrderList = this.handleTree(response.data, "orderCode", "parentOrder");
      this.loading = false;
    });
  },
  methods: {
    // 拆分-选择线体改变
    changeEquipment() {
      if (this.splitForm.routeCode == null) {
        this.$message({
          message: '请先选择工艺！',
          type: 'warning'
        })
        return
      }
    },
    // 拆分-拆分数量变化校验
    splitNumChange(e) {
      //不能为负数
      if (e <= 0) {
        this.$message({
          message: '拆分数量不能为负数！',
          type: 'warning'
        })
        e = 1
        this.splitForm.splitNum = 1
      } else {
        // 获取最大值，拆分数量不得超过最大值
        let max = Number(this.productData[0].quantity) - Number(this.productData[0].quantitySplit)
        // 超过最大值，给用户提醒
        if (e > max) {
          this.$message({
            message: '最大值不能超过' + max + '!',
            type: 'warning'
          })
          this.splitForm.splitNum = max
        }
        //前端数据同步
        // 在获取到新的数据后执行以下代码
        this.proLoading = true // 设置加载状态为true，表示正在加载

        this.productData[0].atrr1 = this.splitForm.splitNum;
        this.productData[0].children[0].atrr1 = this.splitForm.splitNum;

        this.refreshProTable = false // 先将refreshProTable设置为false，隐藏表格
        this.$nextTick(() => {
          // 使用$nextTick来等待DOM更新完成
          this.refreshProTable = true // 立即将refreshProTable设置为true，显示表格
          this.proLoading = false // 设置加载状态为false，表示加载完成
        })
      }
      this.product = this.productData[0]
    },
    // 拆分-校验工单日期
    checkDate(e) {
      var now = new Date()
      if (e < now) {
        e = now
        this.splitForm.productDate = now
        this.$message({
          message: "工单日期不能早于今天",
          type: "warning"
        })
      }
    },
    // 拆分-校验拆分批次号是否重复
    batchCodeChange(e) {
      if (this.formFields.length > 1) {
        for (let i = 0; i < this.formFields.length - 1; i++) {
          if (this.formFields[this.formFields.length - 1].batchCode == this.formFields[i].batchCode) {
            this.$message({
              message: '批次号不能重复！',
              type: 'warning'
            })
            this.formFields = [{
              batchCode: '',
              batchQuantity: ''
            }]
            return
          }
        }
      }
    },
    // 拆分-表单重置
    resetBatch() {
      this.eRouteOptions = [],
        this.splitForm = {
          prodLineCodeArray: [],
          id: null,
          prodLineCode: [],
          splitNum: null,
          productDate: null,
          shiftId: null,
          routeCode: null,
          formFields: []
        }
      this.splitData = []
      this.productData = []
      this.proline = []
      this.splitnum = null
      this.workShift = []
      this.formFields = [{
        batchCode: '',
        batchQuantity: ''
      }]
    },
    // 拆分-填写批次数量方法
    inBatch(e) {
      //不能为负数
      if (e <= 0) {
        this.$message({
          message: '拆分数量不能为负数！',
          type: 'warning'
        })
        this.formFields[this.formFields.length - 1].batchQuantity = 1
      }
      //逻辑判断
      let sum = 0
      for (let i = 0; i < this.formFields.length; i++) {
        sum += Number(this.formFields[i].batchQuantity)
      }
      //如果超过拆分数量，提示并清空当前输入
      if (sum > this.productData[0].atrr1) {
        this.$message({
          message: '你的批次数量总和不能超过拆分数量!',
          type: 'warning'
        })
        this.formFields[this.formFields.length - 1].batchQuantity = Number(this.productData[0].atrr1) - Number(Number(sum) - Number(e))
        if (this.formFields[this.formFields.length - 1].batchQuantity <= 0) {
          this.formFields[this.formFields.length - 1].batchQuantity = 1
        }
      }
      //如果拆分数量为空
      if (this.productData[0].atrr1 == '' || this.productData[0].atrr1 == null) {
        this.formFields[this.formFields.length - 1].batchQuantity = ''
      }
    },
    // 拆分-拆分提交按钮操作
    batchBtn() {
      // 判断数据不能为空
      if (this.splitForm.splitNum == null) {
        this.$message({
          message: '拆分数量不能为空！',
          type: 'warning'
        })
        return
      }
      if (this.splitForm.shiftId == null) {
        this.$message({
          message: '班次信息不能为空！',
          type: 'warning'
        })
        return
      }
      if (this.splitForm.prodLineCodeArray.length == 0) {
        this.$message({
          message: '请选择各流程节点的设备！',
          type: 'warning'
        })
        return
      }
      if (this.splitForm.routeCode == null) {
        this.$message({
          message: '请选择工艺信息！',
          type: 'warning'
        })
        return
      }
      if (this.splitForm.productDate == null) {
        this.$message({
          message: '请选择工单日期！！',
          type: 'warning'
        })
        return
      }
      // 判断如果拆分数量不等于拆分批次数量之和
      let sum = 0
      for (let i = 0; i < this.formFields.length; i++) {
        sum = Number(sum) + Number(this.formFields[i].batchQuantity)
        if (this.formFields[i].batchQuantity == '' || this.formFields[i].batchQuantity == null || this.formFields[i].batchCode == null || this.formFields[i].batchCode == '') {
          this.$message({
            message: '批次数据不能为空',
            type: 'warning'
          })
          return
        }
      }
      if (sum != this.productData[0].atrr1) {
        this.$message({
          message: '批次数量之和不等于拆分数量',
          type: 'warning'
        })
        return
      }

      //整理订单传入到后端
      this.splitForm.formFields = this.formFields
      //整理数据往后端发送
      //下面是请求处理
      const data = {
        formFields: this.formFields,
        prodLineCodeArray: this.splitForm.prodLineCodeArray,
        productDate: this.splitForm.productDate,
        shiftId: this.splitForm.shiftId,
        splitNum: this.splitForm.splitNum,
        product: this.productData[0],
        routeCode: this.splitForm.routeCode
      }

      subSplitOrder(data).then(response => {
        if (response.code == 500) {
          this.$modal.msgError(response.msg)
          return
        }
        this.$modal.msgSuccess('提交成功')
      })

      let id = this.productData[0].id
      // 清除缓存
      this.splitForm = {
        id: null,
        prodLineCode: [],
        splitNum: null,
        productDate: null,
        shiftId: null,
        formFields: []
      }
      this.formFields = [{
        batchCode: '',
        batchQuantity: ''
      }]

      this.getList()
      this.splitOpen = false
    },
    // 判空、空串
    checkNull(entity) {
      if (entity !== undefined && entity !== '' && entity !== null) {
        return 1
      }
      return 0
    },

    // 拆分-选择工艺
    changeRoute(routeCode) {
      console.log("点击了拆分-选择工艺")
      // 选择好工艺进行设备选择
      getProEquipment(routeCode).then(response => {
        this.eRouteOptions = response.data
        //默认全选
        let selectAll = [];
        this.eRouteOptions.forEach(it => {
          var children = it.children;
          if (children != null) {
            children.forEach(it2 => {
              let arr = []
              arr.push(it.value)
              arr.push(it2.value)
              selectAll.push(arr)
            })
          }
        })
        this.splitForm.prodLineCodeArray = selectAll
      })
    },
    // 拆分-动态删除批次
    removeField(index) {
      this.formFields.splice(index, 1)
    },
    // 拆分-动态添加批次
    addField() {
      //如果批次数量大于等于拆分数量则不允许拆分
      let sum = 0
      for (let i = 0; i < this.formFields.length; i++) {
        sum += Number(this.formFields[i].batchQuantity)
      }

      if (sum >= this.productData[0].atrr1) {
        this.$message({
          message: '无法添加！您的批次数量已满！',
          type: 'warning'
        })
        return
      }

      this.formFields.push({batchCode: '', batchQuantity: ''})
      //自动填充
      this.formFields[this.formFields.length - 1].batchQuantity = Number(this.productData[0].atrr1) - Number(sum)
    },
    // 拆分-点击拆分按钮操作
    handleUpdate(row) {
      console.log("点击了拆分按钮")
      // 清除缓存
      this.productData = [];
      this.splitForm = {
        id: null,
        prodLineCodeArray: [],
        splitNum: null,
        productDate: null,
        shiftId: null,
        routeCode: null,
        formFields: []
      };
      this.splitData = [];

      // 初始化数据
      // 1.获取订单信息
      // 2.获取工单信息
      // 3.获取工艺信息
      // 4.获取班次信息
      getSplitInfo(row).then(response => {
        console.log(response.data)

        this.workShift = response.data.proShiftList;
        this.routes = response.data.routeList;
        console.log("工艺list")
        console.log(this.routes)
        this.splitData = response.data.proOrderWorkorderList;
        this.productData.push(response.data.proOrderList[0]);

      })
      // 5.设置默认工单日期
      this.splitForm.productDate = moment(new Date()).format('YYYY-MM-DD')

      // 打开拆分弹窗
      this.splitOpen = true;
    },
    // 导入-点击导入按钮
    handleImport() {
      console.log("点击了导入按钮")
    },
    // 导出
    handleExport() {
      console.log("点击了导出")
      this.download('/plan/whiteOrder/export', {
        ...this.queryParams
      }, `whiteOrder_${new Date().getTime()}.xlsx`)
    },
    // 新增-物料选择-确定按钮
    subMateriel() {
      console.log("点击了物料-确定")

      if (this.selectMaterielList.length < 1) {
        this.$message({
          message: '至少选择一个物料！',
          type: 'warning'
        })
        return
      }

      var code = '';
      var desc = '';
      for (let i = 0; i < this.selectMaterielList.length; i++) {
        code = code + this.selectMaterielList[i].productCode + ',';
        desc = desc + this.selectMaterielList[i].productDescZh + ',';
      }
      this.form.prodCode = code;
      this.form.prodDesc = desc;
      // 关闭选择物料弹窗
      this.innerVisible = false;
    },
    // 新增-物料多选
    handleSelectionChange(select) {
      console.log("选择物料")
      console.log(select)
      this.selectMaterielList = select;
    },
    // 新增-获取物料list
    getMaterielList() {
      this.loading = true;
      selectMaterielList(this.materielQueryParams).then(response => {
          this.materielList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    // 新增-物料搜索按钮
    handleMaterielQuery() {
      console.log("点击了物料搜索按钮")
      this.materielQueryParams.pageNum = 1;
      this.getMaterielList();
    },
    // 新增-车数数量校验
    changeCarNum(num) {
      console.log("车数数量改变")
      // 请先输入订单数量
      if (this.form.quantity == null) {
        this.$message({
          message: '请先输入订单数量！',
          type: 'warning'
        })
        this.form.carNum = null;
        return
      }
      // 车数不能超过订单数量
      if (Number(this.form.quantity) - Number(num) < 0) {
        this.$message({
          message: '车数不能超过订单数量！',
          type: 'warning'
        })
        this.form.carNum = this.form.quantity;
      }
      // 不能为负数
      if (num <= 0) {
        this.$message({
          message: '车数数量不能小于0！',
          type: 'warning'
        })
        this.form.carNum = 1;
      }
    },
    // 新增-订单数量校验
    addQuantity(num) {
      console.log("订单数量改变")
      // 不能为负数
      if (num <= 0) {
        this.$message({
          message: '订单数量不能小于0！',
          type: 'warning'
        })
        this.form.quantity = 1;
      }
    },
    // 新增-点击选择物料
    selectMateriel() {
      console.log("点击了选择物料");
      // 打开选择物料弹窗
      this.innerVisible = true;
      this.getMaterielList();
    },
    // 新增-点击新增按钮
    handleAdd(row) {
      console.log("点击了新增按钮");
      // TODO 清楚缓存
      // 设置白坯
      this.form.prodType = 'white'
      // 打开新增弹窗
      this.dialogVisible = true;
    },
    // 新增-提交按钮
    submitForm() {
      console.log("点击了提交按钮");
      // 校验新增数据是否存在空值
      if (this.form.prodCode == null) {
        this.$message({
          message: '请选择物料！',
          type: 'warning'
        })
        return
      }
      if (this.form.prodDesc == null) {
        this.$message({
          message: '请选择物料！',
          type: 'warning'
        })
        return
      }
      if (this.form.planProDate == null) {
        this.$message({
          message: '请选择计划生产日期！',
          type: 'warning'
        })
        return
      }
      if (this.form.planComplete == null) {
        this.$message({
          message: '请选择计划完成日期！',
          type: 'warning'
        })
        return
      }
      if (this.form.quantity == null) {
        this.$message({
          message: '请输入订单数量！',
          type: 'warning'
        })
        return
      }
      if (this.form.carNum == null) {
        this.$message({
          message: '请输入订单车数！',
          type: 'warning'
        })
        return
      }
      if (this.form.unit == null) {
        this.$message({
          message: '请输入单位！',
          type: 'warning'
        })
        return
      }

      // 新增提交后端
      addWhiteOrder(this.form).then(response => {
        this.$modal.msgSuccess('新增成功')
        this.dialogVisible = false
        this.reset()
        this.getList()
      });
    },
    // 首-查询白坯订单管理列表
    getList() {
      this.loading = true;
      listWhiteOrder(this.queryParams).then(response => {
        this.whiteOrderList = this.handleTree(response.data, "orderCode", "parentOrder");
        this.loading = false;
      });
    },
    /** 转换白坯订单管理数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.orderCode,
        label: node.prodDesc,
        children: node.children
      };
    },
    /** 查询白坯订单管理下拉树结构 */
    getTreeselect() {
      listWhiteOrder().then(response => {
        this.whiteOrderOptions = [];
        const data = {orderCode: 0, prodDesc: '顶级节点', children: []};
        data.children = this.handleTree(response.data, "orderCode", "parentOrder");
        this.whiteOrderOptions.push(data);
      });
    },
    // 首-取消按钮
    cancel() {
      this.open = false;
      // 新增-关闭新增弹窗
      this.dialogVisible = false;
      this.reset();
    },
    // 首-表单重置
    reset() {
      this.form = {
        id: null,
        factoryCode: null,
        orderType: null,
        orderCode: null,
        prodCode: null,
        prodDesc: null,
        quantity: null,
        quantitySplit: null,
        unit: null,
        workerOrder: null,
        planProDate: null,
        planComplete: null,
        atrr1: null,
        atrr2: null,
        atrr3: null,
        status: null,
        parentOrder: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        prodType: null
      };
      this.resetForm("form");
    },
    // 首-搜索按钮操作
    handleQuery() {
      this.queryParams.planDateStart = moment(this.queryParams.planDateArray[0]).format('YYYY-MM-DD')
      this.queryParams.planDateEnd = moment(this.queryParams.planDateArray[1]).format('YYYY-MM-DD')
      this.getList();
    },
    // 首-重置按钮操作
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.planDateArray = [new Date(), new Date()];
      this.queryParams.planDateStart = moment(this.queryParams.planDateArray[0]).format('YYYY-MM-DD');
      this.queryParams.planDateEnd = moment(this.queryParams.planDateArray[1]).format('YYYY-MM-DD');
      this.queryParams.status = null;
      this.handleQuery();
    },
    // 首-展开/折叠操作
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm('是否确认删除白坯订单管理编号为"' + row.id + '"的数据项？').then(function () {
        return delWhiteOrder(row.id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    }
  }
};
</script>
<style>
.el-row {
  margin: 0;
  padding: 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>
