<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"
        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="orderSource">
              <el-radio-group
                v-model="form.orderSource"
                disabled
                v-if="optType == 'view'"
              >
                <el-radio
                  v-for="dict in dict.type.mes_workorder_sourcetype"
                  :key="dict.value"
                  :label="dict.value"
                  >{{ dict.label }}</el-radio
                >
              </el-radio-group>
              <el-radio-group v-model="form.orderSource" v-else>
                <el-radio
                  v-for="dict in dict.type.mes_workorder_sourcetype"
                  :key="dict.value"
                  :label="dict.value"
                  >{{ dict.label }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col
            :lg="6"
            :md="8"
            :sm="12"
            :xs="12"
            v-if="form.orderSource == 'ORDER'"
          >
            <el-form-item label="订单编号" prop="sourceCode">
              <el-input
                v-model="form.sourceCode"
                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
                placeholder="请选择单据状态"
              >
                <el-option
                  v-for="dict in dict.type.mes_order_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="单据状态" prop="status">
              <el-select v-model="form.status" disabled>
                <el-option
                  v-for="dict in dict.type.mes_order_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="工单类型" 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="unitOfMeasure">
              <el-input
                v-model="form.unitOfMeasure"
                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-number
                :min="1"
                v-model="form.quantity"
                placeholder="请输入生产数量"
              />
            </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="batchCode">
              <el-input v-model="form.batchCode" placeholder="请输入批次号" />
            </el-form-item>
          </el-col>
          <!-- <el-row v-if="form.orderSource == 'ORDER'"> -->
          <el-col
            :lg="6"
            :md="8"
            :sm="12"
            :xs="12"
            v-if="form.orderSource == 'ORDER'"
          >
            <el-form-item label="客户编码" prop="clientCode">
              <el-input v-model="form.clientCode" placeholder="请选择客户">
                <el-button
                  slot="append"
                  @click="handleSelectClient"
                  icon="el-icon-search"
                ></el-button>
              </el-input>
              <ClientSelect ref="clientSelect" @onSelected="onClientSelected">
              </ClientSelect>
            </el-form-item>
          </el-col>
          <el-col
            :lg="6"
            :md="8"
            :sm="12"
            :xs="12"
            v-if="form.orderSource == 'ORDER'"
          >
            <el-form-item label="客户名称" prop="clientName">
              <el-input
                v-model="form.clientName"
                readonly="readonly"
                placeholder="请输入客户名称"
              />
            </el-form-item>
          </el-col>

          <el-col
            :lg="6"
            :md="8"
            :sm="12"
            :xs="12"
            v-if="
              form.workorderType == 'OUTSOURCE' ||
              form.workorderType == 'PURCHASE'
            "
          >
            <el-form-item label="供应商编码" prop="vendorCode">
              <el-input v-model="form.vendorCode" placeholder="请选择供应商">
                <el-button
                  slot="append"
                  @click="handleSelectVendor"
                  icon="el-icon-search"
                ></el-button>
              </el-input>
              <VendorSelect ref="vendorSelect" @onSelected="onVendorSelected" />
            </el-form-item>
          </el-col>
          <el-col
            :lg="6"
            :md="8"
            :sm="12"
            :xs="12"
            v-if="
              form.workorderType == 'OUTSOURCE' ||
              form.workorderType == 'PURCHASE'
            "
          >
            <el-form-item label="供应商名称" prop="vendorName">
              <el-input
                v-model="form.vendorName"
                readonly="readonly"
                placeholder="请选择供应商"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :lg="6" :md="8" :sm="12" :xs="12">
            <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-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 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,
    ItemSelect,
    RoutesProcessSelect,
    ClientSelect,
    VendorSelect,
  },
  dicts: ["mes_order_status", "mes_workorder_sourcetype", "mes_workorder_type"],
  provide() {
    return {
      mode: this.mode,
    };
  },
  data() {
    return {
      loading: false,
      optType: undefined,

      bomList: [],
      // 表单参数
      form: {
        // prototypeRequestCode: "",
        // itemId: "",
        // itemName: "",
        // unit: "",
        // routeId: "",
        // routeName: "",
        // abbreviation: "",
        // enName: "",
        // num: "",
        // type: "",
        // status: "PREPARE",
        // modality: "",
        // surfaceTreatment: "",
        // ngReason: "",
        // plannedFinishDate: "",
        // plannedLayoutDate: "",
        // testStandard: "",
        // remark: "",
        workorderCode: "",
        workorderName: "",
        orderSource: "",
        routeName: "",
        sourceCode: "",
        productId: "",
        productCode: "",
        productName: "",
        productSpc: "",
        unitOfMeasure: "",
        quantity: "",
        quantityProduced: "",
        quantityChanged: "",
        quantityScheduled: "",
        clientId: "",
        clientCode: "",
        clientName: "",
        requestDate: "",
        parentId: "",
        ancestors: "",
        status: "PREPARE",
      },
      // 表单校验
      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;
          })
          .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 params = {
        ...this.form,
        bomList,
        processList,
      };
      this.loading = true;
      if (this.mode == "apply") {
        addWorkorder(params)
          .then((res) => {
            this.loading = false;
            this.$modal.msgSuccess("提交成功！");

            // 关闭页签
            tabPlugins.closeOpenPage();
          })
          .catch(() => {
            this.loading = false;
          });
      } else {
        updateWorkorder(params)
          .then(() => {
            this.loading = false;
            this.$modal.msgSuccess("提交成功！");
          })
          .catch(() => {
            this.loading = false;
          });
      }
    },
    /**重置表单 */
    resetForm() {
      this.form = {
        // prototypeRequestCode: "",
        // itemId: "",
        // itemName: "",
        // routeId: "",
        // abbreviation: "",
        // enName: "",
        // num: "",
        // type: "",
        // modality: "",
        // surfaceTreatment: "",
        // ngReason: "",
        // plannedFinishDate: "",
        // plannedLayoutDate: "",
        // testStandard: "",
        // remark: "",
        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.gCode();
    },
  },
};
</script>

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