<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="工单编号" prop="orderCode">
        <el-input
          v-model="queryParams.orderCode"
          placeholder="请输入工单编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="销售订单编号" prop="saleorderCode">
        <el-input
          v-model="queryParams.saleorderCode"
          placeholder="请输入销售订单编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!--      <el-form-item label="物料ID" prop="materialId">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.materialId"-->
      <!--          placeholder="请输入物料ID"-->
      <!--          clearable-->
      <!--          @keyup.enter.native="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="派工类型" prop="dispatchType">-->
      <!--        <el-select v-model="queryParams.dispatchType" placeholder="请选择派工类型" clearable>-->
      <!--          <el-option-->
      <!--            v-for="dict in dict.type.dispatch_type"-->
      <!--            :key="dict.value"-->
      <!--            :label="dict.label"-->
      <!--            :value="dict.value"-->
      <!--          />-->
      <!--        </el-select>-->
      <!--      </el-form-item>-->
      <el-form-item label="工单状态" prop="orderStatus">
        <el-select v-model="queryParams.orderStatus" placeholder="请选择工单状态" clearable>
          <el-option
            v-for="dict in dict.type.plan_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <!--      <el-form-item label="库存锁定标识" prop="stockLockFlag">-->
      <!--        <el-select v-model="queryParams.stockLockFlag" placeholder="请选择库存锁定标识" clearable>-->
      <!--          <el-option-->
      <!--            v-for="dict in dict.type.active_flag"-->
      <!--            :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:productOrder:add']"
        >销售订单新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleNoOrderAdd"
          v-hasPermi="['mes:productOrder: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:productOrder: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:productOrder: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:productOrder:export']"-->
      <!--        >导出-->
      <!--        </el-button>-->
      <!--      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="productOrderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="主键标识" align="center" prop="productOrderId" v-if="columns[0].visible"/>
      <el-table-column label="销售订单ID" align="center" prop="saleOrderId" v-if="columns[2].visible" width="100"/>
      <el-table-column label="销售订单编号" align="center" prop="saleorderCode" v-if="columns[3].visible" width="100"/>
      <el-table-column label="销售订单行号" align="center" prop="saleorderLinenumber" v-if="columns[4].visible" width="110"/>
      <el-table-column label="项目编号" align="center" prop="projectNo" v-if="columns[5].visible"/>
      <el-table-column label="工单编号" align="center" prop="orderCode" v-if="columns[1].visible" width="100"/>
      <el-table-column label="物料名称" align="center" prop="materialName" v-if="columns[6].visible" width="100"/>
      <el-table-column label="物料BOM" align="center" prop="materialBomDesc" v-if="columns[7].visible" width="120"/>
      <el-table-column label="派工类型" align="center" prop="dispatchType" v-if="columns[8].visible">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.dispatch_type" :value="scope.row.dispatchType"/>
        </template>
      </el-table-column>
      <el-table-column label="工艺路线" align="center" prop="dispatchName" v-if="columns[9].visible" width="120"/>
      <el-table-column label="单位时间" align="center" prop="productionTime"  v-if="columns[27].visible">
        <template slot-scope="scope">
          <span>{{formatDayHourMinutes(scope.row.productionTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="销售数量" align="center" prop="saleAmount" v-if="columns[10].visible"/>
      <el-table-column label="计划数量" align="center" prop="planAmount" v-if="columns[11].visible"/>
      <el-table-column label="已派工数量" align="center" prop="dispatchAmount" v-if="columns[12].visible" width="100"/>
      <el-table-column label="完成数量" align="center" prop="completeAmount" v-if="columns[13].visible"/>
      <el-table-column label="工单状态" align="center" prop="orderStatus" v-if="columns[19].visible">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.plan_status" :value="scope.row.orderStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="发布时间" align="center" prop="releaseTime" width="180" v-if="columns[14].visible">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.releaseTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="计划交货日期" align="center" prop="planDeliveryDate" width="180" v-if="columns[26].visible">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="计划开始时间" align="center" prop="planBeginTime" width="180" v-if="columns[15].visible">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.planBeginTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="计划结束时间" align="center" prop="planEndTime" width="180" v-if="columns[16].visible">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.planEndTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="开始时间" align="center" prop="realBeginTime" width="180" v-if="columns[17].visible">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.realBeginTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="完成时间" align="center" prop="realEndTime" width="180" v-if="columns[18].visible">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.realEndTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="库存锁定标识" align="center" prop="stockLockFlag" v-if="columns[20].visible" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.active_flag" :value="scope.row.stockLockFlag"/>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" v-if="columns[21].visible"/>
      <el-table-column label="创建人" align="center" prop="createBy" v-if="columns[22].visible"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180" v-if="columns[23].visible">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新人" align="center" prop="updateBy" v-if="columns[24].visible"/>
      <el-table-column label="更新时间" align="center" prop="updateTime" width="180" v-if="columns[25].visible">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-if="scope.row.orderStatus === '0'"
            v-hasPermi="['mes:productOrder:edit']"
          >修改工单
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-lock"
            @click="handleLockInventory(scope.row)"
          >锁库存
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-success"
            @click="handlePublish(scope.row)"
            v-if="scope.row.orderStatus === '0'"
          >发布
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-d-arrow-left"
            @click="handleRecall(scope.row)"
            v-if="scope.row.orderStatus === '1'"
          >撤回
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-right"
            @click="handleDispatch(scope.row)"
            v-if="scope.row.orderStatus === '1' || scope.row.orderStatus === '3'"
          >生产派工
          </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="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="工单编号" prop="orderCode">
          <el-input v-model="form.orderCode" placeholder="请输入工单编号" :disabled="true"/>
        </el-form-item>
        <!--        <el-form-item label="销售订单ID" prop="saleOrderId">-->
        <!--          <el-input v-model="form.saleOrderId" placeholder="请输入销售订单ID" />-->
        <!--        </el-form-item>-->
        <el-form-item label="销售订单编号" prop="saleorderCode">
          <el-input v-model="form.saleorderCode" placeholder="请点击右侧检索销售订单编号" readonly>
            <el-button slot="append" icon="el-icon-search" @click="handleSaleOrderAdd"></el-button>
          </el-input>
        </el-form-item>
        <el-form-item label="销售订单行号" prop="saleorderLinenumber">
          <el-input v-model="form.saleorderLinenumber" placeholder="请输入销售订单行号" :disabled="true"/>
        </el-form-item>
        <!--        <el-form-item label="项目编号" prop="projectNo">-->
        <!--          <el-input v-model="form.projectNo" placeholder="请输入项目编号" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="物料ID" prop="materialId" >-->
        <!--          <el-input v-model="form.materialId" placeholder="请输入物料ID" :disabled="true"/>-->
        <!--        </el-form-item>-->
        <el-form-item label="物料名称" prop="materialId">
          <el-input v-model="form.materialName" placeholder="请输入物料名称" :disabled="true"/>
        </el-form-item>
        <el-form-item label="物料BOM" prop="materialBomId">
          <el-select v-model="form.materialBomId" placeholder="请选择物料BOM">
            <el-option
              v-for="item in materialBomList"
              :key="item.materialBomId"
              :label="item.materialNameDesc"
              :value="item.materialBomId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="工艺路线" prop="dispatchId">
          <el-select v-model="form.dispatchId" filterable placeholder="请选择工艺路线" clearable>
            <el-option
              v-for="item in routeList"
              :key="item.routeId"
              :label="item.routeName"
              :value="item.routeId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="销售数量" prop="saleAmount">
          <el-input-number v-model="form.saleAmount" placeholder="请输入销售数量" :disabled="true"/>
        </el-form-item>
        <el-form-item label="计划数量" prop="planAmount">
          <el-input-number v-model="form.planAmount" placeholder="请输入计划数量"/>
        </el-form-item>
        <el-form-item label="计划交货日期" prop="planDeliveryDate">
          <el-date-picker clearable
                          v-model="form.planDeliveryDate"
                          type="datetime"
                          value-format="yyyy-MM-dd HH:mm:ss"
                          placeholder="请选择计划交货日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="计划开始时间" prop="planBeginTime">
          <el-date-picker clearable
                          v-model="form.planBeginTime"
                          type="datetime"
                          value-format="yyyy-MM-dd HH:mm:ss"
                          placeholder="请选择计划开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="计划结束时间" prop="planEndTime">
          <el-date-picker clearable
                          v-model="form.planEndTime"
                          type="datetime"
                          value-format="yyyy-MM-dd HH:mm:ss"
                          placeholder="请选择计划结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
      </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="title" :visible.sync="noOrderOpen" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="工单编号" prop="orderCode">
          <el-input v-model="form.orderCode" :disabled="true"/>
        </el-form-item>
        <!--        <el-form-item label="项目编号" prop="projectNo">-->
        <!--          <el-input v-model="form.projectNo" placeholder="请输入项目编号"/>-->
        <!--        </el-form-item>-->
        <el-form-item label="物料名称" prop="materialName">
          <el-input v-model="form.materialName" placeholder="请点击右侧检索物料" readonly>
            <el-button slot="append" icon="el-icon-search" @click="handleMaterialAdd"></el-button>
          </el-input>
        </el-form-item>
        <el-form-item label="物料BOM" prop="materialBomId">
          <el-select v-model="form.materialBomId" placeholder="请选择物料BOM">
            <el-option
              v-for="item in materialBomList"
              :key="item.materialBomId"
              :label="item.materialNameDesc"
              :value="item.materialBomId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="工艺路线" prop="dispatchId">
          <el-select v-model="form.dispatchId" filterable placeholder="请选择工艺路线" clearable>
            <el-option
              v-for="item in routeList"
              :key="item.routeId"
              :label="item.routeName"
              :value="item.routeId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="销售数量" prop="saleAmount">
          <el-input-number v-model="form.saleAmount" placeholder="请输入销售数量"/>
        </el-form-item>
        <el-form-item label="计划数量" prop="planAmount">
          <el-input-number v-model="form.planAmount" placeholder="请输入计划数量"/>
        </el-form-item>
        <el-form-item label="计划交货日期" prop="planDeliveryDate">
          <el-date-picker clearable
                          v-model="form.planDeliveryDate"
                          type="datetime"
                          value-format="yyyy-MM-dd HH:mm:ss"
                          placeholder="请选择计划交货日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="计划开始时间" prop="planBeginTime">
          <el-date-picker clearable
                          v-model="form.planBeginTime"
                          type="datetime"
                          value-format="yyyy-MM-dd HH:mm:ss"
                          placeholder="请选择计划开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="计划结束时间" prop="planEndTime">
          <el-date-picker clearable
                          v-model="form.planEndTime"
                          type="datetime"
                          value-format="yyyy-MM-dd HH:mm:ss"
                          placeholder="请选择计划结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
      </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="saleOrderOpen" append-to-body>
      <add-SaleOrder @selection="handleSelection" ref="saleOrderRef"></add-SaleOrder>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitSaleOrderForm">确 定</el-button>
        <el-button @click="saleOrderOpen = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加物料信息对话框 -->
    <el-dialog title="选择物料信息" :visible.sync="materialOpen" append-to-body>
      <add-bom @selection="handleSelection" ref="materialRef"></add-bom>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitMaterialForm">确 定</el-button>
        <el-button @click="materialOpen = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  listProductOrder,
  getProductOrder,
  delProductOrder,
  addProductOrder,
  updateProductOrder,
  getOrderCode, productOrderLockInventory, productOrderPublish, productOrderRecall
} from "@/api/mes/productOrder";
import addSaleOrder from '@//views/mes/productOrder/addSaleOrder.vue';
import {getMaterialVisionList} from "@//api/mes/materialBom";
import {findRouteList} from "@//api/mes/baseRoute";
import addBom from '@//views/mes/materialBom/addBom.vue';
import router from "@//router";

export default {
  name: "ProductOrder",
  dicts: ['active_flag', 'plan_status', 'dispatch_type'],
  components: {
    'add-SaleOrder': addSaleOrder,
    'add-bom': addBom
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 选中orderCode数组
      orderCodes: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 生产工单表格数据
      productOrderList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示添加销售订单弹出层
      saleOrderOpen: false,
      // 是否显示无订单添加弹出层
      noOrderOpen: false,
      // 是否显示物料弹出层
      materialOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderCode: null,
        saleOrderId: null,
        saleorderCode: null,
        saleorderLinenumber: null,
        projectNo: null,
        materialId: null,
        materialBomId: null,
        dispatchType: null,
        dispatchId: null,
        saleAmount: null,
        planAmount: null,
        dispatchAmount: null,
        completeAmount: null,
        releaseTime: null,
        planDeliveryDate: null,
        planBeginTime: null,
        planEndTime: null,
        realBeginTime: null,
        realEndTime: null,
        orderStatus: null,
        stockLockFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        orderCode: [
          {required: true, message: "工单编号不能为空", trigger: "blur"}
        ],
        saleOrderId: [
          {required: true, message: "销售订单ID不能为空", trigger: "blur"}
        ],
        saleorderCode: [
          {required: true, message: "销售订单编号不能为空", trigger: "blur"}
        ],
        materialId: [
          {required: true, message: "物料ID不能为空", trigger: "blur"}
        ],
        materialBomId: [
          {required: true, message: "物料BOM不能为空", trigger: "blur"}
        ],
        dispatchType: [
          {required: true, message: "派工类型不能为空", trigger: "change"}
        ],
        dispatchId: [
          {required: true, message: "工艺路线不能为空", trigger: "blur"}
        ],
        planDeliveryDate: [
          {required: true, message: "计划交货日期不能为空", trigger: "blur"}
        ],
        planBeginTime: [
          {required: true, message: "计划开始时间不能为空", trigger: "blur"}
        ],
        planEndTime: [
          {required: true, message: "计划结束时间不能为空", trigger: "blur"}
        ],
        saleAmount: [
          {required: true, message: "销售数量不能为空", trigger: "blur"},
          {
            validator: (rule, value, callback) => callback(Number.isInteger(Number(value)) && Number(value) >= 0 ? undefined : new Error("销售数量需要是大于等于0的整数")),
            trigger: "blur"
          }
        ],
        planAmount: [
          {required: true, message: "计划数量不能为空", trigger: "blur"},
          {
            validator: (rule, value, callback) => callback(Number.isInteger(Number(value)) && Number(value) >= 1 ? undefined : new Error("计划数量需要是大于等于1的整数")),
            trigger: "blur"
          }
        ],
      },
      columns: [
        {key: 0, label: `主键标识`, visible: false},
        {key: 1, label: `工单编号`, visible: true},
        {key: 2, label: `销售订单ID`, visible: false},
        {key: 3, label: `销售订单编号`, visible: true},
        {key: 4, label: `销售订单行号`, visible: false},
        {key: 5, label: `项目编号`, visible: false},
        {key: 6, label: `物料名称`, visible: true},
        {key: 7, label: `物料bomID`, visible: true},
        {key: 8, label: `派工类型`, visible: false},
        {key: 9, label: `工艺路线`, visible: true},
        {key: 10, label: `销售数量`, visible: true},
        {key: 11, label: `计划数量`, visible: true},
        {key: 12, label: `已派工数量`, visible: true},
        {key: 13, label: `完成数量`, visible: true},
        {key: 14, label: `发布时间`, visible: true},
        {key: 15, label: `计划开始时间`, visible: true},
        {key: 16, label: `计划结束时间`, visible: true},
        {key: 17, label: `开始时间`, visible: true},
        {key: 18, label: `完成时间`, visible: true},
        {key: 19, label: `工单状态`, visible: true},
        {key: 20, label: `库存锁定标识`, visible: true},
        {key: 21, label: `备注`, visible: false},
        {key: 22, label: `创建人`, visible: false},
        {key: 23, label: `创建时间`, visible: false},
        {key: 24, label: `更新人`, visible: false},
        {key: 25, label: `更新时间`, visible: false},
        {key: 26, label: `计划交货日期`, visible: true},
        {key: 27, label: `单位时间`, visible: true},
      ],
      //物料BOM选项
      materialBomList: [],
      //工艺路线选项
      routeList: [],
    };
  },
  created() {
    if (this.$route.query.queryParams != null){
      this.queryParams = { ...this.$route.query.queryParams }
    }
    this.getList();
    findRouteList().then(response => {
      this.routeList = response.data;
    })
  },
  methods: {
    /** 查询生产工单列表 */
    getList() {
      this.loading = true;
      listProductOrder(this.queryParams).then(response => {
        this.productOrderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.noOrderOpen = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        productOrderId: null,
        orderCode: null,
        saleOrderId: null,
        saleorderCode: null,
        saleorderLinenumber: null,
        projectNo: null,
        materialId: null,
        materialBomId: null,
        dispatchType: '2',
        dispatchId: null,
        saleAmount: null,
        planAmount: null,
        dispatchAmount: null,
        completeAmount: null,
        releaseTime: null,
        planDeliveryDate: null,
        planBeginTime: null,
        planEndTime: null,
        realBeginTime: null,
        realEndTime: null,
        orderStatus: null,
        stockLockFlag: null,
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.materialBomList = null;
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleSaleOrderAdd() {
      this.saleOrderOpen = true;
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.productOrderId)
      this.orderCodes = selection.map(item => item.orderCode)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    handleSelection(selection) {
      this.ids = selection.map(item => item.productOrderId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    /** 提交物料信息按钮 */
    submitMaterialForm() {
      let selectedRow = this.$refs.materialRef.selectedRow;
      this.form.materialId = selectedRow.materialId;
      this.form.materialName = selectedRow.materialName;
      getMaterialVisionList(this.form.materialId).then(response => {
        this.materialBomList = response.data
        if (this.materialBomList.length !== 0) {
          this.form.materialBomId = this.materialBomList[0].materialBomId
        } else {
          this.form.materialBomId = null;
          this.$modal.msgError("该物料未维护BOM信息！");
        }
      })
      this.materialOpen = false;
    },

    /** 提交销售订单信息按钮 */
    submitSaleOrderForm() {
      let selectedRow = this.$refs.saleOrderRef.selectedRow;
      this.form.saleOrderId = selectedRow.saleOrderId;
      this.form.saleorderCode = selectedRow.saleorderCode;
      this.form.saleorderLinenumber = selectedRow.saleorderLinenumber;
      this.form.materialId = selectedRow.materialId;
      this.form.materialCode = selectedRow.materialCode;
      this.form.materialName = selectedRow.materialName;
      this.form.saleAmount = selectedRow.orderAmount;
      this.form.planBeginTime = selectedRow.beginDate == null ? null : selectedRow.beginDate + " 00:00:00";
      this.form.planEndTime = selectedRow.endDate == null ? null : selectedRow.endDate + " 00:00:00";
      this.form.planDeliveryDate = selectedRow.planDeliveryDate == null ? null : selectedRow.planDeliveryDate + " 00:00:00";
      this.form.saleOrderFlag = '1';
      getMaterialVisionList(selectedRow.materialId).then(response => {
        this.materialBomList = response.data
        if (this.materialBomList.length !== 0) {
          this.form.materialBomId = this.materialBomList[0].materialBomId;
        } else {
          this.form.materialBomId = null;
          this.$modal.msgError("该销售订单物料未维护BOM信息！");
        }
      })
      this.saleOrderOpen = false;
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      getOrderCode().then(response => {
        this.form.orderCode = response.msg;
      })
      this.open = true;
      this.title = "添加生产工单";
    },

    /** 新增按钮操作 */
    handleMaterialAdd() {
      this.materialOpen = true;
    },

    /** 无订单新增按钮操作 */
    handleNoOrderAdd() {
      this.reset();
      getOrderCode().then(response => {
        this.form.orderCode = response.msg;
      })
      this.noOrderOpen = true;
      this.form.saleOrderFlag = '0';
      this.title = "添加生产工单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      console.log(row)
      if (row.orderStatus !== '0') {
        return this.$modal.msgError("该订单状态无法修改！");
      }
      this.reset();
      const productOrderId = row.productOrderId || this.ids
      getProductOrder(productOrderId).then(response => {
        this.form = response.data;
        getMaterialVisionList(response.data.materialId).then(response => {
          this.materialBomList = response.data
        })
        if (response.data.saleOrderId === null) {
          this.noOrderOpen = true;
        } else {
          this.open = true;
        }
        this.title = "修改生产工单";
      });
    },

    /** 锁库存 */
    handleLockInventory(row) {
      this.form.productOrderId = row.productOrderId;
      this.form.stockLockFlag = '1';
      productOrderLockInventory(this.form).then(response => {
        this.$modal.msgSuccess("锁库存成功");
        this.getList();
      });
    },

    /** 发布 */
    handlePublish(row) {
      this.form.productOrderId = row.productOrderId;
      this.form.orderStatus = row.orderStatus;
      this.$modal.confirm('是否确认发布生产工单编号为"' + row.orderCode + '"的数据项？').then(function () {
        return true;
      }).then(() => {
        productOrderPublish(this.form).then(response => {
          this.$modal.msgSuccess("发布成功");
          
          const productOrderId = row.productOrderId || this.ids[0];
          const orderCode = row.orderCode;
          const params = {queryParams: this.queryParams};
          this.$tab.closeOpenPage(router.currentRoute);
          this.$tab.openPage("工单[" + orderCode + "]生产派工", '/mes/product-plan/index/' + productOrderId, params);
        });
      }).catch(() => {
      });
    },

    /** 撤回 */
    handleRecall(row) {
      this.form.productOrderId = row.productOrderId;
      this.$modal.confirm('是否确认撤回生产工单编号为"' + row.orderCode + '"的数据项？').then(function () {
        return true;
      }).then(() => {
        productOrderRecall(this.form).then(response => {
          this.getList();
          this.$modal.msgSuccess("撤回成功");
        });
      }).catch(() => {
      });
    },

    /** 生产派工 */
    handleDispatch(row) {
      const productOrderId = row.productOrderId || this.ids[0];
      const orderCode = row.orderCode;
      const params = {queryParams: this.queryParams};
      this.$tab.closeOpenPage(router.currentRoute);
      this.$tab.openPage("工单[" + orderCode + "]生产派工", '/mes/product-plan/index/' + productOrderId, params);
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.saleAmount < this.form.planAmount) {
            return this.$modal.msgError("计划数量不能大于销售数量！");
          }
          if (this.form.productOrderId != null) {
            updateProductOrder(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.noOrderOpen = false;
              this.getList();
            });
          } else {
            addProductOrder(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.noOrderOpen = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const productOrderIds = row.orderCode || this.orderCodes;
      if (row.orderStatus !== '0' && row.orderStatus !== '8') {
        return this.$modal.msgError("该订单状态无法删除！");
      }
      this.$modal.confirm('是否确认删除生产工单编号为"' + productOrderIds + '"的数据项？').then(function () {
        return delProductOrder(productOrderIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('mes/productOrder/export', {
        ...this.queryParams
      }, `productOrder_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
