<template>
  <div v-loading="loading">
    <PageTitle>
      {{ pageTitle }}
      <!-- 申请按钮显示 -->
      <template slot="buttons" v-if="mode == 'apply'">
        <el-button size="mini" @click="resetForm">重置</el-button>
        <el-button size="mini" type="primary" @click="saveForm">提交</el-button>
      </template>

      <!-- 修改 按钮显示 -->
      <template slot="buttons" v-if="mode == 'edit'">
        <el-button size="mini" type="primary" @click="saveForm">提交</el-button>
      </template>
    </PageTitle>

    <PageWrapper>
      <el-form
        class="page-form"
        :model="form"
        ref="form"
        :rules="rules"
        size="small"
        :inline="true"
        label-width="8em"
      >
        <el-row>
          <el-col :lg="6" :md="8" :sm="12" :xs="12">
            <el-form-item label="申请单编码" prop="workorderCode">
              <el-input
                disabled
                v-model="form.workorderCode"
                placeholder="自动生成"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :lg="6" :md="8" :sm="12" :xs="12">
            <el-form-item label="工单名称" prop="workorderName">
              <el-input
                v-model="form.workorderName"
                placeholder="请输入工单名称"
              />
            </el-form-item>
          </el-col>
          <el-col :lg="6" :md="8" :sm="12" :xs="12">
            <el-form-item label="工单类型" prop="workorderType">
              <el-select v-model="form.workorderType" placeholder="请选择类型">
                <el-option
                  v-for="dict in dict.type.mes_workorder_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :lg="6" :md="8" :sm="12" :xs="12">
            <el-form-item label="工艺名称" prop="routeId">
              <el-input
                v-model="form.routeName"
                readonly
                placeholder="请选择工艺路线"
              >
                <el-button
                  slot="append"
                  icon="el-icon-search"
                  @click="$refs['RoutesProcessSelectRef'].showFlag = true"
                ></el-button>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :lg="6" :md="8" :sm="12" :xs="12">
            <el-form-item label="产品编号" prop="productCode">
              <el-input v-model="form.productCode" placeholder="请选择产品">
                <el-button
                  slot="append"
                  @click="handleSelectProduct"
                  icon="el-icon-search"
                ></el-button>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :lg="6" :md="8" :sm="12" :xs="12">
            <el-form-item label="产品名称" prop="productName">
              <el-input
                v-model="form.productName"
                placeholder="请选择产品"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :lg="6" :md="8" :sm="12" :xs="12">
            <el-form-item label="规格型号" prop="productSpc">
              <el-input
                v-model="form.productSpc"
                placeholder="请选择产品"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :lg="6" :md="8" :sm="12" :xs="12">
            <el-form-item label="生产数量" prop="quantity">
              <el-input
                v-model="form.quantity"
                placeholder="请输入生产数量"
                type="number"
                min="1"
              />
            </el-form-item>
          </el-col>
          <el-col :lg="6" :md="8" :sm="12" :xs="12">
            <el-form-item label="计量单位" prop="unitOfMeasure">
              <el-input
                v-model="form.unitOfMeasure"
                placeholder="请输入计量单位"
              />
            </el-form-item>
          </el-col>
          <el-col :lg="6" :md="8" :sm="12" :xs="12">
            <el-form-item label="开始日期" prop="startDate">
              <el-date-picker
                clearable
                v-model="form.startDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择开始日期"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :lg="6" :md="8" :sm="12" :xs="12">
            <el-form-item label="需求日期" prop="requestDate">
              <el-date-picker
                clearable
                v-model="form.requestDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择需求日期"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :lg="6" :md="8" :sm="12" :xs="12">
            <el-form-item label="生产主管" prop="productionAdministrator">
              <el-input
                v-model="form.productionAdministrator"
                placeholder="请输入生产主管"
              />
            </el-form-item>
          </el-col>
          <el-col :lg="6" :md="8" :sm="12" :xs="12">
            <el-form-item label="库存地点" prop="stockLocation">
              <el-input
                v-model="form.stockLocation"
                placeholder="请输入库存地点"
              />
            </el-form-item>
          </el-col>
          <el-col :lg="6" :md="8" :sm="12" :xs="12">
            <el-form-item label="批号" prop="batchNumber">
              <el-input v-model="form.batchNumber" placeholder="请输入批号" />
            </el-form-item>
          </el-col>
          <el-col :lg="6" :md="8" :sm="12" :xs="12">
            <el-form-item label="工单状态" prop="status">
              <el-input v-model="form.status" placeholder="请输入工单状态" />
            </el-form-item>
          </el-col>
          <el-col :lg="6" :md="8" :sm="12" :xs="12">
            <el-form-item label="派工倍数" prop="dispatchMultiple">
              <el-input
                v-model="form.dispatchMultiple"
                placeholder="请输入派工倍数"
              />
            </el-form-item>
          </el-col>
          <el-col :lg="6" :md="8" :sm="12" :xs="12">
            <el-form-item label="排班行数" prop="rowNum">
              <el-input v-model="form.rowNum" placeholder="请输入排版行数" />
            </el-form-item>
          </el-col>

          <el-col :lg="6" :md="8" :sm="12" :xs="12">
            <el-form-item label="单重" prop="singleWeight">
              <el-input v-model="form.singleWeight" placeholder="请输入单重" />
            </el-form-item>
          </el-col>
          <el-col :lg="6" :md="8" :sm="12" :xs="12">
            <el-form-item label="厚度(丝)" prop="thickness">
              <el-input v-model="form.thickness" placeholder="厚度(丝)" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="工单备注" prop="remark">
              <el-input
                v-model="form.remark"
                type="textarea"
                placeholder="请输入内容"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <el-tabs type="border-card" @tab-click="tabClick">
        <el-tab-pane label="BOM">
          <ProogingBom ref="ProogingBomRef" />
        </el-tab-pane>
        <el-tab-pane label="工艺">
          <ProogingProcess ref="ProogingProcessRef" :bomList="bomList" />
        </el-tab-pane>
        <el-tab-pane label="指令">
          <WorkOrderSale ref="WorkOrderSaleRef" />
        </el-tab-pane>
        <el-tab-pane label="SIZE">
          <WorkOrderSize ref="WorkOrderSizeRef" />
        </el-tab-pane>
      </el-tabs>
    </PageWrapper>
    <RoutesProcessSelect
      ref="RoutesProcessSelectRef"
      @onSelected="onRoutesProcessSelect"
    />
    <ItemSelect ref="itemSelect" @onSelected="onItemSelected"> </ItemSelect>
  </div>
</template>

<script>
import { genCode } from "@/api/system/autocode/rule";
import ProogingBom from "./components/ProogingBom.vue";
import ProogingProcess from "./components/ProogingProcess.vue";
import WorkOrderSale from "./components/WorkOrderSale.vue";
import WorkOrderSize from "./components/WorkOrderSize.vue";
import ItemSelect from "@/components/itemSelect/single.vue";
import ClientSelect from "@/components/clientSelect/single.vue";
import VendorSelect from "@/components/vendorSelect/single.vue";
import RoutesProcessSelect from "@/components/routesProcessSelect/index.vue";
import { listRouteprocess } from "@/api/mes/pro/routeprocess";
import tabPlugins from "@/plugins/tab";
import {
  addPrototypeRequest,
  getPrototypeRequest,
  updatePrototypeRequest,
} from "@/api/mes/pro/prototypeRequest";
import {
  listWorkorder,
  getWorkorder,
  delWorkorder,
  addWorkorder,
  updateWorkorder,
  dofinish,
} from "@/api/mes/pro/workorder";
export default {
  components: {
    ProogingProcess,
    ProogingBom,
    WorkOrderSale,
    WorkOrderSize,
    ItemSelect,
    RoutesProcessSelect,
    ClientSelect,
    VendorSelect,
  },
  dicts: [
    "mes_workorder_status",
    "mes_workorder_sourcetype",
    "mes_workorder_type",
  ],
  provide() {
    return {
      mode: this.mode,
    };
  },
  data() {
    return {
      loading: false,
      optType: undefined,

      bomList: [],
      // 表单参数
      form: {
        workorderId: null,
        workorderCode: null,
        workorderName: null,
        routeName: null,
        workorderType: "SELF",
        orderSource: null,
        sourceCode: null,
        productId: null,
        productCode: null,
        productName: null,
        productSpc: null,
        unitOfMeasure: null,
        quantity: null,
        quantityProduced: null,
        quantityChanged: null,
        quantityScheduled: null,
        clientId: null,
        clientCode: null,
        clientName: null,
        vendorId: null,
        vendorCode: null,
        vendorName: null,
        requestDate: null,
        parentId: null,
        status: "PREPARE",
        orderId: null,
        orderNo: null,
        itemId: null,
        itemNo: null,
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
      },
      // 表单校验
      rules: {
        workorderCode: [
          { required: true, message: "工单编码不能为空", trigger: "blur" },
        ],
        workorderName: [
          { required: true, message: "工单名称不能为空", trigger: "blur" },
        ],
        workorderType: [
          { required: true, message: "请选择生产工单类型", trigger: "blur" },
        ],
        orderSource: [
          { required: true, message: "来源类型不能为空", trigger: "blur" },
        ],
        productId: [
          { required: true, message: "产品不能为空", trigger: "blur" },
        ],
        productCode: [
          { required: true, message: "产品编号不能为空", trigger: "blur" },
        ],
        productName: [
          { required: true, message: "产品名称不能为空", trigger: "blur" },
        ],
        quantity: [
          { required: true, message: "生产数量不能为空", trigger: "blur" },
        ],
        requestDate: [
          { required: true, message: "需求日期不能为空", trigger: "blur" },
        ],
      },
    };
  },
  computed: {
    scrollHeight() {
      return "calc(100vh - 73px - 83px)";
    },
    mode() {
      return this.$route.path.split("/").at(-1);
    },
    pageTitle() {
      const titles = {
        edit: "工单修改",
        info: "工单新增",
        apply: "工单申请",
      };
      return titles[this.mode];
    },
  },
  created() {
    this.getFormInfo();
    if (this.mode == "apply") {
      this.gCode();
    }
  },

  methods: {
    /** 查询生产工单下拉树结构 */
    getTreeselect() {
      listWorkorder().then((response) => {
        this.workorderOptions = [];
        const data = {
          workorderId: 0,
          workorderName: "顶级节点",
          children: [],
        };
        data.children = this.handleTree(
          response.data,
          "workorderId",
          "parentId"
        );
        this.workorderOptions.push(data);
      });
    },
    /** 生成编码 */
    gCode() {
      genCode("WORKORDER_CODE").then((response) => {
        this.form.workorderCode = response;
      });
    },
    // //从BOM行中直接新增
    // handleSubAdd(row){
    //   this.open = false;
    //   this.reset();
    //   this.getTreeselect();
    //   if (row != null && row.workorderId) {
    //     this.form = row;
    //     this.form.parentId = row.workorderId;
    //     this.form.workorderId = null;
    //     this.form.workorderCode = null;
    //   } else {
    //     this.form.parentId = 0;
    //   }
    //   this.open = true;
    //   this.title = "添加生产工单";
    //   this.optType="add";
    // },

    //物料选择弹出框
    onItemSelected(obj) {
      if (obj != undefined && obj != null) {
        this.form.productId = obj.itemId;
        this.form.productCode = obj.itemCode;
        this.form.productName = obj.itemName;
        this.form.productSpc = obj.specification;
        this.form.unitOfMeasure = obj.unitOfMeasure;
      }
    },
    //客户选择弹出框

    onClientSelected(row) {
      if (row != undefined && row != null) {
        this.form.clientId = row.clientId;
        this.form.clientCode = row.clientCode;
        this.form.clientName = row.clientName;
      }
    },
    //供应商选择弹出框
    onVendorSelected(row) {
      debugger;
      if (row != undefined && row != null) {
        this.form.vendorId = row.vendorId;
        this.form.vendorCode = row.vendorCode;
        this.form.vendorName = row.vendorName;
      }
    },
    handleSelectProduct() {
      this.$refs.itemSelect.showFlag = true;
    },
    handleSelectClient() {
      this.$refs.clientSelect.showFlag = true;
    },

    handleSelectVendor() {
      this.$refs.vendorSelect.showFlag = true;
    },
    /** 根据 id 获取页面数据 */
    getFormInfo() {
      if (this.mode != "apply") {
        const id = this.$route.query.workorderId;
        this.loading = true;
        getWorkorder(id)
          .then(({ data }) => {
            Object.assign(this.form, data);
            this.bomList = data.bomList;
            // 设置组件数据
            this.$refs["ProogingBomRef"].tableData = data.bomList;
            this.$refs["ProogingProcessRef"].tableData = data.processList;
            this.$refs["WorkOrderSaleRef"].form = data.saleDirective;
            this.$refs["WorkOrderSizeRef"].tableData = data.sizeList;
            this.$refs["WorkOrderSizeRef"].tableColums = [];
            this.$refs["WorkOrderSizeRef"].colums.forEach((value) => {
              let flag = false;
              data.sizeList.forEach((item) => {
                if (item[value.prop] === 0 || item[value.prop]) {
                  flag = true;
                }
              });
              if (flag) {
                this.$refs["WorkOrderSizeRef"].tableColums.push(value);
              }
            });
          })
          .finally(() => {
            this.loading = false;
          });
      }
    },
    // /** 生成编码 */
    // gCode() {
    //   genCode("PROTOTYPE_REQUEST_CODE").then((response) => {
    //     this.form.prototypeRequestCode = response;
    //   });
    // },
    /** 点击tab 获取bom的数据,将参数传递给后面的组件 */
    tabClick(val) {
      if (val.index != 0) {
        this.bomList = this.$refs["ProogingBomRef"].getComData();
      }
    },
    // onItemSelect(row) {
    //   if (row != undefined && row != null) {
    //     this.form.itemId = row.itemId;
    //     this.form.itemName = row.itemName;
    //     this.form.unit = row.unitOfMeasure;
    //   }
    // },
    //物料选择弹出框

    onRoutesProcessSelect(row) {
      if (row != undefined && row != null) {
        this.form.routeId = row.routeId;
        this.form.routeName = row.routeName;
        const params = {
          pageNum: 1,
          pageSize: 1000,
          routeId: row.routeId,
        };
        listRouteprocess(params).then(({ rows }) => {
          this.$refs["ProogingProcessRef"].setList(rows);
        });
      }
    },
    /**提交 */
    saveForm() {
      const bomList = this.$refs.ProogingBomRef.getComData();
      const processList = this.$refs.ProogingProcessRef.getComData();
      const saleList = this.$refs.WorkOrderSaleRef.getComData();
      const sizeList = this.$refs.WorkOrderSizeRef.getComData();
      const params = {
        ...this.form,
        bomList,
        processList,
        saleList,
        sizeList,
      };
      this.loading = true;
      if (this.mode == "apply") {
        addWorkorder(params)
          .then((res) => {
            this.loading = false;
            this.$modal.msgSuccess("提交成功！");

            this.$nextTick(() => {
              // 关闭页签
              tabPlugins.closeOpenPage();
              this.$router.replace({
                path: "/mes/pro/workorder",
              });
            });
          })
          .catch(() => {
            this.loading = false;
          });
      } else {
        updateWorkorder(params)
          .then(() => {
            this.loading = false;
            this.$modal.msgSuccess("提交成功！");
          })
          .catch(() => {
            this.loading = false;
          });
      }
    },
    /**重置表单 */
    resetForm() {
      this.form = {
        workorderId: null,
        workorderCode: null,
        workorderName: null,
        routeName: null,
        workorderType: "SELF",
        orderSource: null,
        sourceCode: null,
        productId: null,
        productCode: null,
        productName: null,
        productSpc: null,
        unitOfMeasure: null,
        quantity: null,
        quantityProduced: null,
        quantityChanged: null,
        quantityScheduled: null,
        clientId: null,
        clientCode: null,
        clientName: null,
        vendorId: null,
        vendorCode: null,
        vendorName: null,
        requestDate: null,
        parentId: null,
        status: "PREPARE",
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
      };
      this.$refs["ProogingBomRef"].resetState();
      this.$refs["ProogingProcessRef"].resetState();
      this.$refs["WorkOrderSaleRef"].resetState();
      this.$refs["WorkOrderSizeRef"].resetState();
      this.gCode();
    },
  },
};
</script>

<style lang="scss" scoped></style>
