<template>
  <el-form ref="form" :model="form" :rules="rules">
    <ele-pro-table
      ref="table"
      :needPage="false"
      :columns="columns"
      :datasource="form.datasource"
      class="time-form"
      @columns-change="handleColumnChange"
      :cache-key="cacheKeyUrl"
      height="350"
      full-height="calc(100vh - 76px)"
      :show-summary="clientEnvironmentId == 4"
      :summary-method="getSummaries"
    >
      <!-- 表头工具栏 -->
      <template v-slot:toolbar>
        <div class="headbox">
          <el-button
            v-if="isShowAdd && needProduce != 4"
            size="small"
            type="primary"
            icon="el-icon-plus"
            class="ele-btn-icon"
            @click="handlAdd"
          >
            新增
          </el-button>
          <el-button
            size="small"
            type="primary"
            icon="el-icon-plus"
            class="ele-btn-icon"
            @click="handParent()"
            v-if="isShowAdd && needProduce == 4"
          >
            新增
          </el-button>
        </div>
      </template>
      <template v-slot:technicalDrawings="{ row, $index }">
        <el-form-item :prop="'datasource.' + $index + '.technicalDrawings'">
          <fileMain v-model="row.technicalDrawings" type="view"></fileMain>
        </el-form-item>
      </template>
      <template v-slot:remark="{ row, $index }">
        <el-form-item :prop="'datasource.' + $index + '.remark'">
          <el-input
            clearable
            v-model="row.remark"
            type="textarea"
            placeholder="请输入"
          />
        </el-form-item>
      </template>

      <template v-slot:packagingStrength="scope">
        <el-form-item>
          <DictSelection
            dict-name="包装强度"
            @change="keyChange(scope.$index, scope.row, 'packagingStrength')"
            v-model="scope.row.extField.packagingStrength"
            :isOne="scope.$index === 0"
          ></DictSelection>
        </el-form-item>
      </template>
      <template v-slot:packagingDensity="scope">
        <el-form-item>
          <DictSelection
            dict-name="包装密度"
            @change="keyChange(scope.$index, scope.row, 'packagingDensity')"
            v-model="scope.row.extField.packagingDensity"
            :isOne="scope.$index === 0"
          ></DictSelection>
        </el-form-item>
      </template>

      <template v-slot:batchStockId="scope">
        <el-form-item :prop="'datasource.' + scope.$index + '.batchStockId'">
          <!-- <el-input v-model="scope.row.batchNo" v-no-chinese></el-input> -->
          <el-select
            v-model="scope.row.batchStockId"
            clearable
            placeholder="请选择"
            @change="batchNoChange(scope.$index, scope.row)"
          >
            <el-option
              v-for="item in scope.row.batchNoList || []"
              :key="item.id"
              :label="item.batchNo"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </template>
      <!-- 生产编号 可编辑 -->
      <template v-slot:productionCodes="{ row }">
        <el-form-item>
          <el-input v-model="row.productionCodes" v-no-chinese></el-input>
        </el-form-item>
      </template>
      <template v-slot:blockCount="scope">
        <el-form-item
          :prop="'datasource.' + scope.$index + '.blockCount'"
          :rules="[{ required: true, message: '请输入', trigger: 'blur' }]"
        >
          <el-input
            v-model="scope.row.blockCount"
            @input="
              (val) => tableHandleKeyUp(scope.row, scope.$index, 'blockCount')
            "
          ></el-input>
        </el-form-item>
      </template>

      <template v-slot:receiveTotalWeight="scope">
        <el-form-item
          :prop="'datasource.' + scope.$index + '.receiveTotalWeight'"
        >
          <el-input
            type="number"
            v-model="scope.row.receiveTotalWeight"
            @input="changeSendTotalWeight(scope.row, scope.$index)"
            style="width: calc(100% - 70px); margin-right: 10px"
          >
            <template slot="append">
              {{ scope.row.weightUnit }}
            </template>
          </el-input>
          <el-button
            size="small"
            type="primary"
            v-if="entrustedCode"
            @click.native="(e) => handleInnerBound(e, scope.row, scope.$index)"
            >选择
          </el-button>
        </el-form-item>
      </template>
      <template v-slot:orderNo="scope">
        <el-form-item
          :prop="'datasource.' + scope.$index + '.orderNo'"
          :rules="[
            {
              required: false,
              message: '请选择订单编号',
              trigger: 'blur'
            }
          ]"
        >
          <el-select
           v-if="needProduce == 4 && orderNoList.length > 1"
            v-model="scope.row.orderNo"
            placeholder="请选择"
          >
            <el-option
              v-for="item in orderNoList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
          <span v-else>{{ scope.row.orderNo }}</span>
        </el-form-item>
      </template>
      <template v-slot:sendTotalWeight="scope">
        <el-form-item :prop="'datasource.' + scope.$index + '.sendTotalWeight'">
          <el-input
            type="number"
            v-model="scope.row.sendTotalWeight"
            style="width: 100%"
            @input="changeCount(scope.row, scope.$index, true, 'totalWeight')"
          >
            <template slot="append">
              {{ scope.row.weightUnit }}
            </template>
          </el-input>
        </el-form-item>
      </template>
      <template v-slot:increaseTotalWeight="scope">
        <el-form-item
          :prop="'datasource.' + scope.$index + '.increaseTotalWeight'"
        >
          <el-input
            type="number"
            v-model="scope.row.increaseTotalWeight"
            style="width: 100%"
            disabled
          >
            <template slot="append">
              {{ scope.row.weightUnit }}
            </template>
          </el-input>
        </el-form-item>
      </template>
      <template v-slot:warehouseId="scope">
        <el-form-item
          :prop="'datasource.' + scope.$index + '.warehouseId'"
          :rules="[
            {
              required: isWarehouseId == 1 ? true : false,
              message: '请选择仓库',
              trigger: 'blur'
            }
          ]"
        >
          <el-select
            v-model="scope.row.warehouseId"
            placeholder="请选择"
            @change="warehouseChange(scope.$index, scope.row, true)"
          >
            <el-option
              v-for="item in scope.row.warehouseList"
              :key="item.warehouseId"
              :label="item.warehouseName"
              :value="item.warehouseId"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </template>

      <template v-slot:singlePrice="scope">
        <el-form-item
          style="margin-bottom: 20px"
          :prop="'datasource.' + scope.$index + '.singlePrice'"
          :rules="{
            required: true,
            message: '请输入正确的单价',
            trigger: 'change'
          }"
        >
          <el-input
            v-model="scope.row.singlePrice"
            placeholder="请输入"
            @input="changeCount(scope.row, scope.$index)"
            type="number"
          >
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
      </template>

      <template v-slot:singleWeight="scope">
        <el-form-item
          style="margin-bottom: 20px"
          :rules="{
            required: false,

            trigger: 'change'
          }"
          :prop="'datasource.' + scope.$index + '.singleWeight'"
        >
          <el-input
            v-model="scope.row.singleWeight"
            type="number"
            placeholder="请输入"
            :disabled="needProduce == 4"
            @input="changeCount(scope.row, scope.$index)"
          >
            <template slot="append">
              {{ scope.row.weightUnit }}
            </template>
          </el-input>
        </el-form-item>
      </template>
      <template v-slot:headerWarehouseNum="{ column }">
        <span class="is-required">{{ column.label }}</span>
      </template>
      <template v-slot:headerWarehouseId="{ column }">
        <span :class="isWarehouseId == 1 ? 'is-required' : ''">{{
          column.label
        }}</span>
      </template>
      <template v-slot:headerTotalCount="{ column }">
        <span class="is-required">{{ column.label }}</span>
      </template>

      <template v-slot:headerReceiveTotalWeight="{ column }">
        <span :class="{ 'is-required': entrustedCode && pricingWay == 2 }">{{
          column.label
        }}</span>
      </template>
      <template v-slot:saleCount="scope">
        <el-form-item
          style="margin-bottom: 20px"
          :prop="'datasource.' + scope.$index + '.saleCount'"
          :rules="[{
            required: true,
            message: '请输入数量',
            trigger: 'change'
          },{
              validator: (rule, value, callback) => {
                if (value === undefined || value === null || value === '') {
                  callback('请输入数量');
                } else if (parseFloat(value) <= 0) {
                  callback('数量必须大于0');
                } else {
                  callback();
                }
              },
              trigger: 'blur'
            }]"
        >
          <el-input
            v-model="scope.row.saleCount"
            placeholder="请输入"
            type="number"
            :min="0"
            :disabled="sourceType == 4"
            @input="changeCount(scope.row, scope.$index, false)"
          >
            <template slot="append">
              <el-select
                v-model="scope.row.saleUnitId"
                style="width: 80px"
                @change="changeCount(scope.row, scope.$index)"
                :disabled="clientEnvironmentId == 4 || sourceType == 4"
              >
                <el-option
                  :label="item.conversionUnit"
                  :value="item.id"
                  v-for="(item, index) in scope.row.packageDispositionList"
                  :key="index"
                ></el-option>
              </el-select>
            </template>
          </el-input>
        </el-form-item>
      </template>
      <template v-slot:warehouseNum="scope">
        <el-form-item :prop="'datasource.' + scope.$index + '.warehouseNum'">
          <span>{{ scope.row.warehouseNum }}</span>
        </el-form-item>
      </template>
      <!-- <template v-slot:saleUnit="scope">
        <el-form-item
          style="margin-bottom: 20px"
          :prop="'datasource.' + scope.$index + '.saleUnitId'"
        >
          <el-select
            v-model="scope.row.saleUnitId"
            style="width: 100%"
            @change="changeCount(scope.row, scope.$index)"
            :disabled="clientEnvironmentId == 4"
          >
            <el-option
              :label="item.conversionUnit"
              :value="item.id"
              @click.native="packingChange(item, scope.$index)"
              v-for="(item, index) in scope.row.packageDispositionList"
              :key="index"
            ></el-option>
          </el-select>
        </el-form-item>
      </template> -->
      <template v-slot:modelKey="scope">
        <el-form-item :prop="'datasource.' + scope.$index + '.' + 'modelKey'">
          <DictSelection
            dictName="物品机型"
            clearable
            v-model="scope.row.modelKey"
            :isOne="scope.$index === 0"
            filterable
            allow-create
            default-first-option
            multiple
          >
          </DictSelection>
        </el-form-item>
      </template>

      <template v-slot:colorKey="scope">
        <el-form-item :prop="'datasource.' + scope.$index + '.' + 'colorKey'">
          <DictSelection
            dictName="物品颜色"
            clearable
            v-model="scope.row.colorKey"
            :isOne="scope.$index === 0"
            filterable
            allow-create
            default-first-option
            multiple
          >
          </DictSelection>
        </el-form-item>
      </template>
      <!-- 操作列 -->
      <template v-slot:action="scope">
        <el-popconfirm
          class="ele-action"
          title="确定要删除吗？"
          @confirm="remove(scope.$index)"
        >
          <template v-slot:reference>
            <el-link type="danger" :underline="false" icon="el-icon-delete">
              删除
            </el-link>
          </template>
        </el-popconfirm>
        <el-link
          type="primary"
          :underline="false"
          icon="el-icon-edit"
          @click="selectStockLedgerDialogOpen(scope.row)"
        >
          替代料
        </el-link>
      </template>
    </ele-pro-table>
    <productListNew
      ref="productListRef"
      @changeParent="changeParent"
    ></productListNew>
    <!--入库详情-->
    <innertboundDetailsDialog
      v-if="innerboundDetailsDialogFlag"
      ref="innerboundDetailsDialogRef"
      :innerboundDetailsDialogFlag.sync="innerboundDetailsDialogFlag"
      @saveDate="saveInnerDate"
    ></innertboundDetailsDialog>
    <!-- 库存台账   -->
    <stock-ledger-dialog
      v-if="stockLedgerDialogFlag"
      :stock-ledger-dialog-flag.sync="stockLedgerDialogFlag"
      ref="stockLedgerDialogRef"
      @getStockLedger="getStockLedger"
    ></stock-ledger-dialog>
    <selectStockLedgerDialog
      ref="selectStockLedgerDialogRef"
      @changeParent="replaceTable"
    ></selectStockLedgerDialog>
    <BIZproductList
      ref="BIZproductListRef"
      classType="1"
      :isGetInventoryTotal="true"
      @changeParent="changeParentBiz"
      :typeIds="typeIds"
      :isFirstRefreshTable="true"
    ></BIZproductList>
  </el-form>
</template>
<script>
  import { numberReg } from 'ele-admin';
  import dictMixins from '@/mixins/dictMixins';
  import productListNew from './product-listNew.vue';
  import {
    getWarehouseOutStock,
    getIdWarehouseList
  } from '@/api/saleManage/saleorder';

  import { copyObj } from '@/utils/util';
  import innertboundDetailsDialog from '@/BIZComponents/innerboundDetailsDialog.vue';
  import stockLedgerDialog from './stockLedger/stockLedgerDialog.vue';

  import getDynamicsColumns from '@/mixins/getDynamicsColumns';
  import selectStockLedgerDialog from '@/BIZComponents/selectStockLedger/selectStockLedgerDialog.vue'; //库存台账
  import BIZproductList from '@/BIZComponents/product-list.vue';
  import tabMixins from '@/mixins/tableColumnsMixin';
  import { levelList, pricingWayList, lbjtList } from '@/enum/dict.js';
  import { changeCount, formatPrice } from '@/BIZComponents/setProduct.js';
  import { parameterGetByCode } from '@/api/main/index.js';
  import { getSummaries } from '@/utils/util.js';
  import { getBatchList } from '@/api/wms';

  export default {
    mixins: [dictMixins, getDynamicsColumns, tabMixins],
    props: {
      orderId: String,
      orderIds: String,
      orderNos: String,
      needProduce: [String, Number],
      entrustedCode: String,
      pricingWay: [String, Number],
      isShowAdd: {
        type: Boolean,
        default: true
      },
      typeIds: {
        type: Array,
        default: () => []
      },
      oldProductList: {
        type: Array,
        default: () => []
      },
      sourceType: {
        type: [String, Number],
        default: ''
      },
      isTotalCount: {
        default: 0
      }
    },
    components: {
      // fileMain,
      innertboundDetailsDialog,
      productListNew,
      stockLedgerDialog,
      selectStockLedgerDialog,
      BIZproductList
    },
    data() {
      const defaultForm = {
        key: null,
        endTime: '',
        isFirst: 0,
        name: '',
        startTime: '',
        workHour: '',
        technicalDrawings: []
        // warehouseCode:"",
        // warehouseId:'',
        // warehouseName:'',
      };
      return {
        cacheKeyUrl: 'eos-saleManage-invoice-inventoryTable',
        current: {},
        childrenColumns: [
          {
            width: 45,
            type: 'selection',
            columnKey: 'selection',
            align: 'center'
          },
          {
            width: 45,
            type: 'index',
            columnKey: 'index',
            align: 'center',
            fixed: 'left'
          },

          {
            minWidth: 100,
            prop: 'code',
            label: '编码',
            align: 'center'
          },
          {
            minWidth: 140,
            prop: 'barcodes',
            label: '发货条码',
            align: 'center'
          },
          {
            minWidth: 100,
            prop: 'engrave',
            label: '刻码',
            align: 'center'
          }
        ],
        selection: [],
        discountTotalPrice: 0.0,
        allPrice: 0.0,
        curIndex: null,
        innerboundDetailsDialogFlag: false,
        stockLedgerDialogFlag: false,
        numberReg,
        defaultForm,
        warehouseList: [],
        dynamicsColumns: [],
        isWarehouseId: 0,
        blockCountColumn: {},
        form: {
          datasource: []
        },
        rules: {},
        columnsVersion: 1
      };
    },
    created() {
      this.requestDict('产地');
      this.requestDict('生产类型');
      parameterGetByCode({
        code: 'eom_saleManage_invoice_warehouseId'
      }).then((res) => {
        if (res.value) {
          this.isWarehouseId = res.value;
        }
      });
    },
    computed: {
      canHandl() {
        return this.form.datasource.length;
      },
      clientEnvironmentId() {
        return this.$store.state.user.info.clientEnvironmentId;
      },
      orderNoList() {
        const temp = this.orderNos?.split(',') || []
        return temp.map(item => {
          return {
            label: item,
            value: item
          }
        });
      },
      columns() {
        let columnsVersion = this.columnsVersion;
        return [
          {
            width: 60,
            type: 'index',
            columnKey: 'index',
            align: 'center',
            fixed: 'left'
          },
          {
            minWidth: 200,
            prop: 'orderNo',
            label: '订单编码',
            align: 'center',
            slot: 'orderNo',
            fixed: 'left'
          },

          {
            width: 200,
            prop: 'productName',
            label: '名称',
            slot: 'productName',
            align: 'center'
          },
          {
            width: 120,
            prop: 'productCode',
            label: '编码',
            slot: 'productCode',
            align: 'center'
          },
          {
            width: 200,
            prop: 'productCategoryName',
            label: '类型',
            slot: 'productCategoryName',
            align: 'center'
          },
          {
            width: 140,
            prop: 'pricingWay',
            label: '计价方式',
            align: 'center',
            fixed: 'left',

            formatter: (row, column) => {
              return pricingWayList.find((item) => item.id == row.pricingWay)
                ?.name;
            }
          },
          {
            width: 160,
            prop: 'batchStockId',
            label: '批次号',
            slot: 'batchStockId',
            align: 'center'
          },
          {
            width: 160,
            prop: 'productBrand',
            label: '牌号',
            slot: 'productBrand',
            align: 'center'
          },
          {
            width: 120,
            prop: 'modelType',
            label: '型号',
            slot: 'modelType',
            align: 'center'
          },
          {
            width: 120,
            prop: 'specification',
            label: '规格',
            slot: 'specification',
            align: 'center'
          },
          {
            width: 160,
            prop: 'modelKey',
            label: '机型',
            slot: 'modelKey',
            align: 'center'
          },
          {
            width: 160,
            prop: 'colorKey',
            label: '颜色',
            slot: 'colorKey',
            align: 'center'
          },
          {
            minWidth: 160,
            prop: 'productionCodes',
            label: '生产编号',
            align: 'center',
            slot: 'productionCodes'
          },
          {
            minWidth: 280,
            prop: 'productionRequirements',
            label: '生产要求',
            align: 'center'
          },
          {
            minWidth: 120,
            prop: 'goodsLevel',
            label: '物品级别',
            formatter: (_row, _column, cellValue) => {
              return levelList.find((item) => item.value == _row.goodsLevel)
                ?.label;
            },
            align: 'center'
          },
          ...this.dynamicsColumns,

          {
            width: 120,
            prop: 'customerMark',
            label: '客户代号',
            slot: 'customerMark',
            align: 'center'
          },
          {
            width: 200,
            prop: 'warehouseId',
            label: '仓库名称',
            slot: 'warehouseId',
            headerSlot: 'headerWarehouseId',
            align: 'center'
          },
          {
            width: 100,
            prop: 'warehouseNum',
            label: '库存',
            align: 'center',
            slot: 'warehouseNum'
          },

          // {
          //   width: 100,
          //   prop: 'stockLedger',
          //   label: '发货明细',
          //   slot: 'stockLedger',
          //   align: 'center'
          // },

          {
            width: 250,
            prop: 'saleCount',
            label: '发货数量',
            slot: 'saleCount',
            headerSlot: 'headerTotalCount',
            align: 'center'
          },
          {
            width: 100,
            prop: 'notSendTotalCount',
            label: '未发数量',
            align: 'center',
            formatter: (row, column) => {
              if (row.notSendTotalCount) {
                return row.notSendTotalCount + ' ' + row.measuringUnit;
              }
            }
          },
          {
            width: 120,
            prop: 'packingSpecification',
            align: 'center',
            label: '包装规格',
            showOverflowTooltip: true
          },

          {
            width: 120,
            prop: 'totalCount',
            label: '计量数量',
            formatter: (row, column) => {
              if (row.totalCount) {
                return row.totalCount + ' ' + row.measuringUnit;
              }
            },
            align: 'center'
          },
          {
            width: 120,
            prop: 'orderTotalCount',
            label: '订单数量',
            formatter: (row, column) => {
              if (row.orderTotalCount) {
                return row.orderTotalCount + ' ' + row.measuringUnit;
              }
            },
            align: 'center'
          },

          // {
          //   width: 80,
          //   prop: 'measuringUnit',
          //   label: '计量单位',
          //   slot: 'measuringUnit',
          //   align: 'center'
          // },
          this.clientEnvironmentId == 4 ? {
                width: 150,
                prop: 'blockCount',
                label: '发货块数',
                slot: 'blockCount',
                align: 'center'
              }
            : { width: 1 },

          {
            width: 200,
            prop: 'singleWeight',
            slot: 'singleWeight',
            label: '单重',

            align: 'center'
          },
          {
            width: 250,
            prop: 'receiveTotalWeight',
            label: '收货总重',
            slot: 'receiveTotalWeight',
            align: 'center',
            headerSlot: 'headerReceiveTotalWeight'
          },
          {
            width: 220,
            prop: 'sendTotalWeight',
            label: '发货总重',
            slot: 'sendTotalWeight',
            align: 'center'
          },

          {
            width: 220,
            prop: 'increaseTotalWeight',
            label: '增重重量',
            slot: 'increaseTotalWeight',

            align: 'center'
          },

          {
            width: 180,
            prop: 'singlePrice',
            label: '单价',
            slot: 'singlePrice',
            align: 'center'
          },
          {
            width: 160,
            prop: 'taxRate',
            label: '税率',
            formatter: (_row, _column, cellValue) => {
              return _row.taxRate ? _row.taxRate + '%' : '';
            },
            align: 'center'
          },
          {
            width: 180,
            prop: 'notaxSinglePrice',
            label: '不含税单价',
            align: 'center'
          },
          {
            width: 160,
            prop: 'discountSinglePrice',
            label: '折后单价',
            slot: 'discountSinglePrice',
            align: 'center'
          },
          {
            width: 120,
            prop: 'totalPrice',
            label: '合计',
            slot: 'totalPrice',
            align: 'center'
          },
          {
            width: 160,
            prop: 'notaxTotalPrice',
            label: '含税合计',
            align: 'center'
          },
          {
            width: 120,
            prop: 'discountTotalPrice',
            label: '折后合计',
            slot: 'discountTotalPrice',
            align: 'center'
          },
          {
            width: 120,
            prop: 'imgCode',
            align: 'center',
            label: '图号/件号',
            showOverflowTooltip: true
          },
          {
            width: 120,
            prop: 'produceType',
            align: 'center',
            label: '属性类型',
            formatter: (row, column) => {
              if (row.produceType) {
                return row.produceType
                  .map((item) => {
                    return lbjtList[item];
                  })
                  .toString();
              }
            },
            showOverflowTooltip: true
          },
          {
            width: 200,
            prop: 'guaranteePeriod',
            label: '有效期',
            slot: 'guaranteePeriod',
            formatter: (_row, _column, cellValue) => {
              let val = '';
              if (_row.guaranteePeriod) {
                val += _row.guaranteePeriod;
              }
              if (_row.guaranteePeriodUnitName) {
                val += _row.guaranteePeriodUnitName;
              }
              return val;
            },
            align: 'center'
          },
          {
            width: 200,
            prop: 'guaranteePeriodDeadline',
            label: '有效期截止日期',
            slot: 'guaranteePeriodDeadline',
            align: 'center'
          },
          {
            prop: 'provenance',
            label: '产地',
            slot: 'provenance',
            align: 'center',
            // show:this.contractBookType==2,
            minWidth: 200,
            showOverflowTooltip: true,
            formatter: (row, column) => {
              return row.provenance && row.provenance.length
                ? row.provenance
                    .map((item) => this.getDictValue('产地', item))
                    .join(',')
                : '';
            }
          },
          {
            width: 130,
            prop: 'technicalAnswerName',
            label: '技术答疑人',
            slot: 'technicalAnswerName',
            align: 'center'
          },
          {
            width: 220,
            prop: 'technicalParams',
            label: '技术参数',
            slot: 'technicalParams',
            align: 'center'
          },
          {
            width: 240,
            prop: 'technicalDrawings',
            label: '技术图纸',
            slot: 'technicalDrawings',
            align: 'center'
          },
          {
            width: 220,
            prop: 'remark',
            label: '备注',
            slot: 'remark',
            align: 'center'
          },
          {
            columnKey: 'action',
            label: '操作',
            width: 200,
            align: 'center',
            resizable: false,
            slot: 'action',
            fixed: 'right',
            showOverflowTooltip: true
          }
        ];
      }
    },
    mounted() {
      // this.clientEnvironmentId =
    },
    methods: {
      formatPrice,
      getSummaries(param) {
        if (this.clientEnvironmentId != 4) {
          return;
        }

        return getSummaries(
          param,
          ['saleCount', 'blockCount', 'totalCount'],
          ' '
        );
      },

      //发货明细选择
      stockLedgerSelect(row, index) {
        this.curIndex = index;
        this.stockLedgerDialogFlag = true;
        this.$nextTick(() => {
          this.$refs.stockLedgerDialogRef.init(row.sendProductDetail, row);
        });
      },

      packingChange(item, index) {
        this.$set(this.form.datasource[index], 'saleUnit', item.conversionUnit);
      },

      //获取
      getStockLedger(sendProductDetail) {
        if (!this.form.datasource[this.curIndex].sendProductDetail)
          this.form.datasource[this.curIndex].sendProductDetail = [];
        let row = this.form.datasource[this.curIndex];
        row.sendProductDetail.push(...sendProductDetail);
        this.form.datasource[this.curIndex] = row;
        this.$refs['childrenTable' + this.curIndex].reload();
        this.$refs.table.reload();
      },
      //删除发货明细
      stockLedgerRemove(PIndex) {
        let row = this.form.datasource[PIndex];
        this.selection.forEach((item) => {
          let index = row.sendProductDetail.findIndex((i) => i.id == item.id);
          row.sendProductDetail.splice(index, 1);
        });
        this.form.datasource[PIndex] = row;
        this.$refs['childrenTable' + PIndex].reload();
        this.$refs.table.reload();
        this.selection = [];
      },

      async warehouseChange(index, row, isReset = false) {
        // console.log('warehouseChange', index, row.isSuspend, isReset);
        const data = row.warehouseList.find(
          (item) => item.warehouseId == row.warehouseId
        );

        this.$set(
          this.form.datasource[index],
          'warehouseName',
          data.warehouseName
        );
        this.$set(
          this.form.datasource[index],
          'warehouseCode',
          data.warehouseCode
        );

        const warehouseOutStock = await getWarehouseOutStock({
          warehouseId: data.warehouseId,
          code: row.productCode
        });
        this.$set(
          this.form.datasource[index],
          'warehouseNum',
          warehouseOutStock || 0
        );

        const tempBatchNoList = await getBatchList({
          warehouseId: data.warehouseId,
          categoryCode: row.productCode
        });
        this.$set(
          this.form.datasource[index],
          'batchNoList',
          tempBatchNoList?.list || []
        );

        if (isReset) {
          this.$set(this.form.datasource[index], 'batchStockId', '');
          this.$set(this.form.datasource[index], 'batchNo', '');
        }
      },

      //批次号选择
      async batchNoChange(index, row) {
        if (!row.batchStockId) {
          this.$set(this.form.datasource[index], 'batchNo', '');
          // this.$set(this.form.datasource[index], 'warehouseNum', '');
          const tempWarehouse = await getIdWarehouseList({
            categoryId: this.form.datasource[index].productId
          });
          // 有仓库列表
          if (tempWarehouse?.length) {
            console.log('666~~~~!!', index, tempWarehouse);
            this.$set(
              this.form.datasource[index],
              'warehouseList',
              tempWarehouse
            );
          }

          this.$set(
            this.form.datasource[index],
            'warehouseNum',
            row.warehouseId
              ? await getWarehouseOutStock({
                  warehouseId: row.warehouseId,
                  code: row.productCode
                })
              : ''
          );

          return;
        }
        const data = row.batchNoList.find(
          (item) => item.id == row.batchStockId
        );
        this.$set(this.form.datasource[index], 'batchNo', data.batchNo);

        this.$set(
          this.form.datasource[index],
          'warehouseNum',
          data.measureQuantity || 0
        );
      },
      //改变数量
      changeCount(row, index, isBlockCount = true, weightType) {
        if (weightType == 'totalWeight') {
          this.$set(
            this.form.datasource[index],
            'totalWeight',
            this.form.datasource[index].sendTotalWeight
          );
        }

        this.$set(
          this.form.datasource,
          index,
          changeCount(
            row,
            {
              countKey: 'saleCount',
              unitKey: 'saleUnit',
              unitIdKey: 'saleUnitId'
            },
            false,
            weightType
          )
        );
        this.$set(
          this.form.datasource[index],
          'sendTotalWeight',
          this.form.datasource[index].totalWeight
        );
        this.changeSendTotalWeight(row, index);
        this.getNotaxSinglePrice();
        this.$forceUpdate();
        if (this.clientEnvironmentId == 4 && !isBlockCount) {
          this.tableHandleKeyUp(row, index, 'sum');
        }
      },
      //修改发货总重
      changeSendTotalWeight(row, index) {
        this.curIndex = index;

        this.setIcreaseTotalWeight(row);
      },
      keyChange(index, row, key) {
        this.$set(
          this.form.datasource[index],
          'extField.' + key,
          row.extField[key]
        );
        this.$forceUpdate();
      },
      //设置增重总重
      setIcreaseTotalWeight(row) {
        let receiveTotalWeight = Number(
          this.form.datasource[this.curIndex]?.receiveTotalWeight
        );
        let sendTotalWeight = Number(
          this.form.datasource[this.curIndex]?.sendTotalWeight
        );
        if (sendTotalWeight) {
          let increaseTotalWeight = sendTotalWeight - receiveTotalWeight;
          this.$set(
            this.form.datasource[this.curIndex],
            'increaseTotalWeight',
            increaseTotalWeight.toFixed(4)
          );
          if (row.pricingWay == 3) {
            this.$set(
              this.form.datasource[this.curIndex],
              'totalPrice',
              (increaseTotalWeight * row.singlePrice).toFixed(2)
            );
          }
        }

        this.$refs.table.reload();
        this.$forceUpdate();
      },
      //计算不含税单价
      getNotaxSinglePrice() {
        this.form.datasource.forEach((item, index) => {
          if (item.singlePrice && item.taxRate) {
            this.$set(
              this.form.datasource[index],
              'notaxSinglePrice',
              formatPrice(item.singlePrice / (1 + item.taxRate / 100))
            );
          } else {
            this.$set(this.form.datasource[index], 'notaxSinglePrice', '');
          }
        });
      },
      //入库单详情
      handleInnerBound(e, rows, index) {
        this.curIndex = index;
        this.innerboundDetailsDialogFlag = true;
        this.$nextTick(() => {
          let row = {
            code: this.entrustedCode
          };
          this.$refs.innerboundDetailsDialogRef.init(row);
        });
      },
      //选择入库单信息
      saveInnerDate(data = []) {
        let totalWeight = data.reduce((num, row) => {
          num += Number(row.weight);
          return num;
        }, 0);
        this.$set(
          this.form.datasource[this.curIndex],
          'receiveTotalWeight',
          totalWeight
        );
        console.log(totalWeight, 'totalWeight');
        this.setIcreaseTotalWeight(this.form.datasource[this.curIndex]);
      },

      // getWeightPrice() {
      //   let increaseTotalWeight =
      //     this.form.datasource[this.curIndex].increaseTotalWeight;
      //   let singlePrice = this.form.datasource[this.curIndex].singlePrice;
      //   let discountSinglePrice =
      //     this.form.datasource[this.curIndex].discountSinglePrice;
      //   this.$set(
      //     this.form.datasource[this.curIndex],
      //     'totalPrice',
      //     (Number(increaseTotalWeight) * Number(singlePrice)).toFixed(2)
      //   );
      //   this.$set(
      //     this.form.datasource[this.curIndex],
      //     'discountTotalPrice',
      //     (Number(discountSinglePrice) * Number(increaseTotalWeight)).toFixed(2)
      //   );
      // },

      // 表格：模数、数量(方)、块数输入框 输入事件
      tableHandleKeyUp(row, index, name) {
        if (row.specification) {
          let modelArr = row.specification.split('*');
          let modelLong = modelArr[0]; // model规格长度
          let modeWide = modelArr[1]; // model规格宽度
          let modeHight = modelArr[2].substr(0, modelArr[2].indexOf('cm')); // model规格高度
          modeHight = Number(modeHight);
          if (name === 'sum') {
            // row.blockCount = Math.floor(
            //   row.totalCount / ((modelLong * modeWide * modeHight) / 1000000)
            // );
            this.$set(
              this.form.datasource[index],
              'blockCount',
              Math.floor(
                row.totalCount / ((modelLong * modeWide * modeHight) / 1000000)
              )
            );
          } else if (name === 'blockCount') {
            row.totalCount =
              (Number(row.blockCount) * modelLong * modeWide * modeHight) /
              1000000;
            row.saleCount = row.totalCount;
            this.changeCount(row, index, true);
          }
        }
      },

      //选择产品回调
      async changeParent(obj) {
        console.log(obj, 'obj');
        obj.forEach((item) => {
          item.orderTotalCount = item.totalCount;
          item.id = '';
        });
        this.putTableValue(copyObj(obj));
      },
      //选择产品回调
      changeParentBiz(obj = [], idx) {
        console.log('obj~~~', obj, idx);
        obj.forEach(async (item, index) => {
          let i = idx == -1 ? index : idx;
          let row = JSON.parse(JSON.stringify(this.defaultForm));
          row.key = this.form.datasource.length + 1;
          row['tempId'] = this.form.datasource.length + 1;

          let parasm = idx == -1 ? row : this.form.datasource[i];
          console.log('parasm~~~~222', parasm);  
          this.$set(parasm, 'productId', item.id);
          this.$set(parasm, 'categoryName', item.name);
          this.$set(parasm, 'productCategoryId', item.categoryLevelId);
          this.$set(parasm, 'productBrand', item.brandNum);
          this.$set(parasm, 'productCategoryName', item.categoryLevelPath);
          this.$set(parasm, 'productCode', item.code);
          this.$set(parasm, 'productName', item.name);
          this.$set(parasm, 'modelType', item.modelType);
          this.$set(parasm, 'availableCountBase', item.availableCountBase);
          this.$set(parasm, 'measuringUnit', item.measuringUnit);
          this.$set(parasm, 'specification', item.specification);
          this.$set(parasm, 'weightUnit', item.weightUnit);
          this.$set(parasm, 'imgCode', item.imgCode);
          this.$set(parasm, 'produceType', item.componentAttribute);
          this.$set(parasm, 'approvalNumber', item.extField?.approvalNumber);
          this.$set(parasm, 'extField', item.extField || {});
          this.$set(parasm, 'singleWeight', item.netWeight);
          this.$set(parasm, 'pricingWay', item.pricingWay || 1);
          this.$set(parasm, 'singlePrice', 0);
          this.$set(parasm, 'discountSinglePrice', 0);
          this.$set(parasm, 'goodsLevel', item.goodsLevel);
          this.$set(parasm, 'orderNo', this.orderNoList[0]?.value || '');
          if (item.modelKey) {
            this.$set(parasm, 'modelKey', item.modelKey.split(','));
          }
          if (item.colorKey) {
            this.$set(parasm, 'colorKey', item.colorKey.split(','));
          }
          this.$set(parasm, 'receiveTotalWeight', 0);
          this.$set(parasm, 'sendTotalWeight', 0);
          this.$set(parasm, 'increaseTotalWeight', 0);
          this.$set(
            parasm,
            'packageDispositionList',
            item.packageDispositionList
          );

          if (item.packageDispositionList?.length) {
            this.$set(parasm, 'saleUnitId', item.packageDispositionList[0].id);
            this.$set(
              parasm,
              'saleUnit',
              item.packageDispositionList[0].conversionUnit
            );
          }
          this.$set(
            parasm,
            'warehouseList',
            await getIdWarehouseList({
              categoryId: item.id
            })
          );

          const templist = await getBatchList({
                categoryCode: item.code,
                warehouseId: item.warehouseId,
                size: -1
              });

          this.$set(
            parasm,
            'batchNoList',
            templist?.list
          );

          console.log('parasm~~~~333', parasm);

          this.$set(
            parasm,
            'packingSpecification',
            item.extField?.packingSpecification
          );
          this.$set(
            parasm,
            'supplierMark',
            this.form.datasource[0]?.supplierMark
          );
          if (item.purchaseOrigins?.length > 0) {
            item.purchaseOrigins = item.purchaseOrigins.map((val) => val + '');
          }
          this.$set(parasm, 'provenance', item.purchaseOrigins || []);
          console.log('parasm~~~~', parasm);
          console.log('row~~~~', row);
          if (idx == -1) {
            this.form.datasource.push(row);
          }
          console.log('this.form.datasource~~~~', this.form.datasource);
        });
      },
      replaceTable(list) {
        list.forEach((item) => {
          item['relationId'] = this.current.tempId;
        });
        this.$emit('replaceTableChange', list);
      },
      // validateTotalCount(row) {
      //   return (rule, value, callback) => {
      //     if (isNaN(value) || Number(value) <= 0) {
      //       this.$message.error('请输入大于0的数');
      //       callback(false);
      //     } else else {
      //       callback();
      //     }
      //   };
      // },
      // 返回列表数据
      getTableValue() {
        let comitDatasource = this.form.datasource;
        if (comitDatasource.length === 0) return [];
        comitDatasource.forEach(async (v) => {
          if (v.modelKey) {
            v.modelKey = v.modelKey.toString();
          }
          if (v.colorKey) {
            v.colorKey = v.colorKey.toString();
          }
          v.totalCount = Number(v.totalCount);
          v.technicalDrawings = Array.isArray(v.technicalDrawings)
            ? v.technicalDrawings
            : [];
          v.customerReqFiles = Array.isArray(v.customerReqFiles)
            ? v.customerReqFiles
            : [];
          v.industryArtFiles = v.industryArtFiles || [];
          v.otherFiles = v.otherFiles || [];
        });
        return comitDatasource;
      },
      getPrice() {
        return [this.allPrice];
      },

      //修改回显
      putTableValue(data, isInit) {
        if (isInit) {
          this.form.datasource = [];
        }
        if (data) {
          this.setValue(data);
        }
      },
      setValue(data) {
        console.log('setValue~~~~~~', data);
        let indexS = [];
        data.forEach((item, index) => {
          if (item.modelKey) {
            this.$set(data[index], 'modelKey', item.modelKey.split(','));
          }
          if (item.colorKey) {
            this.$set(data[index], 'colorKey', item.colorKey.split(','));
          }
          item.receiveTotalWeight = item.receiveTotalWeight || 0;

          if (item.weightUnit == item.measuringUnit) {
            item.sendTotalWeight = item.sendTotalWeight || item.totalCount;
          } else {
            item.sendTotalWeight =
              item.sendTotalWeight || Number(item.totalWeight) || 0;
          }

          if (this.outsourceSendCode) {
            item.increaseTotalWeight =
              Number(item.receiveTotalWeight) - Number(item.sendTotalWeight);
            item.increaseTotalWeight;
          } else {
            item.increaseTotalWeight =
              item.increaseTotalWeight || item.receiveTotalWeight || 0;
          }
          // item['sendTotalWeight'] = item.sendTotalWeigh;
          // item['increaseTotalWeight'] = item.increaseTotalWeight;
          item['tempId'] = this.form.datasource.length;
          indexS.push(this.form.datasource.length);
          this.$set(
            this.form.datasource,
            this.form.datasource.length,
            copyObj(item)
          );

          // this.form.datasource.push(item);
        });
        this.form.datasource.forEach(async (item, index) => {
          if (indexS.includes(index)) {
            if (!item.batchNo) {
              console.log('111~~~~', index);
              this.$set(
                this.form.datasource[index],
                'warehouseList',
                await getIdWarehouseList({
                  categoryId: item.productId
                })
              );
              if (item.warehouseId) {
                this.$set(
                  this.form.datasource[index],
                  'warehouseNum',
                  await getWarehouseOutStock({
                    warehouseId: item.warehouseId,
                    code: item.productCode
                  })
                );
              } else if (this.form.datasource[index]?.warehouseList?.length) {
                this.$set(
                  this.form.datasource[index],
                  'warehouseId',
                  this.form.datasource[index]?.warehouseList[0].warehouseId
                );
                await this.warehouseChange(index, this.form.datasource[index]);
              }

              const templist = await getBatchList({
                categoryCode: item.productCode,
                warehouseId: item.warehouseId,
                size: -1
              });

              // console.log('templist~~~~', index, templist.list);

              // 批次号
              this.$set(
                this.form.datasource[index],
                'batchNoList',
                templist?.list || []
              );
              // console.log(this.form.datasource[index]);
            } else {
              this.setBatchAndWarehouse(item, index);
            }
          }
        });
      },
      async setBatchAndWarehouse(item, index) {
        console.log('333~~~~', index);
        // 通过产品编码查仓库
        const tempWarehouse = await getIdWarehouseList({
          categoryId: item.productId
        });
        // 有仓库列表
        if (tempWarehouse?.length) {
          console.log('666~~~~', index, tempWarehouse);
          this.$set(
            this.form.datasource[index],
            'warehouseList',
            tempWarehouse
          );
          if (item.warehouseId) {
            this.$set(
              this.form.datasource[index],
              'warehouseNum',
              await getWarehouseOutStock({
                warehouseId: item.warehouseId,
                code: item.productCode
              })
            );
          } else {
            if (this.form.datasource[index]?.warehouseList?.length) {
              this.$set(
                this.form.datasource[index],
                'warehouseId',
                this.form.datasource[index]?.warehouseList[0].warehouseId
              );
              await this.warehouseChange(index, this.form.datasource[index]);
            }
          }

          const templist1 = await getBatchList({
            categoryCode: item.productCode,
            warehouseId: item.warehouseId,
            size: -1
          });

          let tempBatchNoList = templist1?.list || [];
          console.log('888~~~~', index, item.batchNo);

          const batchNoObj = tempBatchNoList.find(
            (i) => i.batchNo == item.batchNo
          );

          if (batchNoObj) {
            this.$set(
              this.form.datasource[index],
              'batchStockId',
              batchNoObj.id
            );
            this.$set(
              this.form.datasource[index],
              'warehouseNum',
              batchNoObj.measureQuantity || 0
            );
          } else {
            //不存在
            // 批次列表添加不存在的批次号对象
            tempBatchNoList.push({
              batchNo: item.batchNo,
              id: 999,
              measureQuantity: 0
            });
            // 设置为不存在的批次ID
            this.$set(this.form.datasource[index], 'batchStockId', 999);
            this.$set(this.form.datasource[index], 'warehouseNum', '');
          }

          // // 批次号
          this.$set(
            this.form.datasource[index],
            'batchNoList',
            tempBatchNoList
          );
        } else {
          if (item.batchNo) {
            const tempBatchNoList = [
              {
                batchNo: item.batchNo,
                id: 999,
                measureQuantity: 0
              }
            ];
            this.$set(
              this.form.datasource[index],
              'batchNoList',
              tempBatchNoList
            );
            this.$set(this.form.datasource[index], 'batchStockId', 999);
            this.$set(this.form.datasource[index], 'warehouseNum', '');
          }
        }
      },
      remove(i) {
        this.form.datasource.splice(i, 1);
        this.setSort();
      },

      // 重新排序
      setSort() {
        this.form.datasource.forEach((n, index) => {
          n.key = index + 1;
        });
      },
      //选择产品
      handParent() {
        console.log('this.type~~~~111', this.orderId);
        if (!this.orderId && !this.orderIds)
          return this.$message.error('请先选择订单');
        this.$refs.BIZproductListRef.open('', -1);
      },
      // 添加
      handlAdd() {
        console.log('this.type~~~~222', this.orderId);
        if (!this.orderId && !this.orderIds)
          return this.$message.error('请先选择订单');
        this.$refs.productListRef.open(this.oldProductList);
      },
      //库存台账
      selectStockLedgerDialogOpen(row) {
        this.current = row;
        this.$refs.selectStockLedgerDialogRef.open();
      },
      validateForm(callback) {
        //开始表单校验
        this.$refs.form.validate((valid, obj) => {
          let is = false;
          this.form.datasource.forEach((item) => {
            if (Number(item.totalCount) > item.orderTotalCount) {
              is = true;
            }
          });
          // 退货单退货不校验数量，实物赔偿无法计算
          if (is && this.sourceType != 3 && this.needProduce != 4) {
            this.$message.warning('发货数量大于订单总数量');
            if (this.isTotalCount == 1) {
              callback(false);
            }
          }
          if (obj) {
            let messages = Object.keys(obj).map((key) => obj[key][0]);
            if (messages.length > 0) {
              this.$message.warning(messages[0].message);
            }
          }

          callback(valid);
        });
      }
    }
  };
</script>
<style lang="scss" scoped>
  ::v-deep .el-table .warning-row {
    background: #d9ecff;
  }
  .headbox {
    display: flex;
    justify-content: flex-start;
    align-items: center;

    .amount {
      font-size: 14px;
      font-weight: bold;
      padding-right: 30px;
    }
  }

  .time-form .el-form-item {
    margin-bottom: 0 !important;
  }

  ::v-deep .period {
    display: flex;

    .borderleftnone {
      .el-input--medium .el-input__inner {
        border-top-right-radius: 0;
        border-bottom-right-radius: 0;
      }
    }

    .borderrightnone {
      .el-input--medium .el-input__inner {
        border-top-left-radius: 0;
        border-bottom-left-radius: 0;
      }
    }
  }

  ::v-deep .time-form tbody > tr:hover > td {
    background-color: transparent !important;
  }

  // ::v-deep .time-form .el-table tr {
  //   background-color: #ffffff;
  // }

  .pricebox {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    font-weight: bold;
  }
</style>
