<template>
  <div class="form-page" 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'">
        <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"
        size="small"
        :inline="true"
        label-width="8em"
      >
        <el-row>
          <el-col :lg="6" :md="8" :sm="12" :xs="12">
            <el-form-item :label="$t('生产版本编码')" prop="productionSolutionCode">
              <el-input
                v-model="form.productionSolutionCode"
                placeholder
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :lg="6" :md="8" :sm="12" :xs="12">
            <el-form-item :label="$t('生产版本名称')" prop="productionSolutionName">
              <el-input
                v-model="form.productionSolutionName"
                placeholder
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :lg="6" :md="8" :sm="12" :xs="12">
            <el-form-item :label="$t('产品编码')" prop="itemCode">
              <el-input :disabled="mode == 'info'" v-model="form.itemCode">
                <el-button
                  slot="append"
                  v-if="mode !== 'info'"
                  @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="itemName">
              <el-input v-model="form.itemName" disabled placeholder></el-input>
            </el-form-item>
          </el-col>
          <el-col :lg="6" :md="8" :sm="12" :xs="12">
            <el-form-item :label="$t('有效起始日期')" prop="startDate">
              <el-date-picker
                clearable
                v-model="form.startDate"
                type="date"
                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="expiryDate">
              <el-date-picker
                clearable
                v-model="form.expiryDate"
                type="date"
                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="unitOfMeasure">
              <el-input
                v-model="form.unitOfMeasure"
                disabled
                placeholder
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :lg="6" :md="8" :sm="12" :xs="12">
            <el-form-item :label="$t('common.remark')" prop="remark">
              <el-input
                type="textarea"
                :rows="3"
                v-model="form.remark"
                placeholder
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <el-tabs type="border-card" @tab-click="tabClick">
        <!-- <el-tab-pane label="BOM" style="display: none"> -->
          <ProogingBom ref="ProogingBomRef" style="display: none"/>
        <!-- </el-tab-pane> -->
        <el-tab-pane :label="$t('工艺')">
          <ProogingProcess ref="ProogingProcessRef" :bomList="bomList" />
        </el-tab-pane>
      </el-tabs>
    </PageWrapper>
    <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 RoutesProcessSelect from "@/components/routesProcessSelect/index.vue";
import { listRouteprocess } from "@/api/mes/pro/routeprocess";
import tabPlugins from "@/plugins/tab";
import {
  addProductionSolution,
  // getPrototypeRequest,
  updateProductionSolution,
  getProductionSolution,
  submitProductionSolution,
} from "@/api/mes/pro/productionSolution";

export default {
  components: {
    ProogingBom,
    ProogingProcess,
    ItemSelect,
    RoutesProcessSelect
  },
  provide() {
    return {
      mode: this.mode,
    };
  },
  data() {
    return {
      loading: false,
      bomList: [],
      productionSolutionId: null,
      // 表单参数
      form: {
        productionSolutionId: "",
        productionSolutionCode: "",
        productionSolutionName: "",
        productionSolutionType: "",
        itemId: "",
        itemName: "",
        routeId: "",
        routeName: "",
        usageId: "",
        usageName: "",
        startDate: "",
        expiryDate: "",
        maxLot: "",
        minLot: "",
        unitOfMeasure: "",
        materialsGroupBill: "",
        alternativeBill: "",
        groupCounter: "",
        groupKey: "",
        status: "",
        sapItemCode: "",
        factoryCode: "",
        sapUsageId: "",
        remark: "",
        createBy: "",
        createTime: "",
        itemCode: "",
        updateBy: "",
        updateTime: "",
      },
      rules: {
        productionSolutionName: [
          { required: true, message: this.$t('生产版本名称不能为空'), trigger: "blur" },
        ],
      },
    };
  },
  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('生产版本新增'),
      };
      return titles[this.mode];
    },
  },
  
  created() {
    if (this.$route.query && this.$route.query.productionSolutionId && this.productionSolutionId !== this.$route.query.productionSolutionId) {
      this.productionSolutionId = this.$route.query.productionSolutionId
    }
    if(this.mode === 'apply') this.handleAutoGenChange()
    this.getFormInfo();
  },
  activated() {
    if (this.$route.query && this.$route.query.productionSolutionId && this.productionSolutionId !== this.$route.query.productionSolutionId) {
      this.resetForm()
      this.productionSolutionId = this.$route.query.productionSolutionId
      this.getFormInfo();
    }
  },
  methods: {
    //自动生成编码
    handleAutoGenChange() {
      genCode("PRO_SOLUTION_CODE").then((response) => {
        this.form.productionSolutionCode = response;
      });
    },
    //物料选择弹出框
    onItemSelected(obj) {
      if (obj != undefined && obj != null) {
        this.form.itemCode = obj.itemCode;
        this.form.itemName = obj.itemName;
        this.form.sapItemCode = obj.sapItemCode;
        this.form.productionSolutionName = obj.itemName;
        this.form.unitOfMeasure = obj.unitOfMeasure;
      }
    },
    handleSelectProduct() {
      this.$refs.itemSelect.showFlag = true;
    },
    /** 根据 id 获取页面数据 */
    getFormInfo() {
      if (this.mode != "apply") {
        const id = this.$route.query.productionSolutionId;
        this.loading = true;
        getProductionSolution(id)
          .then(({ data }) => {
            Object.assign(this.form, data);
            this.bomList = data.bomHead.bomItemList;
            // 设置组件数据
            this.$refs["ProogingBomRef"].form2 = data.bomHead;
            this.$refs["ProogingBomRef"].tableData = data.bomHead.bomItemList;
            this.$refs["ProogingProcessRef"].setList(data.processList)
          })
          .finally(() => {
            this.loading = false;
          });
      }
    },
    /** 点击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;
      }
    },
    /**提交 */
    saveForm() {
      const bomHead = this.$refs.ProogingBomRef.getComData();
      const processList = this.$refs.ProogingProcessRef.getComData();
      if (typeof processList === 'boolean') return
      const params = {
        ...this.form,
        bomHead,
        processList,
        specificationSheet: {}
      };
      this.$refs.form.validate( valid => {
        if (valid) {
          this.loading = true;
          if (this.mode == "apply") {
            addProductionSolution(params)
              .then((res) => {
                this.loading = false;
                this.$modal.msgSuccess(this.$t('提交成功！'));
                this.$nextTick(() => {
                  // 关闭页签
                  tabPlugins.closeOpenPage();
                  this.$tab.closePage({
                    path: "/mes/md/production",
                    name: "Production"
                  });
                  this.$nextTick(() => {
                    this.$router.replace({
                        path: "/mes/md/production",
                      });
                  })
                  
                })
              })
              .catch(() => {
                this.loading = false;
              });
          } else {
            updateProductionSolution(params)
              .then(() => {
                this.loading = false;
                this.$modal.msgSuccess(this.$t('提交成功！'));
                this.$nextTick(() => {
                  // 关闭页签
                  tabPlugins.closeOpenPage();
                  this.$tab.closePage({
                    path: "/mes/md/production",
                    name: "Production"
                  });
                  this.$nextTick(() => {
                    this.$router.replace({
                        path: "/mes/md/production",
                      });
                  })
                })
              })
              .catch(() => {
                this.loading = false;
              });
          }
        }
      })
    },
    /**重置表单 */
    resetForm() {
      this.form = {
        productionSolutionId: "",
        productionSolutionCode: "",
        productionSolutionName: "",
        productionSolutionType: "",
        itemId: "",
        itemName: "",
        routeId: "",
        routeName: "",
        usageId: "",
        usageName: "",
        startDate: "",
        expiryDate: "",
        maxLot: "",
        minLot: "",
        unitOfMeasure: "",
        materialsGroupBill: "",
        alternativeBill: "",
        groupCounter: "",
        groupKey: "",
        status: "",
        sapItemCode: "",
        factoryCode: "",
        remark: "",
        createBy: "",
        createTime: "",
        updateBy: "",
        updateTime: "",
        sapUsageId: "",
      };
      this.$refs["ProogingBomRef"].resetState();
      this.$refs["ProogingProcessRef"].resetState();
    },
  },
};
</script>

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