<template>
  <div class="customer-css" ref="pageRoot">
    <!--  查询时间和产品  -->
    <el-form ref="searchForm" :inline="true" label-position="top" label-width="100px" style="margin-top: 0px;" >
      <el-row>
        <el-col :span="24" style="">
          <el-form-item :label="'产品编码:'">
            <!-- <span style="cursor: pointer" slot="label" @click="getBaseList(520)"><a href="#">产品编码</a></span> -->
            <el-input v-model="searchData.partNo" style="width: 130px"></el-input>
          </el-form-item>
          <el-form-item :label="'基准料号:'">
            <el-input v-model="searchData.basePartNo" style="width: 130px"></el-input>
          </el-form-item>
<!--          <el-form-item :label="'NPC货号:'">-->
<!--            <el-input v-model="searchData.npc" style="width: 130px"></el-input>-->
<!--          </el-form-item>-->
          <el-form-item :label="'产品名称:'">
            <el-input v-model="searchData.partDesc" style="width: 130px"></el-input>
          </el-form-item>
          <el-form-item :label="'Item:'">
            <el-input v-model="searchData.item" style="width: 130px"></el-input>
          </el-form-item>
          <el-form-item :label="'SKU:'">
            <el-input v-model="searchData.sku" style="width: 130px"></el-input>
          </el-form-item>
          <el-form-item :label="'默认供应商:'">
            <el-input v-model="searchData.defaultSupplierNo" style="width: 130px"></el-input>
          </el-form-item>
          <el-form-item :label="'一级分类:'">
            <el-select v-model="searchData.category" clearable filterable style="width: 130px" @change="onSearchCategoryChange">
              <el-option v-for="item in searchCategoryLevel1Options" :key="item.familyId"
                :label="item.familyName" :value="item.familyId" />
            </el-select>
          </el-form-item>
          <el-form-item :label="'二级分类:'">
            <el-select v-model="searchData.categoryLevel2" clearable filterable style="width: 130px"
              :disabled="!searchData.category" @change="onSearchCategoryLevel2Change">
              <el-option v-for="item in searchCategoryLevel2Options" :key="item.familyId"
                :label="item.familyName" :value="item.familyId" />
            </el-select>
          </el-form-item>
          <el-form-item :label="'三级分类:'">
            <el-select v-model="searchData.categoryLevel3" clearable filterable style="width: 130px"
              :disabled="!searchData.categoryLevel2">
              <el-option v-for="item in searchCategoryLevel3Options" :key="item.familyId"
                :label="item.familyName" :value="item.familyId" />
            </el-select>
          </el-form-item>
          <el-form-item :label="' '">
            <el-button class="customer-bun-min" type="primary" @click="getMainData" style="">查询</el-button>
            <el-button @click="addPart()" type="primary" style="margin-left: 2px">新增</el-button>
            <el-button @click="openCopyDialog" type="primary" style="margin-left: 2px">复制</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-table
      :height="height"
      :data="mainDataList"
      border
      ref="mainTable"
      highlight-current-row
      @row-click="changeData"
      v-loading="dataListLoading"
      style="margin-top: 0px; width: 100%;">
      <el-table-column
        v-for="(item,index) in columnArray1" :key="index"
        :sortable="item.columnSortable"
        :prop="item.columnProp"
        :header-align="item.headerAlign"
        :show-overflow-tooltip="item.showOverflowTooltip"
        :align="item.align"
        :fixed="item.fixed==''?false:item.fixed"
        :min-width="item.columnWidth"
        :label="item.columnLabel">
        <template slot-scope="scope">
          <span v-if="!item.columnHidden">{{
            formatTableCell(item.columnProp, scope.row)
          }}</span>
          <span v-if="item.columnImage"><img :src="scope.row[item.columnProp]"
                                             style="width: 100px; height: 100px"/></span>
        </template>
      </el-table-column>
      <!-- 操作列 -->
      <el-table-column
        fixed="right"
        header-align="center"
        align="center"
        width="200"
        label="Action">
        <template slot-scope="scope">
          <!-- <el-link style="cursor: pointer" v-if="scope.row.flowStatus === 'COMPLETED' || scope.row.flowStatus === 'TERMINATED'" @click="handleRestart(scope.row)">重新审批 |</el-link>
          <el-link style="cursor: pointer" v-if="scope.row.flowStatus === 'RUNNING'" @click="openApproveDialog(scope.row)">审批 |</el-link> -->
          <el-link style="cursor: pointer" v-if="scope.row.partStage === 'Created'" @click="startFormalApprove(scope.row)">转正 |</el-link>
          <el-link style="cursor: pointer" @click="openChangeDefaultSupplier(scope.row)">变更默认供应商 |</el-link>
          <el-link style="cursor: pointer" @click="editPart(scope.row)">编辑 |</el-link>
          <el-link style="cursor: pointer" @click="deletePart(scope.row)">删除</el-link>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页插件 -->
    <el-pagination ref="mainPagination" style="margin-top: 0px"
                   @size-change="sizeChangeHandle"
                   @current-change="currentChangeHandle"
                   :current-page="pageIndex"
                   :page-sizes="[20, 50, 100, 200, 500]"
                   :page-size="pageSize"
                   :total="totalPage"
                   layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>

    <el-tabs ref="partTabs" v-model="activeName" style="margin-top: 0px; width: 99%;" @tab-click="tabClick" class="customer-tab" type="border-card">
      <el-tab-pane label="基础信息" name="basicInfo" style="">
        <basicInfo ref="basicInfo"></basicInfo>
      </el-tab-pane>
      <el-tab-pane label="规格参数" name="specParams" style="">
        <specParams ref="specParams"></specParams>
      </el-tab-pane>
      <el-tab-pane label="关联供应商" name="suppliers" style="">
        <suppliers ref="suppliers"></suppliers>
      </el-tab-pane>
      <el-tab-pane label="审批与放行" name="approval" style="">
        <approval ref="approval"></approval>
      </el-tab-pane>
      <el-tab-pane label="附件" name="attachments" style="">
        <attachments ref="attachments"></attachments>
      </el-tab-pane>
    </el-tabs>

    <Chooselist ref="baseList" @getBaseData="getBaseData"></Chooselist>

    <!-- 产品编辑对话框 -->
    <!-- 默认弹窗可拖动，特殊需求除外 - rqrq -->
    <el-dialog :title="isAdd ? '新增产品' : '编辑产品'" :visible.sync="partDialogVisible" width="720px" top="3vh" :close-on-click-modal="false" class="part-dialog" v-drag>
      <div class="dialog-content">
        <el-form
          :model="currentpart"
          :rules="partRules"
          ref="partForm"
          label-position="top"
          class="part-form">
          <div class="form-section">
            <el-row :gutter="24">
              <el-col :span="6">
                <el-form-item label="基准料号" prop="basePartNo">
                  <el-input v-model="currentpart.basePartNo" :disabled="!isAdd" @input="syncGeneratedPartNo"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="物料后缀" prop="partSuffix">
                  <el-input v-model="currentpart.partSuffix" :disabled="!isAdd" @input="syncGeneratedPartNo"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="产品编码" prop="partNo">
                  <el-input v-model="currentpart.partNo" disabled></el-input>
                </el-form-item>
              </el-col>
<!--              <el-col :span="6">-->
<!--                <el-form-item label="NPC货号" prop="npc">-->
<!--                  <el-input v-model="currentpart.npc"></el-input>-->
<!--                </el-form-item>-->
<!--              </el-col>-->
            </el-row>
            <el-row :gutter="24">
              <el-col :span="6">
                <el-form-item>
                  <span style="cursor: pointer" slot="label" @click="getBaseList(510)"><a href="#">计量单位</a></span>
                  <el-input v-model="currentpart.unit" ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item prop="defaultSupplierNo">
                  <span style="cursor: pointer" slot="label" @click="getBaseList(520)"><a href="#">默认供应商</a></span>
                  <el-input v-model="currentpart.defaultSupplierNo" ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="Item">
                  <el-input v-model="currentpart.item"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="SKU">
                  <el-input v-model="currentpart.sku"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24">
              <el-col :span="6">
                <el-form-item label="一级分类">
                  <el-select v-model="currentpart.category" clearable filterable style="width: 100%" @change="onPartCategoryChange">
                    <el-option v-for="item in categoryLevel1Options" :key="item.familyId"
                      :label="item.familyName" :value="item.familyId" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="二级分类">
                  <el-select v-model="currentpart.categoryLevel2" clearable filterable style="width: 100%"
                    :disabled="!currentpart.category" @change="onPartCategoryLevel2Change">
                    <el-option v-for="item in categoryLevel2Options" :key="item.familyId"
                      :label="item.familyName" :value="item.familyId" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="三级分类">
                  <el-select v-model="currentpart.categoryLevel3" clearable filterable style="width: 100%"
                    :disabled="!currentpart.categoryLevel2">
                    <el-option v-for="item in categoryLevel3Options" :key="item.familyId"
                      :label="item.familyName" :value="item.familyId" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24">
                <el-col :span="12">
                <el-form-item label="产品名称" prop="partDesc">
                  <el-input v-model="currentpart.partDesc"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="产品规格" prop="partSpec">
                  <el-input v-model="currentpart.partSpec"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </div>

          <div class="form-section">
            <el-row :gutter="24">
              <el-col :span="6">
                <el-form-item >
                  <span style="cursor: pointer" slot="label" @click="getBaseList(529)"><a href="#">采购员</a></span>
                  <el-input v-model="currentpart.buyerName" ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item >
                  <span style="cursor: pointer" slot="label" @click="getBaseList(528)"><a href="#">sourcing专员</a></span>
                  <el-input v-model="currentpart.sourcingName"  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                  <el-form-item>
                  <span style="cursor: pointer" slot="label" @click="getBaseList(527)"><a href="#">属性模板</a></span>
                  <el-input v-model="currentpart.codeNo" ></el-input>
                </el-form-item>
              </el-col>
               <el-col :span="6">
               <el-form-item label="是否在用">
                  <el-select v-model="currentpart.status" placeholder="请选择" >
                    <el-option label="在用" value="Y"></el-option>
                    <el-option label="禁用" value="N"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </div>

          <div class="form-section">
            <el-row :gutter="24">
              <el-col :span="24">
                <el-form-item label="备注">
                  <el-input v-model="currentpart.remark" type="textarea" :rows="2" resize="none" ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer" style="margin-top: 20px">
        <el-button type="primary" @click="savePart()">保存</el-button>
        <el-button @click="partDialogVisible = false">取消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="复制物料" :visible.sync="copyDialogVisible" width="520px" :close-on-click-modal="false" v-drag>
      <el-form :model="copyForm" :rules="copyRules" ref="copyForm" label-position="top">
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="基准料号" prop="basePartNo">
              <el-input v-model="copyForm.basePartNo"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料后缀" prop="partSuffix">
              <el-input v-model="copyForm.partSuffix"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmCopyPart">确认</el-button>
        <el-button @click="copyDialogVisible = false">取消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="变更默认供应商" :visible.sync="changeSupplierDialogVisible" width="560px" :close-on-click-modal="false" v-drag>
      <el-form :model="changeSupplierForm" label-position="top">
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="变更范围">
              <el-select v-model="changeSupplierForm.changeMode" style="width: 100%">
                <el-option label="按产品编码" value="PART_NO"></el-option>
                <el-option label="按基准物料" value="BASE_PART"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="当前供应商编码">
              <el-input v-model="changeSupplierForm.currentSupplierNo" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="24">
            <el-form-item label="当前供应商描述">
              <el-input v-model="changeSupplierForm.currentSupplierName" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="24">
            <el-form-item>
              <span style="cursor: pointer" slot="label" @click="getBaseList(520, '', 'changeSupplier')"><a href="#">目标供应商</a></span>
              <el-input
                v-model="changeSupplierForm.targetSupplierNo"
                readonly
                placeholder="请选择目标供应商"
                @click.native="getBaseList(520, '', 'changeSupplier')">
                <i slot="suffix" class="el-icon-search" style="cursor:pointer" @click.stop="getBaseList(520, '', 'changeSupplier')"></i>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="changeSupplierLoading" @click="confirmChangeDefaultSupplier">确认</el-button>
        <el-button @click="changeSupplierDialogVisible = false">取消</el-button>
      </div>
    </el-dialog>

     <!-- 审批对话框 - rqrq -->
    <!-- <el-dialog
      title="审批"
      :visible.sync="approveDialogVisible"
      width="550px"
      :close-on-click-modal="false"
      v-drag>
      <el-form :model="approveData" label-position="top">
          <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="是否特殊放行">
              <el-select v-model="approveData.specialRelease" style="width: 100%">
                <el-option label="否" value="N"></el-option>
                <el-option label="是" value="Y"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="审批意见">
          <el-input type="textarea" v-model="approveData.comment" :rows="3" placeholder="请输入审批意见"></el-input>
        </el-form-item>
      </el-form>
      <el-footer style="height:40px;margin-top: 60px;text-align:center">
          <el-button type="success" @click="submitApprove('APPROVED')" :loading="approveLoading">同意</el-button>
        <el-button type="danger" @click="submitApprove('REJECTED')" :loading="approveLoading">驳回</el-button>
        <el-button @click="approveDialogVisible = false" :disabled="approveLoading">取消</el-button>
      </el-footer>
    </el-dialog> -->
  </div>
</template>

<script>
/* 组件 */

import {
  searchPartList,
  createPart,
  updatePart,
  copyPartByBase,
  deletePart,
  startPartFormalApprove,
  changePartDefaultSupplier
} from '@/api/part/partInfo.js'
import excel from '@/utils/excel-util.js'
import Chooselist from '@/views/modules/common/Chooselist_eam'
import basicInfo from './com_part_BasicInfo'
import specParams from './com_part_SpecParams'
import suppliers from './com_part_Suppliers'
import approval from './com_part_Approval'
import attachments from './com_part_Attachments'

import {
  approveNodeInstance,
  restartFlowInstance
} from '@/api/workFlow/workFlow.js'
import { listPartFamilyByType } from '@/api/baseInformation/srmPartFamily.js'
import { refreshPropertiesModal as refreshPartPropertiesModal } from '@/api/part/partProperties.js'

export default {
    watch: {
      searchData: {
        deep: true,
        handler: function (newV, oldV) {
          this.searchData.partNo = this.searchData.partNo.toUpperCase()
          this.searchData.npc = this.searchData.npc.toUpperCase()
          this.searchData.category = (this.searchData.category || '').toUpperCase()
          this.searchData.categoryLevel2 = (this.searchData.categoryLevel2 || '').toUpperCase()
          this.searchData.categoryLevel3 = (this.searchData.categoryLevel3 || '').toUpperCase()
          this.searchData.unit = this.searchData.unit.toUpperCase()
          this.searchData.codeNo = this.searchData.codeNo.toUpperCase()
          this.searchData.partDesc = this.searchData.partDesc.toUpperCase()
          this.searchData.partSpec = this.searchData.partSpec.toUpperCase()
          this.searchData.basePartNo = (this.searchData.basePartNo || '').toUpperCase()
          this.searchData.sku = (this.searchData.sku || '').toUpperCase()
          this.searchData.item = (this.searchData.item || '').toUpperCase()
          this.searchData.defaultSupplierNo = (this.searchData.defaultSupplierNo || '').toUpperCase()
        }
      },
      currentpart: {
        deep: true,
        handler: function (newV, oldV) {
          this.currentpart.partNo = this.currentpart.partNo.toUpperCase()
          this.currentpart.npc = this.currentpart.npc.toUpperCase()
          this.currentpart.category = (this.currentpart.category || '').toUpperCase()
          this.currentpart.categoryLevel2 = (this.currentpart.categoryLevel2 || '').toUpperCase()
          this.currentpart.categoryLevel3 = (this.currentpart.categoryLevel3 || '').toUpperCase()
          this.currentpart.unit = this.currentpart.unit.toUpperCase()
          this.currentpart.codeNo = this.currentpart.codeNo.toUpperCase()
          this.currentpart.partDesc = this.currentpart.partDesc.toUpperCase()
          this.currentpart.partSpec = this.currentpart.partSpec.toUpperCase()
          this.currentpart.basePartNo = (this.currentpart.basePartNo || '').toUpperCase()
          this.currentpart.partSuffix = (this.currentpart.partSuffix || '').toUpperCase()
          this.currentpart.sku = (this.currentpart.sku || '').toUpperCase()
          this.currentpart.item = (this.currentpart.item || '').toUpperCase()
          this.currentpart.defaultSupplierNo = (this.currentpart.defaultSupplierNo || '').toUpperCase()
          if (this.isAdd) {
            this.currentpart.partNo = this.generatePartNo(this.currentpart.basePartNo, this.currentpart.partSuffix)
          }
        }
      }
    },
  data () {
    return {
      functionId: this.$route.meta.menuId,
      height: 200,
      detailHeight: 320,
      currentRow: {},
      searchData: {
        partNo: '',
        basePartNo: '',
        npc: '',
        partDesc: '',
        partSpec: '',
        sku: '',
        item: '',
        defaultSupplierNo: '',
        buyerName: '',
        sourcingName: '',
        category: '',
        categoryLevel2: '',
        categoryLevel3: '',
        unit: '',
        status: '',
        codeNo: '',
        createBy: '',
        site: this.$store.state.user.site,
        page: 1,
        limit: 10
      },
      pageIndex: 1,
      pageSize: 50,
      totalPage: 0,
      searchCategoryLevel1Options: [],
      searchCategoryLevel2Options: [],
      searchCategoryLevel3Options: [],
      categoryLevel1Options: [],
      categoryLevel2Options: [],
      categoryLevel3Options: [],
      tagNo: '',
      mainDataList: [],
      dataListLoading: false,
      activeName: 'basicInfo',
        // 审批对话框
      approveDialogVisible: false,
      approveLoading: false,
      approveData: {
        applyNo: '',
        // nodeCode: '',
        // nodeName: '',
        // departmentName: '',  // 审批部门 - rqrq
        // assigneeName: '',
        site: '',
        orderType: '',
        comment: '',
        flowCode: '',
        flowVersion: null
      },
      columnArray1: [
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: 'partTablePartNo',
          tableId: 'partTable',
          tableName: '产品信息',
          columnProp: 'partNo',
          headerAlign: 'center',
          align: 'center',
          columnLabel: '产品编码',
          columnWidth: '100',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: 'partTableBasePartNo',
          tableId: 'partTable',
          tableName: '产品信息',
          columnProp: 'basePartNo',
          headerAlign: 'center',
          align: 'center',
          columnLabel: '基准料号',
          columnWidth: '120',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
        // {
        //   userId: this.$store.state.user.name,
        //   functionId: this.functionId,
        //   serialNumber: 'partTableNpc',
        //   tableId: 'partTable',
        //   tableName: '产品信息',
        //   columnProp: 'npc',
        //   headerAlign: 'center',
        //   align: 'center',
        //   columnLabel: 'NPC货号',
        //   columnWidth: '100',
        //   columnHidden: false,
        //   columnImage: false,
        //   columnSortable: false,
        //   sortLv: 0,
        //   status: true,
        //   fixed: false
        // },
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: 'partTableItem',
          tableId: 'partTable',
          tableName: '产品信息',
          columnProp: 'item',
          headerAlign: 'center',
          align: 'center',
          columnLabel: 'Item',
          columnWidth: '120',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: 'partTableSku',
          tableId: 'partTable',
          tableName: '产品信息',
          columnProp: 'sku',
          headerAlign: 'center',
          align: 'center',
          columnLabel: 'SKU',
          columnWidth: '120',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: 'partTableDefaultSupplierNo',
          tableId: 'partTable',
          tableName: '产品信息',
          columnProp: 'defaultSupplierNo',
          headerAlign: 'center',
          align: 'center',
          columnLabel: '默认供应商',
          columnWidth: '120',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: 'partTablePartDesc',
          tableId: 'partTable',
          tableName: '产品信息',
          columnProp: 'partDesc',
          headerAlign: 'center',
          align: 'left',
          columnLabel: '产品名称',
          columnWidth: '200',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: 'partTablepartSpec',
          tableId: 'partTable',
          tableName: '产品信息',
          columnProp: 'partSpec',
          headerAlign: 'center',
          align: 'left',
          columnLabel: '产品规格',
          columnWidth: '150',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: 'partTableBuyerName',
          tableId: 'partTable',
          tableName: '产品信息',
          columnProp: 'buyerName',
          headerAlign: 'center',
          align: 'center',
          columnLabel: '采购员',
          columnWidth: '100',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: 'partTableSourcingName',
          tableId: 'partTable',
          tableName: '产品信息',
          columnProp: 'sourcingName',
          headerAlign: 'center',
          align: 'center',
          columnLabel: 'sourcing专员',
          columnWidth: '100',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: 'partTableCategory',
          tableId: 'partTable',
          tableName: '产品信息',
          columnProp: 'categoryName',
          headerAlign: 'center',
          align: 'center',
          columnLabel: '一级分类',
          columnWidth: '100',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: 'partTableCategoryLevel2',
          tableId: 'partTable',
          tableName: '产品信息',
          columnProp: 'categoryLevel2Name',
          headerAlign: 'center',
          align: 'center',
          columnLabel: '二级分类',
          columnWidth: '100',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: 'partTableCategoryLevel3',
          tableId: 'partTable',
          tableName: '产品信息',
          columnProp: 'categoryLevel3Name',
          headerAlign: 'center',
          align: 'center',
          columnLabel: '三级分类',
          columnWidth: '100',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: 'partTableUnit',
          tableId: 'partTable',
          tableName: '产品信息',
          columnProp: 'unit',
          headerAlign: 'center',
          align: 'center',
          columnLabel: '计量单位',
          columnWidth: '80',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: 'partTablePartStage',
          tableId: 'partTable',
          tableName: '产品信息',
          columnProp: 'partStage',
          headerAlign: 'center',
          align: 'center',
          columnLabel: '物料阶段',
          columnWidth: '100',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: 'partTableStatus',
          tableId: 'partTable',
          tableName: '产品信息',
          columnProp: 'status',
          headerAlign: 'center',
          align: 'center',
          columnLabel: '是否在用',
          columnWidth: '80',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: 'partTableCodeNo',
          tableId: 'partTable',
          tableName: '产品信息',
          columnProp: 'codeNo',
          headerAlign: 'center',
          align: 'center',
          columnLabel: '属性模板',
          columnWidth: '100',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: 'partTableCreateBy',
          tableId: 'partTable',
          tableName: '产品信息',
          columnProp: 'createBy',
          headerAlign: 'center',
          align: 'center',
          columnLabel: '创建人',
          columnWidth: '100',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        }
        //  {
        //   userId: this.$store.state.user.name,
        //   functionId: this.functionId,
        //   serialNumber: 'partTableDepartmentName',
        //   tableId: 'partTable',
        //   tableName: '产品信息',
        //   columnProp: 'departmentName',
        //   headerAlign: 'center',
        //   align: 'center',
        //   columnLabel: '审批部门',
        //   columnWidth: '100',
        //   columnHidden: false,
        //   columnImage: false,
        //   columnSortable: false,
        //   sortLv: 0,
        //   status: true,
        //   fixed: false
        // },
        //  {
        //   userId: this.$store.state.user.name,
        //   functionId: this.functionId,
        //   serialNumber: 'partTableApproverName',
        //   tableId: 'partTable',
        //   tableName: '产品信息',
        //   columnProp: 'assigneeName',
        //   headerAlign: 'center',
        //   align: 'center',
        //   columnLabel: '要求审批人',
        //   columnWidth: '100',
        //   columnHidden: false,
        //   columnImage: false,
        //   columnSortable: false,
        //   sortLv: 0,
        //   status: true,
        //   fixed: false
        // },
        //  {
        //   userId: this.$store.state.user.name,
        //   functionId: this.functionId,
        //   serialNumber: 'partTableFlowStatus',
        //   tableId: 'partTable',
        //   tableName: '产品信息',
        //   columnProp: 'flowStatus',
        //   headerAlign: 'center',
        //   align: 'center',
        //   columnLabel: '审批状态',
        //   columnWidth: '100',
        //   columnHidden: false,
        //   columnImage: false,
        //   columnSortable: false,
        //   sortLv: 0,
        //   status: true,
        //   fixed: false
        // }
      ],
      exportName: '产品信息' + this.dayjs().format('YYYYMMDDHHmmss'),
      // 产品对话框相关
      partDialogVisible: false,
      isAdd: true,
      currentpart: {
        partNo: '',
        basePartNo: '',
        partSuffix: '',
        npc: '',
        partDesc: '',
        partSpec: '',
        sku: '',
        item: '',
        defaultSupplierNo: '',
        buyerName: '',
        sourcingName: '',
        category: '',
        categoryLevel2: '',
        categoryLevel3: '',
        unit: '',
        status: 'Y',
        codeNo: '',
        createBy: '',
        remark: '',
        site: this.$store.state.user.site,
      },
      partRules: {
         partDesc: [
          { required: true, message: ' ', trigger: 'blur' }
        ],
         npc: [
          { required: true, message: ' ', trigger: 'blur' }
        ],
         partSpec: [
        { required: true, message: ' ', trigger: 'blur' }
        ]
      },
      copyDialogVisible: false,
      copyForm: {
        basePartNo: '',
        partSuffix: ''
      },
      changeSupplierDialogVisible: false,
      changeSupplierLoading: false,
      changeSupplierForm: {
        changeMode: 'PART_NO',
        partNo: '',
        basePartNo: '',
        currentSupplierNo: '',
        currentSupplierName: '',
        targetSupplierNo: '',
        targetSupplierName: ''
      },
      basePickScene: '',
      copyRules: {
        basePartNo: [
          { required: true, message: '请输入基准料号', trigger: 'blur' }
        ],
        partSuffix: [
          { required: true, message: '请输入物料后缀', trigger: 'blur' }
        ]
      }
    }
  },
  /* 组件 */
  components: {
    Chooselist,
    basicInfo,
    specParams,
    suppliers,
    approval,
    attachments
  },

  created() {
    this.loadSearchCategoryLevel1()
    this.getMainData()
  },

  mounted () {
    this.handleResize()
    window.addEventListener('resize', this.handleResize)
  },

  beforeDestroy () {
    window.removeEventListener('resize', this.handleResize)
  },


  methods: {
    getOuterHeight (el) {
      if (!el) return 0
      const rect = el.getBoundingClientRect()
      const style = window.getComputedStyle(el)
      return rect.height + (parseFloat(style.marginTop) || 0) + (parseFloat(style.marginBottom) || 0)
    },
    handleResize () {
      this.$nextTick(() => {
        const rootEl = this.$refs.pageRoot || this.$el
        if (!rootEl) return
        const searchFormEl = this.$refs.searchForm && this.$refs.searchForm.$el
          ? this.$refs.searchForm.$el
          : this.$refs.searchForm
        const paginationEl = this.$refs.mainPagination && this.$refs.mainPagination.$el
          ? this.$refs.mainPagination.$el
          : this.$refs.mainPagination
        const tabsEl = this.$refs.partTabs && this.$refs.partTabs.$el
          ? this.$refs.partTabs.$el
          : this.$refs.partTabs
        const tabsHeaderEl = tabsEl ? tabsEl.querySelector('.el-tabs__header') : null
        const viewportBottomGap = 24
        const pageTop = rootEl.getBoundingClientRect().top
        const availableViewportHeight = window.innerHeight - pageTop - viewportBottomGap
        const fixedBlockHeight = this.getOuterHeight(searchFormEl) + this.getOuterHeight(paginationEl) + this.getOuterHeight(tabsHeaderEl) + 22
        const splitAvailable = availableViewportHeight - fixedBlockHeight
        if (!Number.isFinite(splitAvailable) || splitAvailable <= 0) return
        let mainTableHeight
        let detailHeight
        if (splitAvailable < 520) {
          mainTableHeight = Math.max(180, Math.floor(splitAvailable * 0.45))
          detailHeight = Math.max(220, splitAvailable - mainTableHeight)
        } else {
          mainTableHeight = Math.max(220, Math.floor(splitAvailable * 0.42))
          detailHeight = splitAvailable - mainTableHeight
          if (detailHeight < 320) {
            detailHeight = 320
            mainTableHeight = Math.max(200, splitAvailable - detailHeight)
          }
        }
        this.height = mainTableHeight
        this.detailHeight = detailHeight
        this.applyCurrentTabHeight()
        this.$nextTick(() => {
          if (this.$refs.mainTable && this.$refs.mainTable.doLayout) {
            this.$refs.mainTable.doLayout()
          }
        })
      })
    },
    getBasicTabHeight () {
      return Math.max(Number(this.height) - 20, 180)
    },
    getDetailTabHeight (offset = 0) {
      return Math.max(Number(this.detailHeight) - Number(offset || 0), 220)
    },
    applyCurrentTabHeight () {
      if (this.$refs.basicInfo && this.$refs.basicInfo.searchData) {
        this.$refs.basicInfo.searchData.height = this.getBasicTabHeight()
      }
      if (this.$refs.specParams && this.$refs.specParams.setTableHeight) {
        this.$refs.specParams.setTableHeight(this.getDetailTabHeight(70))
      }
      if (this.$refs.suppliers && this.$refs.suppliers.setTableHeight) {
        this.$refs.suppliers.setTableHeight(this.getDetailTabHeight(90))
      }
      if (this.$refs.approval && this.$refs.approval.setTableHeight) {
        this.$refs.approval.setTableHeight(this.getDetailTabHeight(30))
      }
      if (this.$refs.attachments && this.$refs.attachments.setTableHeight) {
        this.$refs.attachments.setTableHeight(this.getDetailTabHeight(90))
      }
    },
    formatPartStageDesc (partStage) {
      if (partStage === 'Approved') {
        return '正式物料'
      }
      if (partStage === 'Approving') {
        return '转正审批中'
      }
      return '新增物料'
    },
    formatTableCell (columnProp, row) {
      if (columnProp === 'partStage') {
        return this.formatPartStageDesc(row.partStage)
      }
      if (columnProp === 'status') {
        return row.status === 'Y' ? '在用' : row.status === 'N' ? '禁用' : row.status
      }
      if (columnProp === 'categoryName') {
        return row.categoryName || row.category || ''
      }
      if (columnProp === 'categoryLevel2Name') {
        return row.categoryLevel2Name || row.categoryLevel2 || ''
      }
      if (columnProp === 'categoryLevel3Name') {
        return row.categoryLevel3Name || row.categoryLevel3 || ''
      }
      return row[columnProp]
    },
    generatePartNo (basePartNo, partSuffix) {
      const base = (basePartNo || '').trim().toUpperCase()
      const suffix = (partSuffix || '').trim().toUpperCase()
      if (!base || !suffix) {
        return ''
      }
      return `${base}-${suffix}`
    },
    syncGeneratedPartNo () {
      if (!this.isAdd) return
      this.currentpart.partNo = this.generatePartNo(this.currentpart.basePartNo, this.currentpart.partSuffix)
    },
    extractBasePartNo (partNo) {
      const value = (partNo || '').trim().toUpperCase()
      if (!value) return ''
      const index = value.indexOf('-')
      return index > 0 ? value.substring(0, index) : value
    },
    extractPartSuffix (partNo) {
      const value = (partNo || '').trim().toUpperCase()
      if (!value) return ''
      const index = value.indexOf('-')
      return index > 0 && index < value.length - 1 ? value.substring(index + 1) : ''
    },
    openCopyDialog () {
      const selectedBasePartNo = (this.currentRow && this.currentRow.basePartNo) ? this.currentRow.basePartNo : ''
      this.copyForm = {
        // 复制弹窗默认带出当前选中行基准料号 - rqrq
        basePartNo: (selectedBasePartNo || '').trim().toUpperCase(),
        partSuffix: ''
      }
      this.copyDialogVisible = true
      this.$nextTick(() => {
        if (this.$refs.copyForm) {
          this.$refs.copyForm.clearValidate()
        }
      })
    },
    confirmCopyPart () {
      this.$refs.copyForm.validate((valid) => {
        if (!valid) return
        const basePartNo = (this.copyForm.basePartNo || '').trim().toUpperCase()
        const partSuffix = (this.copyForm.partSuffix || '').trim().toUpperCase()
        if (partSuffix.includes('-')) {
          this.$message.warning('物料后缀不能包含 "-"')
          return
        }
        copyPartByBase({
          site: this.$store.state.user.site,
          basePartNo,
          partSuffix
        }).then(({ data }) => {
          if (data && data.code === 0) {
            this.$message.success(`复制成功，新产品编码：${data.partNo || this.generatePartNo(basePartNo, partSuffix)}`)
            this.copyDialogVisible = false
            this.getMainData()
            return
          }
          this.$message.error((data && data.msg) || '复制失败')
        }).catch(error => {
          this.$message.error('复制失败: ' + error.message)
        })
      })
    },
    openChangeDefaultSupplier (row) {
      if (!row || !row.partNo) {
        this.$message.warning('请先选择物料')
        return
      }
      this.changeSupplierForm = {
        changeMode: 'PART_NO',
        partNo: (row.partNo || '').trim().toUpperCase(),
        basePartNo: (row.basePartNo || '').trim().toUpperCase(),
        currentSupplierNo: (row.defaultSupplierNo || '').trim().toUpperCase(),
        currentSupplierName: row.defaultSupplierName || '',
        targetSupplierNo: '',
        targetSupplierName: ''
      }
      this.changeSupplierDialogVisible = true
    },
    confirmChangeDefaultSupplier () {
      const targetSupplierNo = (this.changeSupplierForm.targetSupplierNo || '').trim().toUpperCase()
      const currentSupplierNo = (this.changeSupplierForm.currentSupplierNo || '').trim().toUpperCase()
      if (!targetSupplierNo) {
        this.$message.warning('目标供应商不能为空')
        return
      }
      if (targetSupplierNo === currentSupplierNo) {
        this.$message.warning('目标供应商不能与当前供应商相同')
        return
      }
      const payload = {
        site: this.$store.state.user.site,
        partNo: this.changeSupplierForm.partNo,
        changeMode: this.changeSupplierForm.changeMode,
        targetSupplierNo
      }
      this.changeSupplierLoading = true
      changePartDefaultSupplier(payload).then(({ data }) => {
        if (data && data.code === 0) {
          const updatedCount = data.updatedCount || 0
          this.$message.success(`变更成功，影响 ${updatedCount} 条物料`)
          this.changeSupplierDialogVisible = false
          this.getMainData()
          return
        }
        this.$message.error((data && data.msg) || '变更失败')
      }).catch(error => {
        this.$message.error('变更失败: ' + error.message)
      }).finally(() => {
        this.changeSupplierLoading = false
      })
    },
    startFormalApprove (row) {
      if (!row || !row.partNo) {
        this.$message.warning('未找到有效产品编码')
        return
      }
      // 新增物料阶段手动发起转正审批 - rqrq
      this.$confirm('确认发起该物料的转正流程吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let inData = {
          site: this.$store.state.user.site,
          partNo: row.partNo
        }
        startPartFormalApprove(inData).then(({ data }) => {
          if (data && data.code === 0) {
            this.$message.success(data.msg || '操作成功')
            this.getMainData()
            return
          }
          this.$message.error((data && data.msg) || '发起转正失败')
        }).catch(error => {
          this.$message.error('发起转正失败: ' + error.message)
        })
      }).catch(() => {})
    },
    fetchPartFamilyOptions (familyType, parentPartFamily) {
      return listPartFamilyByType({
        site: this.$store.state.user.site,
        familyType,
        parentPartFamily: parentPartFamily || '',
        active: 'Y'
      }).then(({ data }) => {
        if (data && data.code === 0) {
          return data.list || []
        }
        return []
      }).catch(() => [])
    },
    loadSearchCategoryLevel1 () {
      this.fetchPartFamilyOptions('level1').then(list => {
        this.searchCategoryLevel1Options = list
      })
    },
    onSearchCategoryChange () {
      this.searchData.categoryLevel2 = ''
      this.searchData.categoryLevel3 = ''
      this.searchCategoryLevel2Options = []
      this.searchCategoryLevel3Options = []
      if (!this.searchData.category) return
      this.fetchPartFamilyOptions('level2', this.searchData.category).then(list => {
        this.searchCategoryLevel2Options = list
      })
    },
    onSearchCategoryLevel2Change () {
      this.searchData.categoryLevel3 = ''
      this.searchCategoryLevel3Options = []
      if (!this.searchData.categoryLevel2) return
      this.fetchPartFamilyOptions('level3', this.searchData.categoryLevel2).then(list => {
        this.searchCategoryLevel3Options = list
      })
    },
    loadPartCategoryLevel1 () {
      return this.fetchPartFamilyOptions('level1').then(list => {
        this.categoryLevel1Options = list
      })
    },
    loadPartCategoryLevel2 (keepValues) {
      if (!this.currentpart.category) {
        this.categoryLevel2Options = []
        if (!keepValues) {
          this.currentpart.categoryLevel2 = ''
          this.currentpart.categoryLevel3 = ''
          this.categoryLevel3Options = []
        }
        return Promise.resolve()
      }
      return this.fetchPartFamilyOptions('level2', this.currentpart.category).then(list => {
        this.categoryLevel2Options = list
        if (!keepValues) {
          this.currentpart.categoryLevel2 = ''
          this.currentpart.categoryLevel3 = ''
          this.categoryLevel3Options = []
        }
      })
    },
    loadPartCategoryLevel3 (keepValues) {
      if (!this.currentpart.categoryLevel2) {
        this.categoryLevel3Options = []
        if (!keepValues) {
          this.currentpart.categoryLevel3 = ''
        }
        return Promise.resolve()
      }
      return this.fetchPartFamilyOptions('level3', this.currentpart.categoryLevel2).then(list => {
        this.categoryLevel3Options = list
        if (!keepValues) {
          this.currentpart.categoryLevel3 = ''
        }
      })
    },
    onPartCategoryChange () {
      this.loadPartCategoryLevel2(false)
    },
    onPartCategoryLevel2Change () {
      this.loadPartCategoryLevel3(false)
    },
    initPartCategoryOptions (keepValues) {
      return this.loadPartCategoryLevel1().then(() => {
        return this.loadPartCategoryLevel2(keepValues).then(() => {
          return this.loadPartCategoryLevel3(keepValues)
        })
      })
    },
    getBaseList (val, type, scene) {
      this.tagNo = val
      this.basePickScene = scene || ''
      this.$nextTick(() => {
        let strVal = ''
        if (this.tagNo === 510) {
          strVal = this.currentpart.unit
        }
        if (val === 529) {
          strVal = this.currentpart.buyerName
        }
        if (val === 528) {
          strVal = this.currentpart.sourcingName
        }

        if (val === 527) {
          strVal = this.currentpart.codeNo
        }
        if (val === 520) {
          strVal = this.currentpart.defaultSupplierNo
        }
        if (val === 520 && this.basePickScene === 'changeSupplier') {
          strVal = this.changeSupplierForm.targetSupplierNo
        }

        this.$refs.baseList.init(val, strVal?strVal:'')
      })
    },

    /* 列表方法的回调 */
    getBaseData (val) {
      if (this.tagNo === 510) {
        this.currentpart.unit = val.UMID
      }
      if (this.tagNo === 529) {
        this.currentpart.buyerName = val.UserName
      }
      if (this.tagNo === 528) {
        this.currentpart.sourcingName = val.UserName
      }

      if (this.tagNo === 527) {
        this.currentpart.codeNo = val.code_no
      }
      if (this.tagNo === 520) {
        this.currentpart.defaultSupplierNo = val.supplier_no || ''
      }
      if (this.tagNo === 520 && this.basePickScene === 'changeSupplier') {
        const supplierNo = val.supplier_no || ''
        const supplierName = val.supplier_name || ''
        this.changeSupplierForm.targetSupplierNo = (supplierNo || '').trim().toUpperCase()
        this.changeSupplierForm.targetSupplierName = supplierName || ''
      }
      this.basePickScene = ''
    },

    getMainData () {
      this.searchData.limit = this.pageSize
      this.searchData.page = this.pageIndex
      searchPartList(this.searchData).then(({data}) => {
        if (data.code === 0) {
        // 处理列表数据，确保可以正确显示嵌套属性
          this.mainDataList = data.page.list.map(item => {
            // 方式1：将嵌套属性提取到顶层
            if (item.flowNodeInstanceData) {
              item.departmentName = item.flowNodeInstanceData.departmentName;
              item.assigneeName = item.flowNodeInstanceData.assigneeName;

            } else {
              item.departmentName = '';
              item.assigneeName = '';

            }
            return item;
          });


          // this.mainDataList = data.page.list
          this.pageIndex = data.page.currPage
          this.pageSize = data.page.pageSize
          this.totalPage = data.page.totalCount
          // 判断是否全部存在数据
          if (this.mainDataList.length > 0) {
            // 设置选中行
            this.$refs.mainTable.setCurrentRow(this.mainDataList[0])
            this.changeData(this.mainDataList[0])
          } else {
            this.changeData(null)
          }
        }
        this.dataListLoading = false
      })
    },

    tabClick (tab, event) {
      this.refreshCurrentTabTable()
    },

    // 每页数
    sizeChangeHandle (val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getMainData()
    },

    // 当前页
    currentChangeHandle (val) {
      this.pageIndex = val
      this.getMainData()
    },

    changeData (row) {
      this.currentRow = JSON.parse(JSON.stringify(row))
      this.refreshCurrentTabTable()
    },

    refreshCurrentTabTable () {
      if (this.currentRow === '' || this.currentRow === null) {
        this.currentRow = {site: '', partNo: ''}
      }
      if (this.activeName === 'basicInfo') {
        this.refreshBasicInfo()
      }
      if (this.activeName === 'specParams') {
        this.refreshSpecParams()
      }
      if (this.activeName === 'suppliers') {
        this.refreshSuppliers()
      }
      if (this.activeName === 'approval') {
        this.refreshApproval()
      }
      if (this.activeName === 'attachments') {
        this.refreshAttachments()
      }
    },

    async exportExcel () {
      this.searchData.limit = -1
      this.searchData.page = 1
      excel.exportTable({
        url: '/part/searchPartList',
        columnMapping: this.columnArray1,
        mergeSetting: [],
        params: this.searchData,
        fileName: this.exportName + '.xlsx',
        rowFetcher: res => res.data,
        columnFormatter: [
          { columnProp: 'partStage', formatter: (val) => this.formatPartStageDesc(val) }
        ],
        dropColumns: []
      })
    },

    refreshBasicInfo () {
      let inData = {
        site: this.currentRow.site,
        partNo: this.currentRow.partNo,
        partDesc: this.currentRow.partDesc,
        height: this.getBasicTabHeight()
      }
      this.$refs.basicInfo.init(inData)
    },

    refreshSpecParams () {
      let inData = {
        site: this.currentRow.site,
        partNo: this.currentRow.partNo,
        codeNo: this.currentRow.codeNo,
        functionType:"P",
        height: this.getDetailTabHeight(70)
      }
      this.$refs.specParams.init(inData)
    },

    refreshSuppliers () {
      let inData = {
        site: this.currentRow.site,
        partNo: this.currentRow.partNo,
        height: this.getDetailTabHeight(90)
      }
      this.$refs.suppliers.init(inData)
    },

    refreshApproval () {
      let inData = {
        site: this.currentRow.site,
        orderRef1: this.currentRow.partNo,
        orderType: '产品资料',
        height: this.getDetailTabHeight(30)
      }
      this.$refs.approval.init(inData)
    },

    refreshAttachments () {
      let inData = {
        orderRef1: this.currentRow.site,
        orderRef2: this.currentRow.partNo,
        orderRef3: this.currentRow.partDesc,
        orderReftype: 'part',
        height: this.getDetailTabHeight(90)
      }
      this.$refs.attachments.init(inData)
    },

    // 新增产品
    addPart() {
      this.isAdd = true
      this.currentpart = {
        partNo: '',
        basePartNo: '',
        partSuffix: '',
        npc: '',
        partDesc: '',
        partSpec: '',
        sku: '',
        item: '',
        defaultSupplierNo: '',
        buyerName: '',
        sourcingName: '',
        category: '',
        categoryLevel2: '',
        categoryLevel3: '',
        unit: '',
        status: 'Y',
        codeNo: '',
        createBy: this.$store.state.user.name,
        remark: '',
        site: this.$store.state.user.site,
      }
      this.categoryLevel2Options = []
      this.categoryLevel3Options = []
      this.loadPartCategoryLevel1()
      this.partDialogVisible = true
    },

    // 编辑产品
    editPart(row) {
      if (!row) {
        this.$message.warning('请选择一个产品修改')
        return
      }
      this.isAdd = false
      this.currentpart = {...row}
      // 编辑时基准料号以原值为准，空值保持为空 - rqrq
      this.currentpart.partSuffix = this.extractPartSuffix(this.currentpart.partNo)
      this.initPartCategoryOptions(true).then(() => {
        this.partDialogVisible = true
      })
    },

    // 新增后自动刷新属性模板 - rqrq
    autoRefreshPartPropertiesAfterCreate () {
      const site = (this.$store.state.user.site || '').trim().toUpperCase()
      const partNo = (this.currentpart.partNo || '').trim().toUpperCase()
      const codeNo = (this.currentpart.codeNo || '').trim().toUpperCase()
      if (!site || !partNo || !codeNo) {
        return Promise.resolve(false)
      }
      // 新增料号成功后自动刷新属性模板，提前生成属性 - rqrq
      return refreshPartPropertiesModal({
        site,
        partNo,
        codeNo,
        recordType: 'P'
      }).then(({ data }) => {
        if (data && data.code === 0) {
          return true
        }
        this.$message.warning((data && data.msg) || '刷新属性模板失败')
        return false
      }).catch(error => {
        this.$message.warning('刷新属性模板失败: ' + (error.message || error))
        return false
      })
    },
    // 保存产品
    savePart() {
      if (this.isAdd) {
        const basePartNo = (this.currentpart.basePartNo || '').trim().toUpperCase()
        const partSuffix = (this.currentpart.partSuffix || '').trim().toUpperCase()
        if (!basePartNo || !partSuffix) {
          this.$message.warning('请填写基准料号和物料后缀')
          return
        }
        if (partSuffix.includes('-')) {
          this.$message.warning('物料后缀不能包含 "-"')
          return
        }
        if (!(this.currentpart.defaultSupplierNo || '').trim()) {
          this.$message.warning('请填写默认供应商')
          return
        }
        this.currentpart.defaultSupplierNo = (this.currentpart.defaultSupplierNo || '').trim().toUpperCase()
        this.currentpart.basePartNo = basePartNo
        this.currentpart.partSuffix = partSuffix
        this.currentpart.partNo = this.generatePartNo(basePartNo, partSuffix)
      }
      this.$refs.partForm.validate((valid) => {
        if (valid) {
          const apiCall = this.isAdd ? createPart(this.currentpart) : updatePart(this.currentpart)

          apiCall.then(({data}) => {
            if (data && data.code === 0) {
              const finishSave = (refreshOk) => {
                const successMsg = this.isAdd
                  ? (refreshOk ? '新增产品成功，已刷新属性模板' : '新增产品成功')
                  : '修改产品成功'
                this.$message.success(successMsg)
                this.partDialogVisible = false
                this.getMainData()
              }
              // 新增后自动执行“刷新属性模板”按钮同等逻辑 - rqrq
              if (this.isAdd) {
                this.autoRefreshPartPropertiesAfterCreate().then((refreshOk) => {
                  finishSave(refreshOk)
                })
                return
              }
              finishSave(false)
            } else {
              this.$message.error(data.msg || '操作失败')
            }
          }).catch(error => {
            this.$message.error('操作失败: ' + error.message)
          })
        } else {
          this.$message.warning('请填写必填字段')
        }
      })
    },

    // 删除产品
    deletePart(row) {
      this.$confirm('你确定删除该产品?', '确认删除', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deletePart({
          id: row.id,
          site: row.site,
          partNo: row.partNo
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.$message.success('产品删除成功')
            this.getMainData()
          } else {
            this.$message.error(data.msg || '删除失败')
          }
        }).catch(error => {
          this.$message.error('删除失败: ' + error.message)
        })
      })
    }
     // 打开审批对话框
    // openApproveDialog(row) {
    //   this.approveData = {
    //     applyNo: row.flowNodeInstanceData.applyNo,
    //     site: row.flowNodeInstanceData.site,
    //     orderType: row.flowNodeInstanceData.orderType,
    //     flowCode: row.flowNodeInstanceData.flowCode,
    //     flowVersion: row.flowNodeInstanceData.flowVersion,
    //     nodeCode: row.flowNodeInstanceData.nodeCode,
    //     comment: ''

    //   }
    //   this.approveDialogVisible = true
    // },
    // 提交审批
    // submitApprove(action) {
    //   if (action === 'REJECTED' && !this.approveData.comment) {
    //     this.$message.warning('驳回时必须填写审批意见')
    //     return
    //   }
    //   this.approveLoading = true
    //   approveNodeInstance({
    //     applyNo: this.approveData.applyNo,
    //     nodeCode: this.approveData.nodeCode,
    //     site: this.approveData.site,
    //     orderType: this.approveData.orderType,
    //     specialRelease: this.approveData.specialRelease,
    //     action: action,
    //     comment: this.approveData.comment
    //   }).then(({ data }) => {
    //     if (data && data.code === 0) {
    //       this.$message.success(action === 'APPROVED' ? '审批通过成功' : '驳回成功')
    //       this.approveDialogVisible = false
    //       //刷新列表
    //       this.getMainData()
    //     } else {
    //       this.$message.error(data.msg || '操作失败')
    //     }
    //   }).finally(() => {
    //     this.approveLoading = false
    //   })
    // },

    // 重新审批 - rqrq
    //  handleRestart(row) {
    //   this.$confirm('确定要重新发起审批流程吗？', '提示', {
    //     confirmButtonText: '确定',
    //     cancelButtonText: '取消',
    //     type: 'warning'
    //   }).then(() => {
    //     restartFlowInstance({
    //       applyNo: row.applyNo,
    //       site: row.site,
    //       orderType: row.orderType
    //     }).then(({ data }) => {
    //       if (data && data.code === 0) {
    //         this.$message.success('重新审批成功')
    //         this.getMainData()
    //       } else {
    //         this.$message.error(data.msg || '操作失败')
    //       }
    //     })
    //   }).catch(() => {})
    // }

  }

}
</script>

<!--当前页面的标签样式-->
<style scoped lang="scss">

/deep/ .customer-tab .el-tabs__content {
  padding: 5px !important;
}

/* 产品对话框整体样式 */
.part-dialog {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

.part-dialog .el-dialog {
  margin-top: 5vh !important;
  margin-bottom: 5vh !important;
}

.part-dialog .el-dialog__header {
  padding: 20px 25px 15px 25px;
  border-bottom: 1px solid #E4E7ED;
}

.part-dialog .el-dialog__body {
  padding: 25px 25px 25px 25px;
  max-height: 75vh;
  overflow-y: auto;
  min-height: 400px;
}

.dialog-content {
  width: 100%;
}

/* 产品表单样式 */
.part-form {
  width: 100%;
}

.part-form .el-form-item {
  margin-bottom: 1px;
}

.part-form .el-form-item__label {
  font-weight: 500;
  color: #303133;
  line-height: 32px;
  padding-right: 12px;
}

.part-form .el-form-item__content {
  line-height: normal;
}

/* 表单分组样式 */
.form-section {
  margin-bottom: 5px;
}

.form-section:last-child {
  margin-bottom: 5px;
}

/* 输入框样式 */
.part-form .el-input,
.part-form .el-textarea,
.part-form .el-date-editor {
  width: 100%;
}

/* 文本域样式优化 */
.part-form .el-textarea__inner {
  resize: none;
  font-family: inherit;
  line-height: 1.5;
}

/* 对话框底部按钮居中 */
.dialog-footer-center {
  text-align: center;
  padding: 15px 0 5px 0;
  border-top: 1px solid #E4E7ED;
  margin-top: 15px;
}

.dialog-footer-center .el-button {
  margin: 0 10px;
  min-width: 90px;
  height: 36px;
  padding: 0 20px;
  font-size: 14px;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .part-dialog {
    width: 95% !important;
  }

  .part-dialog .el-dialog__body {
    padding: 20px 20px 15px 20px;
  }
}

@media (max-width: 768px) {
  .part-form .el-col {
    margin-bottom: 20px;
  }

  .form-section {
    margin-bottom: 35px;
  }

  .part-form .el-form-item__label {
    line-height: 28px;
    height: 28px;
  }
}
</style>
