<!--
  查看空派收入-明细
 -->
<template>
  <el-dialog top="0" width="1300px" 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="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 }"
            :footer-method="footerMethodCustomer">
            <vxe-column field="BoxNumber" title="箱号" :min-width="140" />
            <vxe-column field="BillWeight" title="计费实重KG" :min-width="110" />
            <vxe-column field="BillLenght" title="长CM" :min-width="80" />
            <vxe-column field="BillWidth" title="宽CM" :min-width="80" />
            <vxe-column field="BillHeight" title="高CM" :min-width="80" />
            <vxe-column field="BillVolumeWeight" title="计费泡重" :width="120" />
            <vxe-column field="CustomerGoodsNames" title="操作备注" :width="140" fixed="right">
            </vxe-column>
          </vxe-table>
          <div class="flex cost-warp">
            <span>最终确认计费重</span>
            <el-input v-model="propsTotalReceivableData[0].CustomerConfirmBillWeight" @blur="blurCustomerConfirmBillWeight" class="heavy" placeholder="请输入内容"
              :disabled="enabledVisible" />
            <div class="cost weightRate" :class="{ 'mr17': getLengthNum }">-</div>
          </div>
          <div class="cost-warp-2 pl-0">
            <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 pl-0">
            <div />
            <div class="cost" :class="{ 'mr17': getLengthNum }">
              <div class="w-48 lih-36">
                {{ propsTotalReceivableData[0].SplitWeightRate }}
              </div>
            </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 }"
            :footer-method="footerSurchargeMethod">
            <vxe-column field="Id" title="附加费项" :min-width="100">
              <template #default="{ row }">
                <!-- 不编辑显示的文本 -->
                <span>{{ row.FBAOtherFeeId | formatFBAOtherFee(FBAOtherFee) }}</span>
              </template>
            </vxe-column>
            <vxe-column field="CustomerRemark" title="附加费标准" :min-width="100">
              <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" />
            <vxe-column field="Remark" title="备注" :min-width="90" />
            <vxe-column field="SysncJS" title="是否计入销售成本" :width="140">
              <template #default="{ row }">
                <vxe-checkbox v-model="row.SysncJS" :disabled="enabledVisible" size="medium">{{
                  row.SysncJS ? "是" : "否"
                }}</vxe-checkbox>
              </template>
            </vxe-column>
            <!-- <vxe-column v-if="getLengthNum" :width="17" /> -->
          </vxe-table>
          <div class="flex cost-warp">
            <el-input v-model="propsTotalReceivableData[0].ApprovalNumber" :disabled="enabledVisible" class="number"
              placeholder="特殊申请审批编号" />
          </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="单价" />
            <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" @click="detailClose">关闭</el-button>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

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

export default {
  name: 'DetailIconme',
  components: { DefineDescriptions },
  props: {
    width: {
      type: String,
      default: '65%'
    },
    title: String,
    dialogVisible: {
      type: Boolean,
      default: false
    },
    itemsData: {
      type: Object,
      default: () => { }
    },
    customerData: {
      type: Array,
      default: () => []
    },
    surchargeData: {
      type: Array,
      default: () => []
    },
    totalReceivableData: {
      type: Array,
      default: () => []
    },
    SurchargeType: ''
  },
  data() {
    return {
      enabledVisible: true,
      items: [
        { field: 'ReceiveTimeStr', label: '收货日期' },
        { field: 'ForecastTime', label: '预报时间' },
        { field: 'CompanyName', label: '客户名称' },
        { field: 'CustomerOrderNo', label: '客户单号' },
        { field: 'SystemNo', label: '行运易单号' },
        { field: 'PublicName', label: '渠道' },
        { field: 'ReceiverCountryCode', label: '国家' },
        { field: 'BoxQty', label: '件数' },
        { field: 'ReceiverZipCode', label: '收件人邮编', width: 140 }
      ], // 基本信息
      propsCustomerData: [],
      propsSurchargeData: [], // 附加费
      FBAOtherFee: [], // 附加费数据
      propsTotalReceivableData: [
        {
          SettlementConfirmInputWeight: 0,
          CustomerConfirmUnitPrice: 0,
          CustomerConfirmTotalSurcharges: 0,
          CustomerConfirmTotal: 0,
          CustomerConfirmBillWeight: 0,
          SplitWeightRate: 0,
          DeclarationMethod: undefined
        }
      ], // 应收总额
      lengthNum: 0,
      colGutterWidth: 0,
      timers: null,
      billWeight: 0, // 汇总计费泡重
      billVolumeWeight: 0, // 汇总计费实重
      throttledResize: null
    }
  },
  computed: {
    getLengthNum() {
      return this.lengthNum >= 5
    },
  },
  filters: {
    // 显示附加费项对应文本
    formatFBAOtherFee(Id, list) {
      if(list.length === 0) return ''
      // 显示附加费项对应文本
      const findObj = list.find((item) => item.Id == Id)
      return findObj?.Name || ''
    }
  },
  watch: {
    customerData(val) {
      // 子组件内部客户数据
      this.propsCustomerData = deepClone(val)
      if (this.propsCustomerData.length > 0) {
        this.lengthNum = this.propsCustomerData.length
        // 设置滚动条宽度
        this.$nextTick().then(() => {
          clearTimeout(this.timers)
          this.timers = setTimeout(() => {
            this.getColGutterWidth()
          }, 500)
        })
      }
    },
    totalReceivableData(val) {
      this.propsTotalReceivableData = deepClone(val)
    },
    surchargeData(val) {
      this.propsSurchargeData = deepClone(val)
    },
    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() {
    // 销毁
    window.removeEventListener('resize', this.throttledResize)
    clearTimeout(this.timers)
  },
  methods: {
    createThrottledResize() {
      this.getColGutterWidth()
      this.throttledResize = throttle(this.getColGutterWidth, 1000);
    },
    detailClose() {
      this.$emit('detailClose')
    },
    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
        }
      })
    },
    // 附加费-整票附加费累加以及应收总额联动
    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 === 2) {
            return `${this.sumNumGather(data, 'Fee')}`
          }
          return '-'
        })
      ]
    },
    updateTotalSurcharges(surchargeNum) {
      // 附加费总额
      this.propsTotalReceivableData[0].CustomerConfirmTotalSurcharges = surchargeNum
      // 应收总额
      this.changeCustomerConfirmTotal()
    },
    blurCustomerConfirmBillWeight() {
      this.changeCustomerConfirmTotal()
    },
    // 更新单价 =》应收总额更新
    changeCustomerConfirmTotal() {
      const propsTotalReceivableData = this.propsTotalReceivableData[0]
      const CustomerConfirmTotal = (propsTotalReceivableData.CustomerConfirmBillWeight * propsTotalReceivableData.CustomerConfirmUnitPrice) + propsTotalReceivableData.CustomerConfirmTotalSurcharges
      this.propsTotalReceivableData[0].CustomerConfirmTotal = ceilToDecimals(CustomerConfirmTotal, 3)
    },
    // 累加计算
    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 === 0) {
            return '汇总'
          }
          if (columnIndex === 1) {
            // 计费汇总的实重
            const billWeight = this.sumNumGather(data, 'BillWeight')
            return `${billWeight}`
          } else if (columnIndex === 5) {
            // 计费汇总的泡重
            const billVolumeWeight = this.sumNumGather(data, 'BillVolumeWeight')
            return `${billVolumeWeight}`
          }
          return '-'
        })
      ]
    },
  }
}
</script>
<style lang="less">
  @import './style/detail-iconme.less';
</style>
