<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:batchNo="scope">
        <el-form-item :prop="'datasource.' + scope.$index + '.batchNo'">
          <el-input v-model="scope.row.batchNo" v-no-chinese></el-input>
        </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-number
            :controls="false"
            v-model="scope.row.receiveTotalWeight"
            @input="changeSendTotalWeight(scope.row, scope.$index)"
            style="width: 60%; margin-right: 10px"
          >
          </el-input-number>
          <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:sendTotalWeight="scope">
        <el-form-item :prop="'datasource.' + scope.$index + '.sendTotalWeight'">
          <el-input-number
            :controls="false"
            v-model="scope.row.sendTotalWeight"
            style="width: 100%"
            @input="changeSendTotalWeight(scope.row, scope.$index)"
          >
          </el-input-number>
        </el-form-item>
      </template>
      <template v-slot:increaseTotalWeight="scope">
        <el-form-item
          :prop="'datasource.' + scope.$index + '.increaseTotalWeight'"
        >
          <el-input-number
            :controls="false"
            v-model="scope.row.increaseTotalWeight"
            style="width: 100%"
          >
          </el-input-number>
        </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)"
          >
            <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" v-if="needProduce == 4">
        <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="请输入"
          ></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'
          }"
        >
          <el-input
            v-model="scope.row.saleCount"
            placeholder="请输入"
            type="number"
            :min="0"
            @input="changeCount(scope.row, scope.$index, false)"
          >
          </el-input>
        </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 { getFile } from '@/api/system/file';
  import innertboundDetailsDialog from '@/BIZComponents/innerboundDetailsDialog.vue';
  import stockLedgerDialog from './stockLedger/stockLedgerDialog.vue';

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

  export default {
    mixins: [dictMixins, getDynamicsColumns, tabMixins],
    props: {
      orderId: String,
      orderIds: String,
      needProduce: [String, Number],
      entrustedCode: String,
      pricingWay: [String, Number],
      isShowAdd: {
        type: Boolean,
        default: true
      },
      typeIds: {
        type: Array,
        default: () => []
      },
      oldProductList: {
        type: Array,
        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: [],
        columnsVersion: 1,
        isWarehouseId: 0,
        blockCountColumn: {},
        form: {
          datasource: []
        },
        rules: {}
      };
    },
    created() {
      this.getColumns();
      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;
      },
      columns() {
        return [
          {
            width: 60,
            type: 'index',
            columnKey: 'index',
            align: 'center',
            fixed: 'left'
          },
          {
            minWidth: 150,
            prop: 'orderNo',
            label: '订单编码',
            align: 'center',
            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: 160,
            prop: 'batchNo',
            label: '批次号',
            slot: 'batchNo',
            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: 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: 150,
            prop: 'saleCount',
            label: '发货数量',
            slot: 'saleCount',
            headerSlot: 'headerTotalCount',
            align: 'center'
          },
          {
            width: 150,
            prop: 'saleUnit',
            label: '单位',
            slot: 'saleUnit',
            align: 'center'
          },
          {
            width: 120,
            prop: 'packingSpecification',
            align: 'center',
            label: '包装规格',
            showOverflowTooltip: true
          },

          {
            width: 120,
            prop: 'totalCount',
            label: '计量数量',
            // slot: 'totalCount',
            // headerSlot: 'headerTotalCount',
            align: 'center'
          },
          {
            width: 120,
            prop: 'orderTotalCount',
            label: '订单数量',
            slot: 'orderTotalCount',
            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: 120,
            prop: 'singleWeight',
            label: '单重',
            slot: 'singleWeight',
            align: 'center'
          },
          {
            width: 200,
            prop: 'receiveTotalWeight',
            label: '收货总重',
            slot: 'receiveTotalWeight',
            align: 'center',
            headerSlot: 'headerReceiveTotalWeight'
          },
          {
            width: 100,
            prop: 'sendTotalWeight',
            label: '发货总重',
            slot: 'sendTotalWeight',
            align: 'center'
          },

          {
            width: 100,
            prop: 'increaseTotalWeight',
            label: '增重重量',
            slot: 'increaseTotalWeight',
            align: 'center'
          },
          {
            width: 100,
            prop: 'weightUnit',
            label: '重量单位',
            slot: 'weightUnit',
            align: 'center'
          },
          // {
          //   width: 160,
          //   prop: 'pricingWay',
          //   label: '计价方式',
          //   slot: 'pricingWay',
          //   align: 'center',
          //   formatter: (row, column) => {
          //     return row.pricingWay == 1
          //       ? '按数量计费'
          //       : row.pricingWay == 2
          //       ? '按重量计费'
          //       : '';
          //   }
          // },
          {
            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: 180,
            align: 'center',
            resizable: false,
            slot: 'action',
            fixed: 'right',
            showOverflowTooltip: true
          }
        ];
      }
    },
    mounted() {
      // this.clientEnvironmentId =
    },
    methods: {
      getSummaries(param) {
        if (this.clientEnvironmentId != 4) {
          return;
        }

        return getSummaries(
          param,
          ['saleCount', 'blockCount', 'totalCount'],
          ' '
        );
      },
      downloadFile(file) {
        getFile({ objectName: file.storePath }, file.name);
      },
      //发货明细选择
      stockLedgerSelect(row, index) {
        this.curIndex = index;
        this.stockLedgerDialogFlag = true;
        this.$nextTick(() => {
          this.$refs.stockLedgerDialogRef.init(row.sendProductDetail, row);
        });
      },

      // changeCount1(row, index) {
      //   this.tableHandleKeyUp(row, index, 'sum');
      //   this.changeCount(row, index);
      // },
      packingChange(item, index) {
        this.$set(this.form.datasource[index], 'saleUnit', item.conversionUnit);
      },
      //改变数量
      // changeCount() {
      //   this.form.datasource.forEach((item, index) => {
      //     if (item.pricingWay == 1) {
      //       this.$set(
      //         this.form.datasource[index],
      //         'discountTotalPrice',
      //         item.discountSinglePrice * item.totalCount
      //       );
      //       this.$set(
      //         this.form.datasource[index],
      //         'totalPrice',
      //         item.singlePrice * item.totalCount
      //       );
      //     }
      //     if (item.pricingWay == 2) {
      //       this.$set(
      //         this.form.datasource[index],
      //         'discountTotalPrice',
      //         item.discountSinglePrice *
      //           item.totalCount *
      //           (item.singleWeight || 0)
      //       );
      //       this.$set(
      //         this.form.datasource[index],
      //         'totalPrice',
      //         item.singlePrice * item.totalCount * (item.singleWeight || 0)
      //       );
      //     }
      //   });
      // },
      //获取
      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) {
        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
        );
      },
      //改变数量
      changeCount(row, index, isBlockCount = true) {
        this.$set(
          this.form,
          'datasource[' + index + ']',
          changeCount(row, {
            countKey: 'saleCount',
            unitKey: 'saleUnit',
            unitIdKey: 'saleUnitId'
          })
        );
        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 && receiveTotalWeight) {
          this.$set(
            this.form.datasource[this.curIndex],
            'increaseTotalWeight',
            (sendTotalWeight - receiveTotalWeight).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',
              parseFloat(
                (item.singlePrice / (1 + item.taxRate / 100)).toFixed(2)
              )
            );
          } 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)
            );
          } 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) {
        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];
          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);
          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
            })
          );
          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 || []);
          if (idx == -1) {
            this.form.datasource.push(row);
          }
        });
      },
      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) {
        let indexS = [];
        data.forEach((item, index) => {
          if (item.modelKey) {
            item.modelKey = item.modelKey.toString();
          }
          if (item.colorKey) {
            item.colorKey = item.colorKey.toString();
          }
          item.receiveTotalWeight = item.receiveTotalWeight || 0;

          if (item.weightUnit == item.measuringUnit) {
            item.sendTotalWeight = item.sendTotalWeight || item.totalCount;
          } else {
            item.sendTotalWeight =
              item.sendTotalWeight ||
              Number(item.totalCount) * Number(item.singleWeight) ||
              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)) {
            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]);
            }
          }
        });
      },

      remove(i) {
        this.form.datasource.splice(i, 1);
        this.setSort();
      },

      // 重新排序
      setSort() {
        this.form.datasource.forEach((n, index) => {
          n.key = index + 1;
        });
      },
      //选择产品
      handParent() {
        if (!this.orderId && !this.orderIds)
          return this.$message.error('请先选择订单');
        this.$refs.BIZproductListRef.open('', -1);
      },
      // 添加
      handlAdd() {
        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.$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>
  .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>
