<template>
  <el-dialog top="0" width="1200px" title="详情" :visible.sync="dialogVisible" :before-close="detailClose"
    :close-on-click-modal="false">
    <div ref="detailsContentRef" class="details-content">
      <!-- 基本信息 -->
      <DefineDescriptions :items="items" :items-data="itemsData" />
      <!-- 仓库收货数据 -->
      <div class="flex mb-12">
        <div class="warp-left">仓库收货数据</div>
        <div class="warp-right">
          <vxe-table
            ref="storehouseRef"
            class="customer-table" border
            show-overflow
            :data="propsCustomerData"
            show-footer
            show-header-overflow
            height="280px"
            :header-row-style="{
              background: '#f2f6fc',
              borderRight: '1px solid #ccc',
            }"
            :cell-style="{ height: '38px', padding: 0 }"
            :column-config="{ resizable: true }"
            :footer-method="footerMethodCustomerStore">
            <vxe-column field="BoxNumber" :min-width="140" title="箱号" />
            <vxe-column field="OpInputWeight" title="收货实重KG" :min-width="90" />
            <vxe-column field="OpLength" title="长CM" :min-width="80" />
            <vxe-column field="OpWidth" title="宽CM" :min-width="80" />
            <vxe-column field="OpHeight" title="高CM" :min-width="80" />
            <vxe-column field="VolumeWeight" title="计费泡重" :width="120" />
            <vxe-column field="GoodsNames" title="操作备注" :width="140" fixed="right" />
          </vxe-table>
        </div>
      </div>
      <!-- 客户确认数据 -->
      <div class="warp-action" v-show="enabledVisible">
        <el-button type="warning" plain size="mini" @click="hanleRecompute">重算计费泡重</el-button>
        <el-button type="primary" plain size="mini" @click="hanleCheckCopy">复制内容到勾选箱</el-button>
        <el-button type="success" plain size="mini" @click="hanleCheckCopyAll">复制内容到所有箱</el-button>
      </div>
      <div class="flex mb-12">
        <div class="warp-left">客户确认数据</div>
        <div class="warp-right">
          <vxe-table ref="customerRef" class="customer-table" border show-overflow show-footer :data="propsCustomerData"
            height="280px"
            show-header-overflow
            :header-row-style="{
              background: '#f2f6fc',
              borderRight: '1px solid #ccc',
            }"
            :column-config="{ resizable: true }"
            :scroll-y="{ gt: 0 }"
            :cell-style="{ height: '38px', padding: 0 }"
            :edit-config="{ trigger: 'click', mode: 'cell', enabled: enabledVisible }"
            :footer-method="footerMethodCustomer"
            @checkbox-all="handleSelectionCustomer"
            @checkbox-change="handleSelectionCustomer">
            <vxe-column type="checkbox" width="45" />
            <vxe-column field="BoxNumber" title="箱号" :min-width="140" />
            <vxe-column field="BillWeight" title="计费实重KG" :min-width="110"
              :edit-render="{ autofocus: '.vxe-input--inner' }">
              <template #edit="{ row }">
                <vxe-input v-model="row.BillWeight" name="BillWeight" type="text" @blur="hanleRecompute" />
              </template>
            </vxe-column>
            <vxe-column field="BillLenght" title="长CM" :min-width="80" :edit-render="{ autofocus: '.vxe-input--inner' }">
              <template #edit="{ row }">
                <vxe-input v-model="row.BillLenght" name="BillLenght" type="text"
                  @blur="updateSingleCustomerGoodsNames(row, 'BillLenght')" />
              </template>
            </vxe-column>
            <vxe-column field="BillWidth" title="宽CM" :min-width="80" :edit-render="{ autofocus: '.vxe-input--inner' }">
              <template #edit="{ row }">
                <vxe-input v-model="row.BillWidth" name="BillWidth" type="text"
                  @blur="updateSingleCustomerGoodsNames(row, 'BillWidth')" />
              </template>
            </vxe-column>
            <vxe-column field="BillHeight" title="高CM" :min-width="80" :edit-render="{ autofocus: '.vxe-input--inner' }">
              <template #edit="{ row }">
                <vxe-input v-model="row.BillHeight" name="BillHeight" type="text"
                  @blur="updateSingleCustomerGoodsNames(row, 'BillHeight')" />
              </template>
            </vxe-column>
            <vxe-column field="BillVolumeWeight" title="计费泡重" :width="120"
              :edit-render="{ autofocus: '.vxe-input--inner' }">
              <template #edit="{ row }">
                <vxe-input v-model="row.BillVolumeWeight" name="BillVolumeWeight" type="text"
                  @blur="updateSingleCustomerGoodsNames(row, 'BillVolumeWeight')" />
              </template>
            </vxe-column>
            <vxe-column field="CustomerGoodsNames" title="操作备注" :width="140" fixed="right">
              <!-- <template #default>
                <div />
              </template> -->
              <!-- 分泡系数 -->
              <!-- <template #edit="{ row }">
                <vxe-input
                  v-model="row.VolumeFactor"
                  name="VolumeFactor"
                  type="text"
                />
              </template> -->
            </vxe-column>
          </vxe-table>
          <div class="flex cost-warp">
            <span>最终确认计费重</span>
            <el-input v-model="propsTotalReceivableData[0].CustomerConfirmBillWeight" class="heavy" placeholder="请输入内容"
              :disabled="!enabledVisible" />
            <div class="cost weightRate" :class="{ 'mr17': getLengthNum }">-</div>
          </div>
          <div class="cost-warp-2">
            <div>
              <span class="w-180">报关方式</span>
              <el-input v-model="propsTotalReceivableData[0].DeclarationMethod" class="declaration" placeholder="请输入内容"
                :disabled="!enabledVisible" />
            </div>
            <div class="cost weightRate" :class="{ 'mr17': getLengthNum }">分泡系数</div>
          </div>
          <div class="cost-warp-2">
            <div />
            <div class="cost" :class="{ 'mr17': getLengthNum }">
              <el-input v-model="propsTotalReceivableData[0].SplitWeightRate" v-decimal-bubble-input class="w-48"
                placeholder="请输入内容" :disabled="!enabledVisible" />
              <el-button type="primary" size="mini" class="return-btn" :disabled="!enabledVisible"
                @click="hanleRecalculateBillingWeight">重算计费重</el-button>
            </div>
          </div>
        </div>
      </div>
      <!-- 附加费 -->
      <div class="flex mb-12">
        <div class="warp-left">附加费</div>
        <div class="warp-right">
          <vxe-table
            class="customer-table"
            border show-overflow
            show-footer
            show-header-overflow
            :data="propsSurchargeData"
            height="280px"
            :cell-style="{ height: '38px', padding: 0 }"
            :header-row-style="{
              background: '#f2f6fc',
              borderRight: '1px solid #ccc',
            }"
            :column-config="{ resizable: true }"
            :edit-config="{ trigger: 'click', mode: 'cell', enabled: enabledVisible }"
            :footer-method="footerSurchargeMethod">
            <template v-if="enabledVisible">
              <vxe-column title="操作" width="80">
                <template #default="scope">
                  <el-button type="text" size="small" @click.native.prevent="handleAddSurcharge">
                    新增
                  </el-button>
                  <el-button type="text" size="small" class="delete" @click.native.prevent="handleDeleteRow(scope.rowIndex, propsSurchargeData)
                    ">
                    移除
                  </el-button>
                </template>
              </vxe-column>
            </template>
            <vxe-column field="Id" title="附加费项" :min-width="100" :edit-render="{ autofocus: '.vxe-input--inner' }">
              <template #default="{ row }">
                <!-- 不编辑显示的文本 -->
                <span>{{ formatFBAOtherFee(row.FBAOtherFeeId, FBAOtherFee) }}</span>
              </template>
              <template #edit="{ row }">
                <vxe-select v-model="row.FBAOtherFeeId" :transfer="true" placeholder="附加费项"
                  @change="changeFBAOtherFee(row)">
                  <vxe-option v-for="item in FBAOtherFee" :key="item.Id" :value="item.Id" :label="item.Name" />
                </vxe-select>
              </template>
            </vxe-column>
            <vxe-column field="CustomerRemark" title="附加费标准" :min-width="100"
              :edit-render="{ autofocus: '.vxe-input--inner' }">
              <template #edit="{ row }">
                <span v-if="SurchargeType == '结算'">
                  <vxe-input v-model="row.JSRemark" type="text" placeholder="附加费标准" />
                </span>
                <span v-else>
                  <vxe-input v-model="row.CustomerRemark" type="text" placeholder="附加费标准" />
                </span>
              </template>
            </vxe-column>
            <vxe-column field="Fee" title="费项附加费总额" :min-width="100" :edit-render="{ autofocus: '.vxe-input--inner' }">
              <template #edit="{ row }">
                <vxe-input v-model="row.Fee" type="text" placeholder="请填入计费值" />
              </template>
            </vxe-column>
            <vxe-column field="Remark" title="备注" :min-width="90" :edit-render="{ autofocus: '.vxe-input--inner' }">
              <template #edit="{ row }">
                <vxe-input v-model="row.Remark" type="text" placeholder="备注" />
              </template>
            </vxe-column>
            <vxe-column field="SysncJS" title="是否计入销售成本" :width="140">
              <template #header><i class="vxe-icon-edit" v-show="enabledVisible" />是否计入销售成本
              </template>
              <template #default="{ row }">
                <vxe-checkbox v-model="row.SysncJS" size="medium">{{
                  row.SysncJS ? "是" : "否"
                }}</vxe-checkbox>
              </template>
            </vxe-column>
            <!-- <vxe-column v-if="getLengthNum" :width="17" /> -->
            <template #empty>
              <el-button v-show="propsSurchargeData.length === 0 && enabledVisible" type="text" icon="el-icon-plus"
                class="empty" @click="handleAddSurcharge" />
            </template>
          </vxe-table>
          <div class="flex cost-warp">
            <el-input v-model="propsTotalReceivableData[0].ApprovalNumber" :disabled="!enabledVisible" class="number"
              placeholder="特殊申请审批编号" />
            <!-- :class="{ 'mr17': getLengthNumber }" -->
          </div>
        </div>
        <div class="col-gutter-width" :style="{ width: `${colGutterWidth}px` }" />
      </div>
      <!-- 应收金额 -->
      <div class="flex mb-12">
        <div class="warp-left">应收总额</div>
        <div class="flex-1">
          <el-table :data="propsTotalReceivableData" border>
            <el-table-column prop="CustomerConfirmBillWeight" label="计费重量KG">
              <!-- <template slot-scope="scope">
                <el-input
                  v-model="scope.row.CustomerConfirmBillWeight"
                  size="small"
                  placeholder="计费重量KG"
                />
              </template> -->
            </el-table-column>
            <el-table-column prop="CustomerConfirmUnitPrice" label="单价">
              <template slot-scope="scope">
                <el-input v-model="scope.row.CustomerConfirmUnitPrice" :disabled="!enabledVisible" size="small"
                  placeholder="单价" @input="changeCustomerConfirmTotal" />
              </template>
            </el-table-column>
            <el-table-column prop="CustomerConfirmTotalSurcharges" label="附加费总额">
              <template slot-scope="scope">
                <div v-if="scope.row.CustomerConfirmTotalSurcharges > 0">
                  {{ scope.row.CustomerConfirmTotalSurcharges }}
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="CustomerConfirmTotal" label="应收总额">
              <template slot-scope="scope">
                <div v-if="scope.row.CustomerConfirmTotal > 0">
                  {{ scope.row.CustomerConfirmTotal }}
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="flex flex-1 total-receivable">
          <el-button
            size="mini" type="success"
            :loading="saveLadding"
            @click="confirmSell"
            v-show="enabledVisible && getSellRoles"
            >销售确认</el-button>
          <el-button size="mini" type="primary" :loading="saveLadding" @click="edit"
            v-show="enabledVisible">确定修改</el-button>
          <el-button size="mini" @click="detailClose">取消</el-button>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import { deepClone } from '@/utils'
import { _getAll } from '@/api/order/fba/index'
import DefineDescriptions from './DefineDescriptions.vue'
import { throttle } from 'echarts/lib/export'
import { calculate_VolumeWeight } from '@/utils/calculate'
import { _getUnitPrice, _getBoxlDCRData } from '@/api/fba/Receiving'
import { mapGetters } from "vuex";

export default {
  name: 'DetailIconme',
  components: { DefineDescriptions },
  props: {
    // 是否启用编辑，默认启用
    enabledVisible: {
      type: Boolean,
      default: true
    },
    width: {
      type: String,
      default: '65%'
    },
    title: String,
    dialogVisible: {
      type: Boolean,
      default: false
    },
    orderId: {
      type: Number,
      default: 0
    },
    itemsData: {
      type: Object,
      default: () => { }
    },
    customerData: {
      type: Array,
      default: () => []
    },
    surchargeData: {
      type: Array,
      default: () => []
    },
    totalReceivableData: {
      type: Array,
      default: () => []
    },
    SurchargeType: ''
  },
  data() {
    return {
      items: [
        { field: 'ReceiveTimeStr', label: '收货日期' },
        { field: 'CompanyName', label: '客户名称' },
        { field: 'CustomerOrderNo', label: '客户单号' },
        { field: 'SystemNo', label: '行运易单号' },
        { field: 'PublicName', label: '渠道' },
        { field: 'ReceiverCountryCode', label: '国家' },
        { field: 'BoxQty', label: '件数' },
        { field: 'ReceiverZipCode', label: '收件人邮编', width: 140 }
      ], // 基本信息
      multipleCustomer: [], // 客户确认数据选中数据
      currentInput: {
        value: '',
        field: ''
      }, // 当前的复制内容
      oldCustomerData: [],
      propsCustomerData: [],
      propsSurchargeData: [], // 附加费
      FBAOtherFee: [], // 附加费数据
      propsTotalReceivableData: [
        {
          SettlementConfirmInputWeight: 0,
          CustomerConfirmUnitPrice: 0,
          CustomerConfirmTotalSurcharges: 0,
          CustomerConfirmTotal: 0,
          CustomerConfirmBillWeight: 0,
          SplitWeightRate: 0,
          DeclarationMethod: undefined
        }
      ], // 应收总额
      saveLadding: false,
      timerBlur: null,
      lengthNum: 0,
      lengthNumber: 0,
      colGutterWidth: 0,
      timers: null,
      billWeight: 0, // 汇总计费泡重
      billVolumeWeight: 0, // 汇总计费实重
      throttledResize: null
    }
  },
  computed: {
    getOrderId() {
      return this.orderId
    },
    getLengthNum() {
      return this.lengthNum >= 5
    },
    getLengthNumber() {
      return this.lengthNumber >= 5 || this.lengthNum >= 5
    },
    ...mapGetters(["roles"]),
    // 销售按钮
    getSellRoles() {
      if(this.roles.length === 0) return false
      return this.roles.some((item) => item.includes('销售')) && this.itemsData.SalesmanConfirmFee == false
    },
    getDialogVisible() {
      return this.dialogVisible
    }
  },
  watch: {
    customerData(val) {
      // 子组件内部客户数据
      this.propsCustomerData = deepClone(val)
      this.oldCustomerData = deepClone(val)
      if (this.propsCustomerData.length > 0) {
        this.lengthNum = this.propsCustomerData.length
        this.$nextTick().then(() => {
          if(this.$refs.customerRef) {
            this.$refs.customerRef.$el.addEventListener(
              'blur',
              this.defineBlur,
              true
            )
          }
          clearTimeout(this.timers)
          this.timers = setTimeout(() => {
            this.getColGutterWidth()
          }, 500)
        })
      }
    },
    totalReceivableData(val) {
      this.propsTotalReceivableData = deepClone(val)
    },
    surchargeData(val) {
      this.propsSurchargeData = deepClone(val)
      this.lengthNumber = this.propsSurchargeData.length
    },
    colGutterWidth(val) {
      this.$nextTick(() => {
        const detailsContentDom = this.$refs.detailsContentRef
        if (detailsContentDom) detailsContentDom.setAttribute('style', `--col-gutter-width: ${val}px`)
      })
    }
  },
  created() {
    _getAll().then((res) => {
      this.FBAOtherFee = res
    })
  },
  mounted() {
    window.addEventListener('resize', this.throttledResize)
    this.createThrottledResize()
  },
  beforeDestroy() {
    // 销毁
    clearTimeout(this.timerBlur)
    this.timerBlur = null
    if (this.$refs.customerRef) { this.$refs.customerRef.$el.removeEventListener('blur', this.defineBlur) }
    window.removeEventListener('resize', this.throttledResize)
    clearTimeout(this.timers)
  },
  methods: {
    createThrottledResize() {
      this.getColGutterWidth()
      this.throttledResize = throttle(this.getColGutterWidth, 1000);
    },
    detailClose() {
      this.$emit('detailClose')
    },
    edit() {
      this.saveLadding = true
      const params = {
        OrderId: this.getOrderId,
        customerData: this.propsCustomerData,
        surchargeData: this.propsSurchargeData,
        totalReceivableData: this.propsTotalReceivableData
      }
      this.$emit('detailEdit', params, this.cancelLoading)
    },
    confirmSell() {
      this.saveLadding = true
      this.$emit('confirmSell', this.itemsData.Id, this.cancelLoading)
    },
    cancelLoading() {
      this.saveLadding = false
    },
    getColGutterWidth() {
      this.$nextTick().then(() => {
        if (!this.$refs.customerRef) return
        const colGutter = this.$refs.customerRef.$el.querySelector('.vxe-header--gutter')
        if (colGutter) {
          this.colGutterWidth = colGutter.clientWidth > 0 ? colGutter.clientWidth : 17
        } else {
          this.colGutterWidth = this.getLengthNum ? 15 : 0
        }
      })
    },
    defineBlur(e) {
      clearTimeout(this.timerBlur)
      if (e.target) {
        this.currentInput.value = e.target.value // 输入框的内容
        this.currentInput.field = e.target.getAttribute('name') // 字段
      }
      this.timerBlur = setTimeout(() => {
        this.currentInput.value = ''
        this.currentInput.field = ''
      }, 500)
      // console.log(e,"blur事件");
    },
    // 客户确认数据复选框勾选
    handleSelectionCustomer() {
      const $table = this.$refs.customerRef
      const selectRecords = $table.getCheckboxRecords()
      this.multipleCustomer = selectRecords
    },
    // 复制内容到勾选框
    hanleCheckCopy() {
      const field = this.currentInput.field
      const value = this.currentInput.value
      if (!value) return
      if (this.multipleCustomer.length > 0) {
        const IdList = this.multipleCustomer.map((item) => item.Id)
        this.propsCustomerData = this.propsCustomerData.map((item) => {
          if (IdList.includes(item.Id)) {
            item[field] = value
          }
          return item
        })
        this.updateCustomerGoodsNames()
      }
    },
    // 复制内容到全部
    hanleCheckCopyAll() {
      const value = this.currentInput.value
      if (!value) return
      let cloneCurrentInput = deepClone(this.currentInput)
      this.$confirm('是否复制内容到所有箱?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.propsCustomerData = this.propsCustomerData.map((item) => {
            if (item) item[cloneCurrentInput.field] = cloneCurrentInput.value
            return item
          })
          this.updateCustomerGoodsNames()
          cloneCurrentInput = null
        })
        .catch(() => {
          cloneCurrentInput = null
        })
    },
    // 添加附加费
    handleAddSurcharge() {
      // 限制只能添加3条附加费
      if (this.propsSurchargeData.length === 3) {
        return
      }
      this.propsSurchargeData.push({
        FBAOtherFeeId: null,
        CustomerRemark: '',
        Fee: '',
        Remark: '',
        SysncJS: false
      })
      this.lengthNumber = this.propsSurchargeData.length
    },
    // 移除附加费
    handleDeleteRow(index, data) {
      this.propsSurchargeData.splice(index, 1)
      this.lengthNumber = this.propsSurchargeData.length
    },
    formatCalculateType(value) {
      if (value === 0) return '称重_KG'
      if (value === 1) return '固定'
      return ''
    },
    formatFBAOtherFee(Id, list) {
      // 显示附加费项对应文本
      const findObj = list.find((item) => item.Id == Id)
      return findObj?.Name
    },
    // 附加费项change事件
    changeFBAOtherFee(row) {
      const findFee = this.FBAOtherFee.find((item) => item.Id === row.FBAOtherFeeId)
      // row.JSRemark = findFee.JSRemark;
      // row.CustomerRemark = findFee.CustomerRemark;
      // row.Remark = findFee.Remark;
      // row.SysncJS = findFee.SysncJS;
      this.$set(row, 'JSRemark', findFee.JSRemark)
      this.$set(row, 'CustomerRemark', findFee.CustomerRemark)
      this.$set(row, 'Remark', findFee.Remark)
      this.$set(row, 'SysncJS', findFee.SysncJS)
    },
    // 附加费-整票附加费累加以及应收总额联动
    footerSurchargeMethod({ columns, data }) {
      if (data.length === 0) {
        this.updateTotalSurcharges(0)
        return []
      }
      let surchargeNum = 0
      data.forEach(row => {
        surchargeNum += Number(row.Fee)
      })
      this.$nextTick(() => {
        this.updateTotalSurcharges(surchargeNum)
      })
      return [
        columns.map((column, columnIndex) => {
          if (columnIndex === 0) {
            return '汇总'
          }
          if (columnIndex === 3) {
            return `${this.sumNumGather(data, 'Fee')}`
          }
          return '-'
        })
      ]
    },
    updateTotalSurcharges(surchargeNum) {
      // 附加费总额
      this.propsTotalReceivableData[0].CustomerConfirmTotalSurcharges = surchargeNum
      // 应收总额
      this.changeCustomerConfirmTotal()
    },
    // 更新单价 =》应收总额更新
    changeCustomerConfirmTotal() {
      const propsTotalReceivableData = this.propsTotalReceivableData[0]
      this.propsTotalReceivableData[0].CustomerConfirmTotal = (propsTotalReceivableData.CustomerConfirmBillWeight * propsTotalReceivableData.CustomerConfirmUnitPrice) + propsTotalReceivableData.CustomerConfirmTotalSurcharges
    },
    sumNumGather(list, field) {
      let count = 0
      list.forEach(item => {
        count += Number(item[field])
      })
      return Number(count) >= 0 ? Math.ceil(count) : 0
    },
    // 仓库收货数据汇总
    footerMethodCustomerStore({ columns, data }) {
      return [
        columns.map((column, columnIndex) => {
          if (columnIndex === 0) {
            return '汇总'
          }
          if (columnIndex === 1) {
            return `${this.sumNumGather(data, 'OpInputWeight')}`
          } else if (columnIndex === 5) {
            return `${this.sumNumGather(data, 'VolumeWeight')}`
          }
          return '-'
        })
      ]
    },
    // 客户确认数据汇总
    footerMethodCustomer({ columns, data }) {
      return [
        columns.map((column, columnIndex) => {
          if (columnIndex === 1) {
            return '汇总'
          }
          if (columnIndex === 2) {
            // 计费汇总的实重
            this.billWeight = this.sumNumGather(data, 'BillWeight')
            return `${this.billWeight}`
          } else if (columnIndex === 6) {
            // 计费汇总的泡重
            this.billVolumeWeight = this.sumNumGather(data, 'BillVolumeWeight')
            return `${this.billVolumeWeight}`
          }
          return '-'
        })
      ]
    },
    // 重新获取单价
    getUnitPrice() {
      const paramsData = {
        OrderId: this.itemsData.Id,
        PublicExpressId: this.itemsData.CreateOrderChannelId,
        CustomerId: this.itemsData.CustomerId,
        TransactionTime: this.itemsData.ReceiveTime,
        ZipCode: this.itemsData.ReceiverZipCode,
        gWeight: this.propsTotalReceivableData[0].CustomerConfirmBillWeight,
      }
      _getUnitPrice(paramsData)
        .then((res) => {
          const price = typeof res === 'number' && isFinite(res) ? res : 0
          if (Number(price) >= 0 && this.propsTotalReceivableData[0].CustomerConfirmUnitPrice != price) {
            this.$confirm('是否更新单价?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.propsTotalReceivableData[0].CustomerConfirmUnitPrice = price
            })
          }
        })
    },
    // 重算计费重
    getRecalculateBillingWeight(billWeight, billVolumeWeight) {
      const rate = Number(this.propsTotalReceivableData[0].SplitWeightRate)
      if (rate > 0) {
        // `汇总计费泡重/体积重整数`+（`汇总计费泡重/体积重整数`-`汇总计费实重`）*`分泡系数`
        const CustomerConfirmBillWeight = billVolumeWeight - (billVolumeWeight - billWeight) * rate
        // （最终计费`重量`需要判断`不能小于实重`）不足`1kg`的按`1kg计费`；
        const floorBillWeight = Number(Math.ceil(CustomerConfirmBillWeight))
        this.propsTotalReceivableData[0].CustomerConfirmBillWeight = floorBillWeight > billWeight
          ? floorBillWeight : Number(Math.ceil(billWeight))
      }
      this.getUnitPrice()
    },
    hanleRecalculateBillingWeight() {
      // a.当`汇总计费泡重`大于`汇总计费实重`、b.`分泡系数`不为`空`（数值范围：`0-1`），
      if (this.billVolumeWeight > this.billWeight) {
        this.getRecalculateBillingWeight(this.billWeight, this.billVolumeWeight)
      } else {
        this.getRecalculateBillingWeight(this.billWeight, this.billVolumeWeight)
        // 实重大取实重
        this.propsTotalReceivableData[0].CustomerConfirmBillWeight = this.billWeight
      }
    },
    // 重算计费泡重/最终确认计费重
    hanleRecompute() {
      const CustomerVolumnWeightFactor = this.itemsData.CustomerVolumnWeightFactor
      this.propsCustomerData = this.propsCustomerData.map((item) => {
        if (Number(item.VolumeWeight) >= 0) item.BillVolumeWeight = calculate_VolumeWeight(item.BillLenght, item.BillWidth, item.BillHeight, item.BillVolumeWeight, CustomerVolumnWeightFactor)
        return item
      })
      const rate = Number(this.propsTotalReceivableData[0].SplitWeightRate)
      this.$nextTick(() => {
        if (rate > 0) {
          this.hanleRecalculateBillingWeight()
        } else {
          // 没有分泡系数取：泡重和计费重哪个大取的取哪个
          this.billVolumeWeight > this.billWeight
            ? this.propsTotalReceivableData[0].CustomerConfirmBillWeight = this.billVolumeWeight
            : this.propsTotalReceivableData[0].CustomerConfirmBillWeight = this.billWeight;
          //
          this.getUnitPrice()
        }
      })
      this.updateCustomerGoodsNames()
    },
    // 检测单个更新客户确认数据备注
    updateSingleCustomerGoodsNames(row, field) {
      const currentRow = this.oldCustomerData.find((item) => item.BoxNumber === row.BoxNumber)
      if (!currentRow) return
      if (currentRow[field] == row[field]) return
      _getBoxlDCRData(row).then((result) => {
        const res = typeof result === 'string' ? result : result.data
        this.$set(row, 'CustomerGoodsNames', res);
      })
      // 更新的旧表格数据
      this.$nextTick(() => {
        this.oldCustomerData = deepClone(this.propsCustomerData)
      })
    },
    // 批量更新客户确认数据备注
    updateCustomerGoodsNames() {
      const changeBoxNumbers = this.getDifferentBoxNumbers(this.oldCustomerData, this.propsCustomerData)
      if (changeBoxNumbers.length === 0) return
      const paramsArr = this.propsCustomerData.filter(item => changeBoxNumbers.indexOf(item.BoxNumber) !== -1)
      for (const params of paramsArr) {
        _getBoxlDCRData(params).then((result) => {
          const index = this.propsCustomerData.findIndex((item) => item.BoxNumber === params.BoxNumber)
          const res = typeof result === 'string' ? result : result.data
          this.$set(this.propsCustomerData[index], 'CustomerGoodsNames', res);
        })
      }
      // 更新的旧表格数据
      this.$nextTick(() => {
        this.oldCustomerData = deepClone(this.propsCustomerData)
      })
    },
    // 对比原/变的箱子数据
    getDifferentBoxNumbers(arr1, arr2) {//原始值、改变值
      if (arr1.length !== arr2.length) return this.$message.error('数据有错')
      const originArr = arr1.map(item => ({
        BoxNumber: item.BoxNumber,
        BillWeight: item.BillWeight,
        BillLenght: item.BillLenght,
        BillWidth: item.BillWidth,
        BillHeight: item.BillHeight,
        BillVolumeWeight: item.BillVolumeWeight
      }))
      const changeArr = arr2.map(item => ({
        BoxNumber: item.BoxNumber,
        BillWeight: item.BillWeight,
        BillLenght: item.BillLenght,
        BillWidth: item.BillWidth,
        BillHeight: item.BillHeight,
        BillVolumeWeight: item.BillVolumeWeight
      }))
      const diffBoxNumbers = [];
      // 遍历第一个数组中的对象
      for (let i = 0; i < originArr.length; i++) {
        const originObj = originArr[i];
        const changeObj = changeArr[i];
        // 比较对象的属性值
        if (
          originObj.BoxNumber != changeObj.BoxNumber ||
          originObj.BillWeight != changeObj.BillWeight ||
          originObj.BillLenght != changeObj.BillLenght ||
          originObj.BillWidth != changeObj.BillWidth ||
          originObj.BillHeight != changeObj.BillHeight ||
          originObj.BillVolumeWeight != changeObj.BillVolumeWeight
        ) {
          diffBoxNumbers.push(originObj.BoxNumber);
        }
      }
      return diffBoxNumbers;
    }
  }
}
</script>
<style lang="less">
  @import './style/detail-iconme.less';
</style>
