<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'|| mode== 'make'">
        <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 v-if="mode === 'make'|| mode === 'makeInfo'" :lg="6" :md="8" :sm="12" :xs="12">
            <el-form-item label="父工单编码" prop="parentCode">
              <el-input
                disabled
                v-model="form.parentCode"
                placeholder="自动生成"
              ></el-input>
            </el-form-item>
          </el-col>
          <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 :disabled="mode == 'make'" 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
                :disabled="mode == 'make'"
                placeholder="请选择工艺路线"
              >
                <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="产品编号" prop="productCode">
              <el-input :disabled="mode == 'make'" v-model="form.productCode" placeholder="请选择产品">
                <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="产品名称" 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"
                @blur="handleChangeQuantity"
              />
            </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="请输入计量单位"
                :disabled="mode == 'make'"
              />
            </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"
                :disabled="mode == 'make'"
                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"
                :disabled="mode == 'make'"
                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
                :disabled="mode == 'make'"
                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
                :disabled="mode == 'make'"
                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" :disabled="mode == 'make'" placeholder="请输入批号" />
            </el-form-item>
          </el-col>
          <el-col :lg="6" :md="8" :sm="12" :xs="12">
            <el-form-item label="工单状态" prop="status">
              <el-select v-model="form.status" :disabled="mode == 'make'" placeholder="请选择工单状态">
                <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="派工倍数" :disabled="mode == 'make'" prop="dispatchMultiple">
              <el-input
                v-model="form.dispatchMultiple"
                :disabled="mode == 'make'"
                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" :disabled="mode == 'make'" 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" :disabled="mode == 'make'" 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" :disabled="mode == 'make'" placeholder="请输入厚度(丝)" />
            </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'" placeholder="请输入包装数量" />
            </el-form-item>
          </el-col>
          <el-col :lg="6" :md="8" :sm="12" :xs="12">
            <el-form-item label="按指令包装" prop="packByDirective">
              <el-select v-model="form.packByDirective" :disabled="mode == 'make'" placeholder="请选择类型">
                <el-option
                  v-for="dict in dict.type.sys_yes_no"
                  :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="按size包装" prop="packBySize">
              <el-select v-model="form.packBySize" :disabled="mode == 'make'" placeholder="请选择类型">
                <el-option
                  v-for="dict in dict.type.sys_yes_no"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </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"
                :disabled="mode == 'make'"
                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,
  getMakeWorkorderCode,
  makeSubmitWorkorder
} 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",
    "sys_yes_no",
  ],
  provide() {
    return {
      mode: this.mode,
    };
  },
  data() {
    return {
      loading: false,
      optType: undefined,

      bomList: [],
      // 表单参数
      form: {
        workorderId: null,
        workorderCode: null,
        workorderName: null,
        routeName: null,
        workorderType: "product",
        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,
        packBySize: null,
        packByDirective: null,
        packNum: 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" },
        ],
      },
      currentData: {}
    };
  },
  computed: {
    scrollHeight() {
      return "calc(100vh - 73px - 83px)";
    },
    mode() {
      return this.$route.path.split("/").at(-1);
    },
    pageTitle() {
      const titles = {
        edit: "工单修改",
        info: "工单新增",
        apply: "工单申请",
        make: "补单工单",
        makeInfo: "补数订单查看",
      };
      return titles[this.mode];
    },
  },
  created() {
    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')
          console.log(this.currentData.quantity, 'this.currentData.quantity')
          let quantity = parseInt(this.form.quantity*item.quantity*100/this.currentData.quantity)
          // console.log(quantity, 'quantity')
          return {
            ...item,
            quantity: quantity/100
          }
        })
        console.log(bomList, 'bomList')
        this.bomList = bomList
        this.$refs["ProogingBomRef"].tableData = bomList
      }
    },
    /** 查询生产工单下拉树结构 */
    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() {
      if (this.mode === 'apply') {
        genCode("WORKORDER_CODE").then((response) => {
          this.form.workorderCode = response;
        });
      } else if(this.mode === 'make') {
        getMakeWorkorderCode(this.form.parentCode).then(res => {
          console.log(res, 88899)
          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();
            }
            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.$refs.form.validate( valid => {
        if (valid) {
          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 if(this.mode === 'make') {
            makeSubmitWorkorder(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: "product",
        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,
        packBySize: null,
        packByDirective: 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>
