<template>
  <div class="form-page" 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
        :model="form"
        ref="form"
        size="small"
        :inline="true"
        label-width="8em"
      >
        <el-row>
          <el-col :md="8" :xs="12">
            <el-form-item label="量产制作单编码" prop="productionMakeCode">
              <el-input
                disabled
                v-model="form.productionMakeCode"
                placeholder="自动生成"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :md="8" :xs="12" style="height: 50.5px">
            <el-form-item label="产品" prop="itemId">
              <el-input
                v-model="form.itemName"
                readonly
                placeholder="请选择产品"
              >
                <el-button
                  slot="append"
                  icon="el-icon-search"
                  @click="$refs['ItemSelectRef'].showFlag = true"
                  v-if="false"
                ></el-button>
              </el-input>
              <ItemSelect ref="ItemSelectRef" @onSelected="onItemSelect" />
            </el-form-item>
          </el-col>
          <el-col :md="8" :xs="12" style="height: 50.5px">
            <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"
                  v-if="false"
                ></el-button>
              </el-input>
              <RoutesProcessSelect
                ref="RoutesProcessSelectRef"
                @onSelected="onRoutesProcessSelect"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :md="8" :xs="12">
            <el-form-item label="印刷正面颜色" prop="printingFrontcolor">
              <el-input v-model="form.printingFrontcolorName"
                        readonly
                        placeholder="请输入印刷正面颜色">
                <el-button
                  slot="append"
                  icon="el-icon-search"
                  @click="$refs['printingFrontcolorSelect'].showFlag = true"
                ></el-button>
              </el-input>
              <ColorSelect
                ref="printingFrontcolorSelect"
                @onSelected="onPrintingFrontcolorSelected"
              >
              </ColorSelect>
            </el-form-item>
          </el-col>
          <el-col :md="8" :xs="12">
            <el-form-item label="印刷背面颜色" prop="printingBackcolor">
              <el-input
                readonly
                v-model="form.printingBackcolorName"
                placeholder="请输入印刷背面颜色"
              >
                <el-button
                  slot="append"
                  icon="el-icon-search"
                  @click="$refs['printingBackcolorSelect'].showFlag = true"
                ></el-button>
              </el-input>
              <ColorSelect
                ref="printingBackcolorSelect"
                @onSelected="onPrintingBackcolorSelected"
              >
              </ColorSelect>
            </el-form-item>
          </el-col>

        </el-row>

        <el-row>
          <el-col :md="8" :xs="12">
            <el-form-item label="备注" prop="remark">
              <el-input
                type="textarea"
                :rows="3"
                v-model="form.remark"
                placeholder="备注"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :md="8" :xs="12">
            <el-form-item label="产品正面" prop="frontImg">
              <ImageUpload :limit="1" :value="form.frontImg" fieldName="frontImg" :fileSize="5"
                           @onUploaded="handleImgUploaded" @onRemoved="handleImgRemoved"></ImageUpload>
            </el-form-item>
          </el-col>
          <el-col :md="8" :xs="12">
            <el-form-item label="产品背面" prop="backImg">
              <ImageUpload :limit="1" :value="form.backImg" fieldName="backImg" :fileSize="5" @onUploaded="handleImgUploaded" @onRemoved="handleImgRemoved"></ImageUpload>
            </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>
  </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 { closeOpenPage } from "@/plugins/tab";
import ColorSelect from "@/components/colorSelect/index.vue";

//新增方法的js
import { listProductionMake, getProductionMake, delProductionMake, addProductionMake, updateProductionMake } from "@/api/mes/pro/productionMake";
import { getProductionRequest } from "@/api/mes/pro/productionRequest";

export default {
  components: { ProogingBom, ProogingProcess, ItemSelect, RoutesProcessSelect, ColorSelect },
  dicts: [],
  provide() {
    return {
      mode: this.mode,
    };
  },
  data() {
    return {
      loading: false,
      bomList: [],
      // 表单参数
      form: {
        prototypeRequestCode: "",
        itemId: "",
        itemName: "",
        unit: "",
        routeId: "",
        routeName: "",
        abbreviation: "",
        enName: "",
        num: "",
        type: "",
        modality: "",
        surfaceTreatment: "",
        ngReason: "",
        plannedFinishDate: "",
        plannedLayoutDate: "",
        testStandard: "",
        remark: "",
        //量产制作单参数（注意修改---------------------------------------------------------）
        productionMakeId: null,
        productionMakeCode: null,
        productionRequestId: null,
        identifyingPeople: null,
        identifyingDate: null,
        printingFrontcolor: null,
        printingBackcolor: null,
        printingFrontcolorName: null,
        printingBackcolorName: null,
        frontImg: null,
        backImg: null,
        productionMakeStatus: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      },
      rules: {},
    };
  },
  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();
    this.gCode();
  },
  methods: {
    /** 根据 id 获取页面数据 */
    getFormInfo() {
      if (this.mode != "apply") {
        const id = this.$route.query.productionMakeId;
        this.loading = true;
        getProductionMake(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;
          });
      }else if(this.$route.query.productionRequestId){
        this.loading = true;
        getProductionRequest(this.$route.query.productionRequestId)
          .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("PRODUCTION_MAKE_CODE").then((response) => {
        this.form.productionMakeCode = 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,
        'productionRequestId':this.$route.query.productionRequestId,
        bomList,
        processList,
      };
      this.loading = true;
      if (this.mode == "apply") {
        addProductionMake(params)
          .then((res) => {
            this.loading = false;
            this.$modal.msgSuccess("提交成功！");

            // 关闭页签
            closeOpenPage();
          })
          .catch(() => {
            this.loading = false;
          });
      } else {
        updateProductionMake(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: "",
        //量产制作单参数（注意修改---------------------------------------------------------）
        productionMakeId: null,
        productionMakeCode: null,
        productionRequestId: null,
        identifyingPeople: null,
        identifyingDate: null,
        printingFrontcolor: null,
        printingBackcolor: null,
        printingFrontcolorName: null,
        printingBackcolorName: null,
        frontImg: null,
        backImg: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.$refs["ProogingBomRef"].resetState();
      this.$refs["ProogingProcessRef"].resetState();
      this.gCode();
    },
    onPrintingBackcolorSelected(obj) {
      if (obj != undefined && obj != null) {
        obj.forEach((element) => {
          this.form.printingBackcolor = element.colorId;
          this.form.printingBackcolorName = element.colorName;
        });
      }
    },
    onPrintingFrontcolorSelected(obj) {
      if (obj != undefined && obj != null) {
        obj.forEach((element) => {
          this.form.printingFrontcolor = element.colorId;
          this.form.printingFrontcolorName = element.colorName;
        });
      }
    },
    //图片上传成功
    handleImgUploaded(imgUrl, obj){
      this.form[obj.$attrs.fieldName] = imgUrl;
    },
    //图片移除
    handleImgRemoved(imgUrl, obj){
      this.form[obj.$attrs.fieldName] = null;
    },

  },
};
</script>

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