<template>
  <j-modal
    :title="title"
    :width="width"
    :visible="visible"
    :confirmLoading="confirmLoading"
    v-bind:prefixNo="prefixNo"
    fullscreen
    switchHelp
    switchFullscreen
    @cancel="handleCancel"
    :id="prefixNo"
    :style="modalStyle"
  >
    <template slot="footer">
      <a-button key="back" @click="handleCancel">取消</a-button>
      <a-button type="primary" v-if="showOkFlag" :loading="confirmLoading" @click="handleOk">保存（Ctrl+S）</a-button>
    </template>
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-tabs default-active-key="1" size="small" v-model="activeKey">
          <a-tab-pane key="1" tab="基本信息" id="materialHeadModal" forceRender>
            <a-row class="form-row" :gutter="24" type="flex">
              <a-col :xl="6" :lg="8" :md="12" :sm="24">
                <a-form-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="名称"
                  data-step="1"
                  data-title="名称"
                  data-intro="名称必填，可以重复"
                >
                  <a-input
                    placeholder="请输入名称"
                    v-decorator.trim="['name', validatorRules.name]"
                    @change="handleNameChange"
                  />
                </a-form-item>
              </a-col>
              <a-col :xl="6" :lg="8" :md="12" :sm="24">
                <a-form-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="品牌"
                  data-step="2"
                  data-title="品牌"
                  data-intro="请填写商品的品牌，方便区别不同品牌的商品"
                >
                  <a-input placeholder="请输入品牌" v-decorator.trim="['brand']" />
                </a-form-item>
              </a-col>
              <a-col :xl="6" :lg="8" :md="12" :sm="24">
                <a-form-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="助记码"
                  data-step="3"
                  data-title="助记码"
                  data-intro="助记码自动生成，助记码是商品名称的首字母缩写"
                >
                  <a-input placeholder="" v-decorator.trim="['mnemonic']" :readOnly="true" />
                </a-form-item>
              </a-col>
              <a-col :xl="6" :lg="8" :md="12" :sm="24">
                <a-form-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="类别"
                  data-step="4"
                  data-title="类别"
                  data-intro="类别需要在【商品类别】页面进行录入，录入之后在此处进行调用"
                >
                  <a-tree-select
                    style="width: 100%"
                    :dropdownStyle="{ maxHeight: '200px', overflow: 'auto' }"
                    allow-clear
                    :treeData="categoryTree"
                    v-decorator="['categoryId', validatorRules.categoryId]"
                    placeholder="请选择类别"
                  >
                  </a-tree-select>
                </a-form-item>
              </a-col>
              <a-col :xl="6" :lg="8" :md="12" :sm="24">
                <a-form-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="序列号"
                  data-step="5"
                  data-title="序列号"
                  data-intro="此处是商品的序列号开关，如果选择了有，则在采购入库单据需要录入该商品的序列号，在销售出库单据需要选择该商品的序列号进行出库"
                >
                  <a-tooltip title="如果选择为有，则在采购入库单需要录入该商品的序列号">
                    <a-select placeholder="有无序列号" v-decorator="['enableSerialNumber']">
                      <a-select-option value="1">有</a-select-option>
                      <a-select-option value="0">无</a-select-option>
                    </a-select>
                  </a-tooltip>
                </a-form-item>
              </a-col>
              <a-col :xl="6" :lg="8" :md="12" :sm="24">
                <a-form-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="系统SPU"
                  data-step="6"
                  data-title="系统SPU"
                  data-intro="系统SPU"
                >
                  <a-input placeholder="提交后自动生成" disabled v-decorator="['systemSpu']" />
                </a-form-item>
              </a-col>
              <a-col :xl="6" :lg="8" :md="12" :sm="24">
                <a-form-item
                  :labelCol="{
                    xs: { span: 24 },
                    sm: { span: 10 },
                  }"
                  :wrapperCol="{
                    xs: { span: 24 },
                    sm: { span: 14 },
                  }"
                  label="无动销提醒周期"
                  data-step="7"
                  data-title="无动销提醒周期"
                  data-intro="无动销提醒周期"
                >
                  <a-tooltip title="无动销提醒周期">
                    <a-select placeholder="无动销提醒周期" v-decorator="['movingPinReminderCycle']">
                      <a-select-option value="7">一周</a-select-option>
                      <a-select-option value="14">两周</a-select-option>
                      <a-select-option value="30">一个月</a-select-option>
                      <a-select-option value="90">一季度</a-select-option>
                    </a-select>
                  </a-tooltip>
                </a-form-item>
              </a-col>
              <a-col :xl="6" :lg="8" :md="12" :sm="24">
                <a-form-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="保质期（天）"
                  data-step="8"
                  data-title="保质期（天）"
                  data-intro="保质期（天）"
                >
                  <a-input-number :min="0" v-decorator="['expiryNum']" style="width: 100%;" placeholder="请输入保质期（天）" />
                </a-form-item>
              </a-col>
              <a-col :xl="6" :lg="8" :md="12" :sm="24">
                <a-form-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="默认采购价"
                  data-step="9"
                  data-title="默认采购价"
                  data-intro="默认采购价"
                > 
                  <a-input @blur="$refs.meTable.$forceUpdate()" v-decorator="['defaultPurchaseDecimal',validatorRules.defaultPurchaseDecimal]" style="width: 100%" placeholder="请输入默认采购价" />
                </a-form-item>
              </a-col>
              <a-col :xl="6" :lg="8" :md="12" :sm="24">
                <a-form-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="默认销售价"
                  data-step="10"
                  data-title="默认销售价"
                  data-intro="默认销售价"
                >
                  <a-input @blur="$refs.meTable.$forceUpdate()" v-decorator="['defaultWholesaleDecimal',validatorRules.defaultWholesaleDecimal]" style="width: 100%;" placeholder="请输入默认销售价" />
                </a-form-item>
              </a-col>
            </a-row>
            <div style="margin-top: 8px" id="materialDetailModal">
              <a-table
                ref="meTable"
                size="middle"
                rowKey="id"
                :loading="meTable.loading"
                :columns="meTable.columns"
                :dataSource="meTable.dataSource"
                :pagination="meTable.pagination"
                :scroll="meTable.scroll"
                bordered
                @change="handleMeTableChange"
              >
                <template slot="supplierId" slot-scope="text, record">
                  {{ formatSupplierName(record.supplierId) }}
                </template>
                <template slot="depotId" slot-scope="text, record">
                  {{ formatDepotName(record.depotId) }}
                </template>
                <template slot="purchaseDecimal" slot-scope="text, record">
                  {{ record.purchaseDecimal }}
                  <a-tooltip slot="suffix" title="采购价和默认采购价不一致">
                    <a-icon type="info-circle" style="color: #f5222d" v-show="record.purchaseDecimal!=form.getFieldValue('defaultPurchaseDecimal')" />
                  </a-tooltip>
                </template>
                <template slot="wholesaleDecimal" slot-scope="text, record">
                  {{ record.wholesaleDecimal }}
                  <a-tooltip slot="suffix" title="销售价和默认销售价不一致">
                    <a-icon type="info-circle" style="color: #f5222d" v-show="record.wholesaleDecimal!=form.getFieldValue('defaultWholesaleDecimal')" />
                  </a-tooltip>
                </template>
              </a-table>
            </div>
            <a-row class="form-row" :gutter="24" type="flex">
              <a-col :lg="24" :md="24" :sm="24">
                <a-form-item :labelCol="labelCol" :wrapperCol="{ xs: { span: 24 }, sm: { span: 24 } }" label="">
                  <a-textarea :rows="1" placeholder="请输入备注" v-decorator="['remark']" style="margin-top: 8px" />
                </a-form-item>
              </a-col>
            </a-row>
          </a-tab-pane>
          <a-tab-pane key="2" tab="商品SKU" forceRender>
            <j-editable-table
              ref="editableProBarCodeTable"
              :loading="mbTable.loading"
              :columns="mbTable.columns"
              :dataSource="mbTable.dataSource"
              :height="300"
              minWidth="100%"
              :maxHeight="300"
              :rowNumber="false"
              :rowSelection="true"
              :actionButton="true"
              @added="handleMbTableAdded"
            >
            <template #commodityUnit="{value,index,allValues,rowId}">
              <div style="display: flex;align-items: center;">
                <a-input disabled :value="value" placeholder="自动带出">
                </a-input>
                <span class="sp-btn" @click="editMaterialUnitModal({value,index,allValues,rowId})">+管理</span>
              </div>
            </template>
            <template #upcList="{value,rowId}">
              <div style="display: flex;align-items: center;">
                <a-input disabled :value="value[0]&&value[0].upc?value[0].upc:''" placeholder="自动带出">
                </a-input>
                <span class="sp-btn" @click="editMaterialUpcModal({value,rowId})">+管理</span>
              </div>
            </template>
            <template #enabled="{value,handleChange}">
              <a-switch :checked="value" @change="(v) => handleChange(v)" checkedChildren="启用" unCheckedChildren="禁用" />
            </template>
            </j-editable-table>
          </a-tab-pane>
          <a-tab-pane key="3" tab="扩展信息" forceRender>
            <a-row v-if="mpShort.otherField1.enabled" class="form-row" :gutter="24">
              <a-col :lg="6" :md="6" :sm="6">
                <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="mpShort.otherField1.name">
                  <a-input v-decorator.trim="['otherField1']" />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row v-if="mpShort.otherField2.enabled" class="form-row" :gutter="24">
              <a-col :lg="6" :md="6" :sm="6">
                <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="mpShort.otherField2.name">
                  <a-input v-decorator.trim="['otherField2']" />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row v-if="mpShort.otherField3.enabled" class="form-row" :gutter="24">
              <a-col :lg="6" :md="6" :sm="6">
                <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="mpShort.otherField3.name">
                  <a-input v-decorator.trim="['otherField3']" />
                </a-form-item>
              </a-col>
            </a-row>
          </a-tab-pane>
          <a-tab-pane key="4" tab="库存数量" forceRender>
            <j-editable-table
              ref="editableDepotTable"
              :loading="depotTable.loading"
              :columns="depotTable.columns"
              :dataSource="depotTable.dataSource"
              minWidth="100%"
              :maxHeight="300"
              :rowNumber="true"
              :rowSelection="false"
              :actionButton="false"
            >
              <template #buttonAfter>
                <a-button style="margin: 0px 0px 8px 0px" @click="batchSetStock('lowSafeStock')">最低安全库存-批量</a-button>
                <a-button style="margin-left: 8px" @click="batchSetStock('highSafeStock')">最高安全库存-批量</a-button>
              </template>
            </j-editable-table>
            <!-- 表单区域 -->
            <batch-set-stock-modal ref="stockModalForm" @ok="batchSetStockModalFormOk"></batch-set-stock-modal>
          </a-tab-pane>
          <a-tab-pane key="5" tab="图片信息" forceRender>
            <a-row class="form-row" :gutter="24" style="padding-top: 20px">
              <a-col :lg="18" :md="18" :sm="24">
                <a-form-item
                  :labelCol="{ xs: { span: 24 }, sm: { span: 3 } }"
                  :wrapperCol="{ xs: { span: 24 }, sm: { span: 20 } }"
                  label="图片信息"
                >
                  <j-image-upload v-model="fileList" bizPath="material" text="上传" isMultiple></j-image-upload>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24"></a-col>
            </a-row>
            <a-row class="form-row" :gutter="24">
              <a-col :lg="18" :md="18" :sm="24">
                <a-form-item
                  :labelCol="{ xs: { span: 24 }, sm: { span: 3 } }"
                  :wrapperCol="{ xs: { span: 24 }, sm: { span: 20 } }"
                  label="上传提示"
                >
                  图片最多4张，且单张大小不超过1M
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24"></a-col>
            </a-row>
          </a-tab-pane>
        </a-tabs>
      </a-form>
    </a-spin>
    <!-- 货品单位管理 -->
    <material-unit-modal ref="materialUnitModal" @ok="unitOk"></material-unit-modal>
    <material-upc-modal ref="materialUpcModal" @ok="upcOk"></material-upc-modal>
  </j-modal>
</template>
<script>
import pick from 'lodash.pick'
import BatchSetPriceModal from './BatchSetPriceModal'
import BatchSetStockModal from './BatchSetStockModal'
import MaterialUnitModal from './MaterialUnitModal'
import MaterialUpcModal from './MaterialUpcModal'
import JEditableTable from '@/components/jeecg/JEditableTable'
import { FormTypes, getRefPromise, VALIDATE_NO_PASSED, validateFormAndTables } from '@/utils/JEditableTableUtil'
import {
  queryMaterialCategoryTreeList,
  changeNameToPinYin,
} from '@/api/api'
import {  autoJumpNextInput, handleIntroJs } from '@/utils/util'
import { getAction, httpAction } from '@/api/manage'
import JImageUpload from '@/components/jeecg/JImageUpload'
import JDate from '@/components/jeecg/JDate'
import Vue from 'vue'
import { MaterialModalMixins } from '../mixins/MaterialModalMixins'
import { mixinDevice } from '@/utils/mixin.js'

export default {
  name: 'MaterialModal',
  mixins: [MaterialModalMixins,mixinDevice],
  components: {
    BatchSetPriceModal,
    BatchSetStockModal,
    MaterialUnitModal,
    MaterialUpcModal,
    JImageUpload,
    JDate,
    JEditableTable,
    VNodes: {
      functional: true,
      render: (h, ctx) => ctx.props.vnodes,
    },
  },
  data() {
    return {
      title: '操作',
      width: '1300px',
      visible: false,
      activeKey: '1',
      modalStyle: '',
      categoryTree: [],
      unitList: [],
      depotList: [],
      fileList: [],
      meDeleteIdList: [], //删除条码信息的id数组
      prefixNo: 'material',
      model: {},
      showOkFlag: true,
      setTimeFlag: null,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      mpShort: {
        mfrs: {},
        otherField1: {},
        otherField2: {},
        otherField3: {},
      },
      meTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '批次号',
            dataIndex: 'batchNumber',
          },
          {
            title: 'SKU',
            dataIndex: 'sku',
          },
          {
            title: '单位',
            dataIndex: 'commodityUnit',
          },
          {
            title: '采购价',
            dataIndex: 'purchaseDecimal',
            scopedSlots: { customRender: 'purchaseDecimal' } 
          },
          {
            title: '销售价',
            dataIndex: 'wholesaleDecimal',
            scopedSlots: { customRender: 'wholesaleDecimal' } 
          },
          {
            title: '生产日期',
            dataIndex: 'productionDate',
          },
          {
            title: '供应商',
            dataIndex: 'supplierId',
            scopedSlots: { customRender: 'supplierId' } 
          },
          {
            title: '库存（最小单位）',
            dataIndex: 'inventory',
          },
          {
            title: '仓库名称',
            dataIndex: 'depotId',
            scopedSlots: { customRender: 'depotId' } 
          },
          {
            title: '库位',
            dataIndex: 'position',
          },
        ],
        pagination: {
          current: 1,
          pageSize: 10,
          pageSizeOptions: ['10', '20', '30', '50', '100'],
          showTotal: (total, range) => {
            return range[0] + '-' + range[1] + ' 共' + total + '条'
          },
          showQuickJumper: true,
          showSizeChanger: true,
          total: 0,
        },
        scroll: {}
      },
      mbTable:{
        loading: false,
        dataSource: [],
        columns: [
          {
            title: 'SKU',
            key: 'sku',
            width: '250px',
            disabled: true,
            type: FormTypes.input,
            placeholder: '自动生成',
          },
          {
            title: '单位',
            key: 'commodityUnit',
            width: '140px',
            type: FormTypes.slot,
            disabled: true,
            placeholder: '请输入${title}',
            validateRules: [{ required: true, message: '单位不能为空' }],
          },
          {
            title: '规格',
            key: 'standard',
            width: '100px',
            type: FormTypes.input,
            placeholder: '请输入${title}',
            validateRules: [{ required: true, message: '规格不能为空' }],
          },
          {
            title: '颜色',
            key: 'color',
            width: '100px',
            type: FormTypes.input,
            placeholder: '请输入${title}',
          },
          {
            title: '重量(kg)',
            key: 'weight',
            width: '100px',
            type: FormTypes.inputNumber,
            placeholder: '请输入重量',
          },
          {
            title: '型号',
            key: 'model',
            width: '100px',
            type: FormTypes.input,
            placeholder: '请输入${title}',
          },
          {
            title: 'UPC',
            key: 'upcList',
            width: '180px',
            type: FormTypes.slot,
            placeholder: '请输入${title}',
          },
          {
            title: '是否启用',
            key: 'enabled',
            width: '100px',
            type: FormTypes.slot,
            placeholder: '请输入${title}',
          },
          {
            title: '单位集合',
            key: 'unitList',
            width: '100px',
            type: FormTypes.hidden,
          },
        ]
      },
      depotTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '仓库',
            key: 'name',
            width: '15%',
            type: FormTypes.normal,
          },
          {
            title: '期初库存',
            key: 'number',
            width: '15%',
            type: FormTypes.inputNumber,
            defaultValue: '',
            placeholder: '请输入${title}',
          },
          {
            title: '库存总数量',
            key: 'currentStock',
            width: '15%',
            type: FormTypes.inputNumber,
            defaultValue: '',
            disabled: true,
            placeholder: '请输入${title}',
          },
          {
            title: '最低安全库存数量',
            key: 'lowSafeStock',
            width: '15%',
            type: FormTypes.inputNumber,
            defaultValue: '',
            placeholder: '请输入${title}',
          },
          {
            title: '最高安全库存数量',
            key: 'highSafeStock',
            width: '15%',
            type: FormTypes.inputNumber,
            defaultValue: '',
            placeholder: '请输入${title}',
          },
          {
            title: '仓位货架',
            key: 'position',
            width: '9%',
            type: FormTypes.input,
            defaultValue: '',
            placeholder: '请输入${title}',
          },
        ],
      },
      confirmLoading: false,
      form: this.$form.createForm(this),
      validatorRules: {
        name: {
          rules: [
            { required: true, message: '请输入名称!' },
            { max: 100, message: '长度请小于100个字符', trigger: 'blur' },
          ],
        },
        categoryId: {
          rules: [{ required: true, message: '请选择类别!' }],
        },
        defaultWholesaleDecimal: {
          rules: [{ required: true, message: '请输入默认销售价!' },{ pattern: /^(?:0|[1-9]\d*)(?:\.\d{1,4})?$/, message: '金额格式不正确!' }],
        },
        defaultPurchaseDecimal: {
          rules: [{ required: true, message: '请输入默认采购价!' },{ pattern: /^(?:0|[1-9]\d*)(?:\.\d{1,4})?$/, message: '金额格式不正确!' }],
        },
      },
      url: {
        add: '/material/add',
        edit: '/material/update',
        materialsExtendList: '/materialsExtend/getDetailList',
        depotWithStock: '/depot/getAllListWithStock',
        batchList: '/materialBatch/getDetailList',
      },
    }
  },
  created() {
    this.loadParseMaterialProperty()
    let realScreenWidth = window.screen.width
    this.width = realScreenWidth < 1500 ? '1200px' : '1400px'
    this.initSelectOpts()
  },
  mounted() {
    document.getElementById(this.prefixNo).addEventListener('keydown', this.handleOkKey)
  },
  beforeDestroy() {
    document.getElementById(this.prefixNo).removeEventListener('keydown', this.handleOkKey)
  },
  methods: {
    // 快捷键
    handleOkKey(e) {
      const key = window.event.keyCode ? window.event.keyCode : window.event.which
      if (key === 83 && e.ctrlKey) {
        //保存 CTRL+S
        this.handleOk()
        e.preventDefault()
      }
    },
    // 获取所有的editableTable实例
    getAllTable() {
      return Promise.all([getRefPromise(this, 'editableProBarCodeTable'),getRefPromise(this, 'editableDepotTable')])
    },
    handleMbTableAdded(e){
      const { row, target } = e
      target.setValues([{ rowKey: row.id, values: { enabled: true } }])
    },
    add() {
      // 默认新增一条数据
      this.getAllTable().then((editableTables) => {
        editableTables[0].add()
      })
      this.edit({})
      this.$nextTick(() => {
        handleIntroJs('material', 11)
      })
    },
    async edit(record) {
      this.form.resetFields()
      this.model = Object.assign({}, record)
      this.activeKey = '1'
      this.visible = true
      this.meDeleteIdList = []
      this.modalStyle = 'top:0;height: 95%;'
      if (JSON.stringify(record) === '{}') {
        this.fileList = []
      } else {
        setTimeout(() => {
          this.fileList = record.imgName
        }, 5)
      }
      this.$nextTick(() => {
        this.form.setFieldsValue(
          pick(
            this.model,
            'name',
            'brand',
            'mnemonic',
            'categoryId',
            'enableSerialNumber',
            'movingPinReminderCycle',
            'expiryNum',
            'defaultPurchaseDecimal',
            'defaultWholesaleDecimal',
            'systemSpu',
            'remark',
            'otherField1',
            'otherField2',
            'otherField3'
          )
        )
        autoJumpNextInput('materialHeadModal')
      })
      this.loadTreeData()
      this.loadUnitListData()
      // 加载子表数据
      if (this.model.id) {
        let params = { materialId: this.model.id }
        this.requestProMbTableData(this.url.materialsExtendList, params, this.mbTable)
        this.requestMeTableData()
        this.requestDepotTableData(this.url.depotWithStock, { mId: this.model.id }, this.depotTable)
      } else {
        this.requestDepotTableData(this.url.depotWithStock, { mId: 0 }, this.depotTable)
      }
    },
    requestMeTableData(){
      const params = {
        materialId: this.model.id,
        currentPage: this.meTable.pagination.current,
        pageSize: this.meTable.pagination.pageSize,
      }
      this.meTable.loading = true
      getAction(this.url.batchList, params)
        .then((res) => {
          this.meTable.dataSource = res.data.rows
          this.meTable.pagination.total = Number(res.data.total)
        })
        .finally(() => {
          this.meTable.loading = false
        })
    },
    /** 查询条码tab的数据 */
    requestProMbTableData(url, params, tab) {
      tab.loading = true
      getAction(url, params)
        .then((res) => {
          tab.dataSource = res.data
          console.log('tab.dataSource-----', tab.dataSource)
        })
        .finally(() => {
          tab.loading = false
        })
    },
    /** 查询仓库tab的数据 */
    requestDepotTableData(url, params, tab) {
      tab.loading = true
      getAction(url, params)
        .then((res) => {
          tab.dataSource = (res.data || []).map(item => {
            item.number = item.initStock
            return item
          })
          console.log('====================', res.data)
        })
        .finally(() => {
          tab.loading = false
        })
    },
    close() {
      this.$emit('close')
      this.visible = false
      this.modalStyle = ''
      this.meTable.dataSource = []
      this.meTable.pagination.current = 1
      this.getAllTable().then((editableTables) => {
        editableTables[0].initialize()
        editableTables[1].initialize()
      })
    },
    handleOk() {
      this.validateFields()
    },
    handleCancel() {
      this.close()
    },
    /** 触发表单验证 */
    validateFields() {
      this.getAllTable()
        .then((tables) => {
          console.log('tables========', tables)
          /** 一次性验证主表和所有的次表 */
          return validateFormAndTables(this.form, tables)
        })
        .then((allValues) => {
          console.log('allValues========',allValues)
          let formData = this.classifyIntoFormData(allValues)
          // 发起请求
          return this.requestAddOrEdit(formData)
        })
        .catch((e) => {
          this.$message.warning('请完善必填项！')
          if (e.error === VALIDATE_NO_PASSED) {
            // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
            this.activeKey = e.index == null ? this.activeKey : (e.index + 2).toString()
          } else {
            console.error(e)
          }
        })
    },
    /** 整理成formData */
    classifyIntoFormData(allValues) {
      let materialMain = Object.assign(this.model, allValues.formValue)
      console.log('allValues.tablesValue[0].values',allValues.tablesValue[0].values)
      return {
        ...materialMain, // 展开
        stock: allValues.tablesValue[1].values,
        meList: allValues.tablesValue[0].values.map(item => {
          return {
            ...item,
            upcList: item.upcList?item.upcList:[],
            id: item.id.length > 19 ? null : item.id, // 后端接收不了大于19位id
          }
        }),
      }
    },
    /** 发起新增或修改的请求 */
    requestAddOrEdit(formData) {
      console.log('formData------------', formData)
      if (formData.meList.length === 0) {
        this.$message.warning('抱歉，必须填一条SKU信息！')
        return
      }
      //对最低和最高安全库存进行校验
      for (let i = 0; i < formData.stock.length; i++) {
        let depotStockObj = formData.stock[i]
        if (formData.enableSerialNumber === '1' && depotStockObj.initStock && depotStockObj.initStock - 0) {
          this.$message.warning('抱歉，序列号商品不能录入期初库存，建议进行入库单据录入！')
          return
        }
        if (formData.enableBatchNumber === '1' && depotStockObj.initStock && depotStockObj.initStock - 0) {
          this.$message.warning('抱歉，批号商品不能录入期初库存，建议进行入库单据录入！')
          return
        }
        if (depotStockObj.lowSafeStock && depotStockObj.highSafeStock) {
          if (depotStockObj.lowSafeStock - 0 > depotStockObj.highSafeStock - 0) {
            this.$message.warning('抱歉，' + depotStockObj.name + '的最低安全库存大于最高安全库存！')
            return
          }
        }
      }
      //图片校验
      if (this.fileList && this.fileList.length > 0) {
        formData.imgName = this.fileList
        let fileArr = this.fileList.split(',')
        if (fileArr.length > 4) {
          this.$message.warning('抱歉，商品图片不能超过4张！')
          return
        }
      } else {
        formData.imgName = ''
      }
      formData.meDeleteIdList = this.meDeleteIdList
      //接口调用
      let url = this.url.add,
        method = 'post'
      if (this.model.id) {
        url = this.url.edit
        method = 'put'
      }
      const that = this
      this.confirmLoading = true
      httpAction(url, formData, method)
        .then((res) => {
          if (res.code === 200) {
            that.$emit('ok')
            that.confirmLoading = false
            that.close()
          } else {
            that.$message.warning(res.data.message)
            that.confirmLoading = false
          }
        })
        .finally(() => {})
    },
    loadTreeData() {
      let that = this
      let params = {}
      params.id = ''
      queryMaterialCategoryTreeList(params).then((res) => {
        if (res) {
          that.categoryTree = []
          for (let i = 0; i < res.length; i++) {
            let temp = res[i]
            that.categoryTree.push(temp)
          }
        }
      })
    },
    loadUnitListData() {
      let that = this
      let params = {}
      getAction('/unit/getAllList', params).then((res) => {
        if (res) {
          that.unitList = res.data
        }
      })
    },
    batchSetStock(type) {
      this.$refs.stockModalForm.add(type)
      this.$refs.stockModalForm.disableSubmit = false
    },
    batchSetStockModalFormOk(stock, batchType) {
      let arr = this.depotTable.dataSource
      let depotTableData = []
      for (let i = 0; i < arr.length; i++) {
        let depotInfo = {
          name: arr[i].name,
          currentStock: arr[i].currentStock,
          lowSafeStock: arr[i].lowSafeStock,
          highSafeStock: arr[i].highSafeStock,
        }
        if (batchType === 'currentStock') {
          depotInfo.currentStock = stock - 0
        } else if (batchType === 'lowSafeStock') {
          depotInfo.lowSafeStock = stock - 0
        } else if (batchType === 'highSafeStock') {
          depotInfo.highSafeStock = stock - 0
        }
        if (arr[i].id) {
          depotInfo.id = arr[i].id
        }
        depotTableData.push(depotInfo)
      }
      this.depotTable.dataSource = depotTableData
    },
    loadParseMaterialProperty() {
      let mpList = Vue.ls.get('materialPropertyList')
      for (let i = 0; i < mpList.length; i++) {
        if (mpList[i].nativeName === '制造商') {
          this.mpShort.mfrs.name = mpList[i].anotherName
          this.mpShort.mfrs.enabled = mpList[i].enabled
        }
        if (mpList[i].nativeName === '自定义1') {
          this.mpShort.otherField1.name = mpList[i].anotherName
          this.mpShort.otherField1.enabled = mpList[i].enabled
        }
        if (mpList[i].nativeName === '自定义2') {
          this.mpShort.otherField2.name = mpList[i].anotherName
          this.mpShort.otherField2.enabled = mpList[i].enabled
        }
        if (mpList[i].nativeName === '自定义3') {
          this.mpShort.otherField3.name = mpList[i].anotherName
          this.mpShort.otherField3.enabled = mpList[i].enabled
        }
      }
    },
    handleNameChange(e) {
      let that = this
      if (e.target.value) {
        if (this.setTimeFlag != null) {
          clearTimeout(this.setTimeFlag)
        }
        this.setTimeFlag = setTimeout(() => {
          changeNameToPinYin({ name: e.target.value }).then((res) => {
            if (res && res.code === 200) {
              that.form.setFieldsValue({ mnemonic: res.data })
            } else {
              that.$message.warning(res.data)
            }
          })
        }, 500)
      } else {
        that.form.setFieldsValue({ mnemonic: '' })
      }
    },
    handleMeTableChange(pagination) {
      if (pagination && pagination.current) {
        this.meTable.pagination = pagination
      }
      this.requestMeTableData()
    },
    editMaterialUnitModal({value,index,allValues,rowId}){
      console.log('allValues====',allValues)
      console.log('value====',value)
      const obj = allValues.inputValues[index]
      let unitList = [
        {
          name: value,
          ratio: 1,
        }
      ]
      if(obj.unitList&& obj.unitList.length > 0){
        unitList = obj.unitList
      }
      this.$refs.materialUnitModal.edit({
        unitList,
        rowId: rowId,
      })
      this.$refs.materialUnitModal.unitOpts = this.unitList
    },
    editMaterialUpcModal({value,rowId}) {
      let upcList = [
        {
          upc: ''
        }
      ]
      if (value&&value.length > 0) {
        upcList = value
      }
      this.$refs.materialUpcModal.edit({
        upcList: upcList,
        rowId: rowId,
      })
    },
    upcOk({upcList,rowId}) {
      const target = this.$refs.editableProBarCodeTable
      target.setValues([{ rowKey: rowId, values: { upcList: upcList } }])
    },
    unitOk({unitList,rowId}) {
      const target = this.$refs.editableProBarCodeTable
      target.setValues([{ rowKey: rowId, values: { commodityUnit: unitList[0].name, unitList: unitList } }])
    },
  },
}
</script>
<style lang="less" scoped>
.input-table {
  max-width: 100%;
  min-width: 1200px;
}
.tag-info {
  font-size: 14px;
  height: 32px;
  line-height: 32px;
  width: 100%;
  padding: 0px 11px;
  color: #bbb;
  background-color: #ffffff;
}
/deep/ .ant-table td { white-space: nowrap; }
.sp-btn{
  display: inline-block;
  white-space: nowrap;
  box-sizing: border-box;
  padding: 0 5px;
  font-size: 12px;
  cursor: pointer;
  color: #1890FF;
}
</style>
