<template>
  <div v-loading="loading">
    <PageTitle>
      {{ pageTitle }}
      <!-- 申请按钮显示 -->
      <template slot="buttons" v-if="mode == 'apply'">
        <el-button size="mini" @click="resetForm">{{ $t('common.reset') }}</el-button>
        <el-button size="mini" type="primary" @click="saveForm">{{ $t('common.submit') }}</el-button>
      </template>

      <!-- 修改 按钮显示 -->
      <template slot="buttons" v-if="mode == 'edit'|| mode== 'make'">
        <el-button size="mini" type="primary" @click="saveForm">{{ $t('common.submit') }}</el-button>
      </template>
    </PageTitle>

    <PageWrapper>
      <el-form
        class="page-form"
        :model="form"
        ref="form"
        :rules="rules"
        :disabled="mode == 'info' || mode == 'makeInfo'"
        size="small"
        :inline="true"
        label-width="8em"
      >
        <el-row>
          <el-col v-if="mode === 'make'|| mode === 'makeInfo'" :lg="6" :md="8" :sm="12" :xs="12">
            <el-form-item :label="$t('父工单编码')" prop="parentCode">
              <el-input
                disabled
                v-model="form.parentCode"

              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :lg="6" :md="8" :sm="12" :xs="12">
            <el-form-item :label="$t('工单编码')" prop="workorderCode">
              <el-input
                disabled
                v-model="form.workorderCode"

              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :lg="6" :md="8" :sm="12" :xs="12">
            <el-form-item :label="$t('工单名称')" prop="workorderName">
              <el-input
                v-model="form.workorderName"

              />
            </el-form-item>
          </el-col>
          <el-col :lg="6" :md="8" :sm="12" :xs="12">
            <el-form-item :label="$t('订单单别')" prop="orderType">
              <el-input
                v-model="form.orderType"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :lg="6" :md="8" :sm="12" :xs="12">
            <el-form-item :label="$t('订单单号')" prop="orderCode">
              <el-input
                v-model="form.orderCode"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :lg="6" :md="8" :sm="12" :xs="12">
            <el-form-item :label="$t('订单序号')" prop="orderSerial">
              <el-input
                v-model="form.orderSerial"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :lg="6" :md="8" :sm="12" :xs="12">
            <el-form-item :label="$t('客户图号')" prop="customerDrawingNo">
              <el-input
                v-model="form.customerDrawingNo"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :lg="6" :md="8" :sm="12" :xs="12">
            <el-form-item :label="$t('客户项目号')" prop="customerProjectNo">
              <el-input
                v-model="form.customerProjectNo"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :lg="6" :md="8" :sm="12" :xs="12">
            <el-form-item :label="$t('内部图号')" prop="inDrawingNo">
              <el-input
                v-model="form.inDrawingNo"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :lg="6" :md="8" :sm="12" :xs="12">
            <el-form-item :label="$t('是否紧急')" prop="rushOrder">
              <el-input
                v-model="form.rushOrder"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :lg="6" :md="8" :sm="12" :xs="12">
            <el-form-item :label="$t('工单类型')" prop="workorderType">
              <el-select :disabled="mode == 'make'" v-model="form.workorderType">
                <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="$t('生产版本')" prop="productionSolutionCode">
              <el-input
                v-model="form.productionSolutionCode"
                readonly
                :disabled="mode == 'make'"

              >
                <el-button
                  slot="append"
                  v-if="!(mode === 'make' ||  mode === 'makeInfo')"
                  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="$t('产品编号')" prop="productCode">
              <el-input :disabled="mode == 'make'" readonly v-model="form.productCode">
                <el-button
                  slot="append"
                  v-if="!(mode === 'make' ||  mode === 'makeInfo')"
                  @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="$t('产品名称')" prop="productName">
              <el-input
                v-model="form.productName"

                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :lg="6" :md="8" :sm="12" :xs="12">
            <el-form-item :label="$t('规格型号')" prop="productSpc">
              <el-input
                v-model="form.productSpc"

                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :lg="6" :md="8" :sm="12" :xs="12">
            <el-form-item :label="$t('生产数量')" prop="quantity">
              <el-input
                v-model="form.quantity"

                type="number"
                min="1"
                @blur="handleChangeQuantity"
              />
            </el-form-item>
          </el-col>
          <el-col :lg="6" :md="8" :sm="12" :xs="12">
            <el-form-item :label="$t('计量单位')" prop="unitOfMeasure">
              <el-input
                v-model="form.unitOfMeasure"

                :disabled="mode == 'make'"
              />
            </el-form-item>
          </el-col>
          <el-col :lg="6" :md="8" :sm="12" :xs="12">
            <el-form-item :label="$t('common.start_date')" prop="startDate">
              <el-date-picker
                clearable
                v-model="form.startDate"
                type="date"
                :disabled="mode == 'make'"
                value-format="yyyy-MM-dd"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :lg="6" :md="8" :sm="12" :xs="12">
            <el-form-item :label="$t('需求日期')" prop="requestDate">
              <el-date-picker
                clearable
                v-model="form.requestDate"
                type="date"
                :disabled="mode == 'make'"
                value-format="yyyy-MM-dd"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :lg="6" :md="8" :sm="12" :xs="12">
            <el-form-item :label="$t('生产主管')" prop="productionAdministrator">
              <el-input
                :disabled="mode == 'make'"
                v-model="form.productionAdministrator"

              />
            </el-form-item>
          </el-col>
          <el-col :lg="6" :md="8" :sm="12" :xs="12">
            <el-form-item :label="$t('库存地点')" prop="stockLocation">
              <el-input
                :disabled="mode == 'make'"
                v-model="form.stockLocation"

              />
            </el-form-item>
          </el-col>
          <el-col :lg="6" :md="8" :sm="12" :xs="12">
            <el-form-item :label="$t('批号')" prop="batchNumber">
              <el-input v-model="form.batchNumber" :disabled="mode == 'make'" />
            </el-form-item>
          </el-col>
          <el-col :lg="6" :md="8" :sm="12" :xs="12">
            <el-form-item :label="$t('工单状态')" prop="status">
              <el-select v-model="form.status" :disabled="mode == 'make'">
                <el-option
                  v-for="dict in dict.type.mes_workorder_status"
                  :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="$t('已排产数量')" prop="quantityScheduled">
              <el-input v-model="form.quantityScheduled" disabled />
            </el-form-item>
          </el-col>
          <el-col :lg="18" :md="16" :sm="24" :xs="24">
            <el-form-item :label="$t('工单备注')" prop="remark">
              <el-input
                v-model="form.remark"
                type="textarea"
                :disabled="mode == 'make'"

              />
            </el-form-item>
          </el-col>
          <!-- <el-col :lg="6" :md="8" :sm="12" :xs="12">
            <el-form-item label="包装数量" prop="packNum">
              <el-input v-model="form.packNum" :disabled="mode == 'make'" />
            </el-form-item>
          </el-col>
          <el-col :lg="6" :md="8" :sm="12" :xs="12">
            <el-form-item label="包装类型" prop="packType">
              <el-select v-model="form.packType" :disabled="mode == 'make'">
                <el-option
                  v-for="dict in dict.type.pro_pack_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="packUnitOfMeasure">
              <el-input
                v-model="form.packUnitOfMeasure"

                :disabled="mode == 'make'"
              />
            </el-form-item>
          </el-col>
          <el-col :lg="6" :md="8" :sm="12" :xs="12">
            <el-form-item
              label="LOSS数是否单独包装"
              prop="lossIndividuallyWrap"
            >
              <el-select
                v-model="form.lossIndividuallyWrap"

                :disabled="mode == 'make'"
              >
                <el-option
                  v-for="dict in dict.type.sap_yes_no"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </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="$t('工艺')">
          <ProogingProcess ref="ProogingProcessRef" :bomList="bomList" />
        </el-tab-pane>
        <!-- <el-tab-pane label="指令" v-if="false"> -->
          <WorkOrderSale ref="WorkOrderSaleRef" style="display: none" />
        <!-- </el-tab-pane> -->
        <!-- <el-tab-pane label="SIZE" v-show="false" > -->
          <WorkOrderSize ref="WorkOrderSizeRef" style="display: none" />
        <!-- </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/productionSolution/index.vue";
// import { listRouteprocess } from "@/api/mes/pro/routeprocess";
import { listProductionSolutionProcess } from "@/api/mes/pro/productionSolutionProcess";
import tabPlugins from "@/plugins/tab";
import {
  addPrototypeRequest,
  getPrototypeRequest,
  updatePrototypeRequest,
} from "@/api/mes/pro/prototypeRequest";
import {
  listWorkorder,
  getWorkorder,
  delWorkorder,
  addWorkorder,
  updateWorkorder,
  dofinish,
  getMakeWorkorderCode,
  makeSubmitWorkorder
} from "@/api/mes/pro/workorder";
var isRefresh = false;
export default {
  components: {
    isRefresh,
    ProogingProcess,
    ProogingBom,
    WorkOrderSale,
    WorkOrderSize,
    ItemSelect,
    RoutesProcessSelect,
    ClientSelect,
    VendorSelect,
  },
  dicts: [
    "mes_workorder_status",
    "mes_workorder_sourcetype",
    "mes_workorder_type",
    "sys_yes_no",
    "pro_pack_type",
    "sap_yes_no",
  ],
  provide() {
    return {
      mode: this.mode,
    };
  },
  data() {
    return {
      loading: false,
      optType: undefined,
      workorderId: null,
      bomList: [],
      // 表单参数
      form: {
        workorderId: null,
        workorderCode: null,
        workorderName: null,
        routeName: null,
        groupKey: null,
        groupCounter: null,
        workorderType: "510",
        orderSource: null,
        sourceCode: null,
        productId: null,
        startDate: 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,
        packType: null,
        packUnitOfMeasure: null,
        lossIndividuallyWrap: null,
        packNum: null,
        productionSolutionId: null,
        productionSolutionCode: null,
        productionSolutionName: null,
      },
      // 表单校验
      rules: {
        workorderCode: [
          { required: true, message: this.$t('工单编码不能为空'), trigger: "blur" },
        ],
        workorderName: [
          { required: true, message: this.$t('工单名称不能为空'), trigger: "blur" },
        ],
        workorderType: [
          { required: true, message: this.$t('请选择生产工单类型'), trigger: "blur" },
        ],
        orderSource: [
          { required: true, message: this.$t('来源类型不能为空'), trigger: "blur" },
        ],
        productId: [
          { required: true, message: this.$t('产品不能为空'), trigger: "blur" },
        ],
        productCode: [
          { required: true, message: this.$t('产品编号不能为空'), trigger: "blur" },
        ],
        productName: [
          { required: true, message: this.$t('产品名称不能为空'), trigger: "blur" },
        ],
        quantity: [
          { required: true, message: this.$t('生产数量不能为空'), trigger: "blur" },
        ],
        requestDate: [
          { required: true, message: this.$t('需求日期不能为空'), trigger: "blur" },
        ],
      },
      currentData: {}
    };
  },
  computed: {
    scrollHeight() {
      return "calc(100vh - 73px - 83px)";
    },
    mode() {
      return this.$route.path.split("/").at(-1);
    },
    pageTitle() {
      const titles = {
        edit: this.$t('工单修改'),
        info: this.$t('工单新增'),
        apply: this.$t('工单申请'),
        make: this.$t('补单工单'),
        makeInfo: this.$t('补数订单查看'),
      };
      return titles[this.mode];
    },
  },
  activated() {
    // if(!this.$route.query.workorderId) {
    //   this.resetForm()
    // }
    if (this.$route.query && this.$route.query.workorderId && this.workorderId !== this.$route.query.workorderId) {
      this.resetForm()
      this.workorderId = this.$route.query.workorderId
      this.getFormInfo();
      if (this.mode == "apply") {
        this.gCode();
      }
    }

  },
  created() {
    if (this.$route.query && this.$route.query.workorderId && this.workorderId !== this.$route.query.workorderId) {
      this.workorderId = this.$route.query.workorderId
    }
    this.getFormInfo();
    if (this.mode == "apply") {
      this.gCode();
    }
  },

  methods: {
    handleChangeQuantity() {
      // 计算补单的时候 数量变更修改
      if (this.mode === 'make') {
        // this.form.quantity
        this.bomList = []
        const bomList = this.currentData.bomList.map((item,index) => {
          // console.log(item, 'items')
          let quantity = parseInt(this.form.quantity*item.quantity*100/this.currentData.quantity)
          // console.log(quantity, 'quantity')
          return {
            ...item,
            quantity: quantity/100
          }
        })
        this.bomList = bomList
        this.$refs["ProogingBomRef"].tableData = bomList
      }
    },
    /** 查询生产工单下拉树结构 */
    getTreeselect() {
      listWorkorder().then((response) => {
        this.workorderOptions = [];
        const data = {
          workorderId: 0,
          workorderName: this.$t('顶级节点'),
          children: [],
        };
        data.children = this.handleTree(
          response.data,
          "workorderId",
          "parentId"
        );
        this.workorderOptions.push(data);
      });
    },
    /** 生成编码 */
    gCode() {
      if (this.mode === 'apply') {
        genCode("WORKORDER_CODE").then((response) => {
          this.form.workorderCode = response;
        });
      } else if(this.mode === 'make') {
        getMakeWorkorderCode(this.form.parentCode).then(res => {
          if (res.code === 200) {
            this.form.workorderCode = res.data.code
          }
        })
      }
    },
    // //从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.currentData = {}
            if (this.mode == 'make') {
              this.currentData = data
              this.form = Object.assign({}, data, {quantity: null , workorderType:"complements",  parentCode: data.workorderCode, workorderCode: ''})
              this.gCode();
            }
            const sizeList = data.sizeList || [];
            this.bomList = data.bomList || [];
            // 设置组件数据
            this.$refs["ProogingBomRef"].tableData = data.bomList || [];
            console.log('生产工单', data.processList)

            this.$refs["ProogingProcessRef"].tableData = data.processList || [];
            this.$refs["WorkOrderSaleRef"].tableData = data.saleDirectiveList || [];
            this.$refs["WorkOrderSizeRef"].tableData = sizeList;
            this.$refs["WorkOrderSizeRef"].tableColums = [];
            this.$refs["WorkOrderSizeRef"].colums.forEach((value) => {
              let flag = false;
              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.productionSolutionId = row.productionSolutionId;
        this.form.productionSolutionCode = row.productionSolutionCode;
        this.form.groupCounter = row.groupCounter;
        this.form.groupKey = row.groupKey;
        if (!this.form.productId) {
          this.form.productCode = row.itemCode;
          this.form.productName = row.itemName;
          this.form.productId = row.itemId;
        }
        this.form.productionSolutionName = row.productionSolutionName;
        const params = {
          pageNum: 1,
          pageSize: 1000,
          productionSolutionId: row.productionSolutionId,
        };
        listProductionSolutionProcess(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.$refs.form.validate( valid => {
        if (valid) {
          this.loading = true;
          if (this.mode == "apply") {
            addWorkorder(params)
              .then((res) => {
                this.loading = false;
                this.$modal.msgSuccess(this.$t('提交成功！'));

                this.$nextTick(() => {
                  // 关闭页签
                  tabPlugins.closeOpenPage();
                  this.$router.replace({
                    path: "/mes/pro/workorder",
                  });
                });
              })
              .catch(() => {
                this.loading = false;
              });
          } else if(this.mode === 'make') {
            makeSubmitWorkorder(params)
            .then((res) => {
              this.loading = false;
              this.$modal.msgSuccess(this.$t('提交成功！'));

              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(this.$t('提交成功！'));
              })
              .catch(() => {
                this.loading = false;
              });
          }
        }
      })


    },
    /**重置表单 */
    resetForm() {
      this.form = {
        workorderId: null,
        workorderCode: null,
        workorderName: null,
        routeName: null,
        workorderType: "510",
        orderSource: null,
        sourceCode: null,
        productId: null,
        productCode: null,
        productName: null,
        productSpc: null,
        unitOfMeasure: null,
        quantity: null,
        quantityProduced: null,
        quantityChanged: null,
        quantityScheduled: null,
        clientId: null,
        groupKey: null,
        groupCounter: 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,
        startDate: null,
        updateTime: null,
        packType: null,
        packUnitOfMeasure: null,
        lossIndividuallyWrap: null,
        packNum: 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>
