<template>
  <div>
    <div class="app-container">
      <div class="filter-container">
        <el-form :inline="true" class="demo-form-inline" ref="elFormRef">
          <el-form-item label="收货日期">
            <div class="block">
              <el-date-picker
                v-model="pagerDto._Range_ReceiveTime"
                type="daterange"
                range-separator="~"
                value-format="yyyy-MM-dd"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              />
            </div>
          </el-form-item>
          <el-form-item label="客户名称">
            <el-select
              v-model="pagerDto._Eq_CustomerId"
              placeholder="所属客户"
              clearable
              filterable
            >
              <el-option
                v-for="item in Customers"
                :key="item.Id"
                :label="item.CompanyName"
                :value="item.Id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="单号">
            <MultipleNumber @getNumber="getNumber" />
          </el-form-item>
          <el-form-item label="渠道">
            <el-select
              v-model="pagerDto._Eq_CreateOrderChannelId"
              placeholder="下单渠道"
              clearable
              filterable
            >
              <el-option
                v-for="item in publicChannel"
                :key="item.Id"
                :label="item.Name"
                :value="item.Id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="国家">
            <el-select
              v-model="pagerDto._Eq_ReceiverCountryCode"
              clearable
              filterable
              auto-complete="false"
              style="width: 290px"
              fillter
            >
              <el-option
                v-for="(item, index) in serachCountryList"
                :key="index"
                :label="item.CnName + ' ' + item.Code + ' ' + item.EnName"
                :value="item.Code"
              >
                <span
                  style="float: left"
                >{{ item.CnName }}
                  <span style="color: #8492a6; font-size: 10px">{{
                    item.EnName
                  }}</span>
                </span>
                <span style="float: right">{{ item.Code }}</span>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="销售">
            <el-select
              v-model="pagerDto._Eq_SalesmanUserId"
              placeholder="所属销售"
              clearable
              filterable
            >
              <el-option
                v-for="item in Users"
                :key="item.Id"
                :label="item.NickName"
                :value="item.Id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="操作人">
            <el-select
              v-model="pagerDto._Eq_SettlementConfirmUserName"
              placeholder="操作人"
              clearable
              filterable
            >
              <el-option
                v-for="item in Users"
                :key="item.Id"
                :label="item.NickName"
                :value="item.NickName"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="是否确认">
            <el-select
              v-model="pagerDto._Eq_IsConfim"
              placeholder="是否确认"
              clearable
              filterable
            >
              <el-option
                v-for="item in SimpleChoice"
                :key="item.Id"
                :label="item.Name"
                :value="item.Id"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button
              icon="el-icon-search"
              size="small"
              type="primary"
              :loading="serachLadding"
              @click="search"
            >搜索</el-button>
          </el-form-item>
        </el-form>
        <div class="batch-warp">
          <el-button
            type="success"
            size="small"
            plain
            @click="hanleSurcharges"
          >批量修改附加费</el-button>
          <el-button
            type="primary"
            size="small"
            plain
            @click="hanleHeavyBilling"
          >批量修改计费重</el-button>
          <el-button
            type="success"
            size="small"
            plain
            :loading="saveLadding"
            @click="hanleToEnd"
          >生成结算计费</el-button>
           <el-button
            type="primary"
            size="small"
            plain
            :loading="saveLadding"
            @click="ExportEnd"
          >导出结算信息</el-button>
        </div>
        <!-- 表格 -->
        <vxe-grid
          ref="gridTableRef"
          class="settlement-table"
          v-bind="gridTableOptions"
          @checkbox-change="handleSelectionChange"
          @checkbox-all="handleSelectionChange"
          @edit-actived="editActived"
        >
          <template #edit_SettlementSplitWeightRate="scope">
            <el-input v-model="scope.row.SettlementSplitWeightRate" v-decimal-bubble-input class="define-input" />
          </template>
          <template #edit_SettlementConfirmInputWeight="scope">
            <el-input v-model="scope.row.SettlementConfirmInputWeight" v-decimal-input class="define-input" />
          </template>
          <template #edit_SettlementConfirmVolumeWeight="scope">
            <el-input v-model="scope.row.SettlementConfirmVolumeWeight" v-decimal-input class="define-input" />
          </template>
          <template #header_SettlementConfirmBillWeight="{ row }">
            {{ row }}结算计费重
            <el-button
              v-show="isEdit"
              type="primary"
              size="mini"
              style="padding: 4px 6px;"
              :loading="returnLoading"
              round
              @click="recalculateChargeTotal">
              重算
            </el-button>
          </template>
          <template #edit_SettlementConfirmBillWeight="scope">
            <el-input v-model="scope.row.SettlementConfirmBillWeight" v-decimal-input class="define-input" @blur="balanceTotal(scope)" />
          </template>
          <template #edit_SettlementConfirmUnitPrice="scope">
            <el-input v-model="scope.row.SettlementConfirmUnitPrice" v-decimal-input class="define-input" @blur="balanceTotal(scope)" />
          </template>
          <!-- 附加费 1 -->
          <template #default_FBAOtherFeeId_1="{row}">
            {{ formatFBAOtherFee(row.FBAOtherFeeId_1) }}
          </template>
          <template #edit_FBAOtherFeeId_1="scope">
            <vxe-select v-model="scope.row.FBAOtherFeeId_1" @change="changeFBAOtherFee(scope,'1')">
              <vxe-option v-for="item in FBAOtherFee" :key="item.Id" :value="item.Id" :label="item.Name" />
            </vxe-select>
          </template>
          <template #edit_Fee_1="scope">
            <el-input v-model="scope.row.Fee_1" v-decimal-input class="define-input" @blur="surchargeTotal(scope)" />
          </template>
          <!-- 2 -->
          <template #default_FBAOtherFeeId_2="{row}">
            {{ formatFBAOtherFee(row.FBAOtherFeeId_2) }}
          </template>
          <template #edit_FBAOtherFeeId_2="scope">
            <vxe-select v-model="scope.row.FBAOtherFeeId_2" @change="changeFBAOtherFee(scope,'2')">
              <vxe-option v-for="item in FBAOtherFee" :key="item.Id" :value="item.Id" :label="item.Name" />
            </vxe-select>
          </template>
          <template #edit_Fee_2="scope">
            <el-input v-model="scope.row.Fee_2" v-decimal-input class="define-input" @blur="surchargeTotal(scope)" />
          </template>
          <!-- 3 -->
          <template #default_FBAOtherFeeId_3="{row}">
            {{ formatFBAOtherFee(row.FBAOtherFeeId_3) }}
          </template>
          <template #edit_FBAOtherFeeId_3="scope">
            <vxe-select v-model="scope.row.FBAOtherFeeId_3" @change="changeFBAOtherFee(scope,'3')">
              <vxe-option v-for="item in FBAOtherFee" :key="item.Id" :value="item.Id" :label="item.Name" />
            </vxe-select>
          </template>
          <template #edit_Fee_3="scope">
            <el-input v-model="scope.row.Fee_3" v-decimal-input class="define-input" @blur="surchargeTotal(scope)" />
          </template>
          <!--  -->
          <template #actions="{ row }">
            <template v-if="$refs.gridTableRef.isActiveByRow(row)">
              <div class="define-edit">
                <el-button v-show="!row.IsSettlementConfirm" type="primary" size="mini" :loading="row.editLoading" @click="hanleEditRow(row)">修改</el-button>
                <el-button type="danger" size="mini" @click="cancelRowEvent(row)">取消</el-button>
              </div>
            </template>
            <template v-else>
              <div class="define-edit">
                <el-dropdown placement="bottom">
                  <span class="el-dropdown-link">
                    {{ row.IsSettlementConfirm ? '已确认' : '未确认' }}<i class="el-icon-arrow-down el-icon--right" />
                  </span>
                  <el-dropdown-menu slot="dropdown" style="width: 100px;">
                    <div class="grid-btn-warp">
                      <el-button v-show="!row.IsSettlementConfirm" type="primary" size="small" class="view-btn" :loading="row.confirmLoading" @click="hanleConfirmRow(row)">确认</el-button>
                      <!-- <el-button v-show="!row.IsSettlementConfirm" type="warning" size="small" class="view-btn" :loading="row.editLoading" @click="hanleEditRow(row)">修改</el-button> -->
                      <!-- <el-button type="success" size="small" class="view-btn" :loading="row.viewLoading" @click="openDetails(row)">查看</el-button> -->
                    </div>
                  </el-dropdown-menu>
                </el-dropdown>
                <el-button type="text" size="small" @click="openIconmeDetails(row)" :loading="row.detailLoading" class="details">查看</el-button>
              </div>
            </template>
          </template>
        </vxe-grid>
        <el-pagination
          :page-sizes="[20, 50, 100, 150, 200]"
          :current-page="pagerDto.PageIndex"
          :page-size="pagerDto.PageSize"
          background
          layout="prev, pager, next ,total ,jumper,sizes,slot "
          :total="pagerDto.total"
          @current-change="pagerSerach"
          @size-change="sizeChange"
        />
      </div>
    </div>
    <!-- 收入详情 -->
    <ViewDetailIconme
      title="详情"
      :dialog-visible.sync="showIconmeDetails"
      :items-data="itemsData"
      :customer-data="customerData"
      :surcharge-data="surchargeData"
      :total-receivable-data="totalReceivableData"
      surcharge-type="收入"
      @detailClose="handleIconmeDetailClose"
    />
    <SurchargesList
      title="批量修改附加费"
      :dialog-visible.sync="surchargesVisible"
      :table-data="surchargesData"
      :table-column="SurchargesColumn"
      @close="hanleCloseSurcharges"
      @edit="hanleEditSurcharges"
    />
    <HeavyBillingList
      title="批量修改计费"
      :dialog-visible.sync="heavyBillingVisible"
      :table-data="heavyBillingData"
      :table-column="HeavyBillingColumn"
      @close="hanleCloseHeavyBilling"
      @edit="hanleEditHeavyBilling"
    />
  </div>
</template>
<script>
import {
  _getSettlementConfirmList,
  _getSettlementConfirm,
  _updateSettlementConfirm,
  _goToEnd,
  _getUnitPrice,
  _updateBatchSettlementWeight,
  _getBatchSettlementWeight,
  _getBatchSettlementIncidenta,
  _updateBatchSettlementIncidenta,
  _SettlementConfirmOperation,
  _updateSettlementConfirmForTable,
_getCustomerConfirm
} from '@/api/fba/Receiving'
import { addDays, DateFormat } from '@/api/timehelp'
import {
  _getCountries,
  _getAllPublic,
  _getDeliverChannel,
  _getCustomers,
  _getFBAChannel,
  _getAllUsers
} from '@/api/baseInfo'
// import DetailISettlement from './components/DetailISettlement.vue'
import SurchargesList from './components/SurchargesList.vue'
import HeavyBillingList from './components/HeavyBillingList.vue'
import { _getAll } from '@/api/order/fba'
import MultipleNumber from './components/multipleNumber.vue'
import { defineThrottle } from '@/utils/index';
import ViewDetailIconme from "./components/ViewDetailIconme.vue";
import axios from "axios";

export default {
  name: 'Settlement',
  components: { SurchargesList, HeavyBillingList, MultipleNumber, ViewDetailIconme },
  // vue指令
  directives: {
    decimalInput: {
      bind: function(el, binding, vnode) {
        el.handleInput = function handleInput(event) {
          const input = event.target
          const value = input.value
          // 移除非数字字符和超过两位小数的部分
          const newValue = value.replace(/[^0-9.]/g, '').replace(/^\D*(\d*(?:\.\d{0,3})?).*$/g, '$1')
          input.value = newValue
          // 更新双向绑定
          vnode.componentInstance.$emit('input', newValue)
        }
        el.addEventListener('input', el.handleInput)
      },
      unbind(el) {
        el.removeEventListener('input', el.handleInput)
      }
    }
  },
  data() {
    return {
      sData: [],
      showBtn: false,
      serachLadding: false,
      saveLadding: false,
      SimpleChoice: [
        { Id: 1, Name: '是' },
        { Id: 2, Name: '否' }
      ],
      Customers: [],
      publicChannel: [],
      serachCountryList: [],
      Users: [],
      pagerDto: {
        PageIndex: 1,
        PageSize: 20,
        total: 0,
        QuerySort: [{ Field: 'Id', IsDesc: true }],
        _Range_ReceiveTime: []
      },
      OrderId: 0,
      ids: [],
      // 详情
      showDetails: false, // 收入明细
      isSettlementConfirm: false, // 查看是否编辑状态
      itemsData: {
        ReceiveTimeStr: '',
        CompanyName: '',
        CustomerOrderNo: '',
        SystemNo: '',
        PublicName: '',
        ReceiverCountryCode: '',
        BoxQty: 0
      },
      storehouseData: [], // 仓库收货数据
      customerData: [], // 客户确认数据
      surchargeData: [], // 附加费
      totalReceivableData: [
        {
          SettlementConfirmInputWeight: 0.0,
          SettlementConfirmUnitPrice: 0.0,
          CustomerConfirmTotalSurcharges: 0.0,
          CustomerConfirmTotal: 0.0,
          CustomerConfirmBillWeight: 0.0
        }
      ], // 应收总额
      currentInput: {
        value: '',
        field: ''
      }, //
      multipleCustomer: [], // 客户确认数据选中数据
      surchargesVisible: false, // 附加费弹窗
      surchargesData: [], // 附加费列表数据
      heavyBillingVisible: false,
      heavyBillingData: [],
      HeavyBillingColumn: [
        { key: 1, type: 'checkbox', field: 'OrderId', width: 45 },
        { key: 'OrderNo', field: 'OrderNo', title: '订单号', width: 180 },
        {
          key: 'Weight',
          field: 'Weight',
          title: '最终计费重',
          editRender: { autofocus: '.vxe-input--inner' }
        },
        {
          key: 'UnitPrice',
          field: 'UnitPrice',
          title: '单价',
          editRender: { autofocus: '.vxe-input--inner' }
        }
      ], // 结算批量修改计费-key需唯一值
      SurchargesColumn: [
        { key: 'OrderNo', field: 'OrderNo', title: '订单号', width: 180 },
        {
          key: 'FBAOtherFeeId',
          field: 'FBAOtherFeeId',
          title: '附加费项',
          isSelect: true,
          editRender: {}
        },
        {
          key: 'CustomerRemark',
          field: 'CustomerRemark',
          title: '附加费标准',
          editRender: { autofocus: '.define-input .vxe-input--inner' }
        },
        {
          key: 'Fee',
          field: 'Fee',
          title: '整票附加费',
          editRender: { autofocus: '.define-input .vxe-input--inner' }
        },
        {
          key: 'Remark',
          field: 'Remark',
          title: '备注',
          editRender: { autofocus: '.define-input .vxe-input--inner' }
        },
        // {
        //   key: "SysncJS",
        //   field: "SysncJS",
        //   title: "是否记入结算价",
        //   deCheckbox: true,
        //   width: 130,
        // },
        { key: '4Actions', field: null, title: '操作', width: 80 }
      ], // 结算批量修改附加费-key需唯一值
      FBAOtherFee: [],
      gridTableOptions: {
        border: true,
        resizable: true,
        showOverflow: false,
        keepSource: true,
        height: 600,
        align: 'left',
        editConfig: { trigger: 'click', mode: 'row', autoClear: false },
        rowClassName({ row }) {
          if(Number(row.Profit) < 0) return 'profit-bj'
        },
        columns: [
          { type: 'checkbox', width: 45 },
          { field: 'ReceiveTimeStr', title: '收货日期', minWidth: 100 },
          { field: 'CompanyName', title: '客户名称', minWidth: 100 },
          { field: 'CustomerOrderNo', title: '客户单号', minWidth: 150 },
          { field: 'SystemNo', title: '行运易单号', minWidth: 150 },
          { field: 'PublicName', title: '渠道', minWidth: 150 },
          { field: 'ReceiverCountryCode', title: '国家', minWidth: 100 },
          { field: 'BoxQty', title: '收货件数', minWidth: 100 },
          { field: 'ApprovalNumber', title: '特殊审批编号', minWidth: 110 },
          { field: 'OPInputWeight', title: '收货实重', minWidth: 100 },
          { field: 'OPVolumeWeight', title: '收货泡重', minWidth: 100 },
          {
            field: 'SettlementConfirmInputWeight',
            title: '结算实重',
            width: 110,
          },
          {
            field: 'SettlementConfirmVolumeWeight',
            title: '结算泡重',
            width: 110,
          },
          // 编辑---
          {
            field: 'SettlementSplitWeightRate',
            title: '结算分泡系数',
            width: 130,
            editRender: { autofocus: '.define-input .el-input__inner' },
            slots: { edit: 'edit_SettlementSplitWeightRate' }
          },
          {
            field: 'SettlementConfirmBillWeight',
            title: '结算计费重',
            width: 175,
            editRender: { autofocus: '.define-input .el-input__inner' },
            slots: { edit: 'edit_SettlementConfirmBillWeight', header: 'header_SettlementConfirmBillWeight' }
          },
          {
            field: 'SettlementConfirmUnitPrice',
            title: '结算单价',
            width: 120,
            editRender: { autofocus: '.define-input .el-input__inner' },
            slots: { edit: 'edit_SettlementConfirmUnitPrice' }
          },
          {
            field: 'FBAOtherFeeId_1',
            title: '附加费项1',
            width: 120,
            editRender: {
              // name: '$select',
              // props: {
              //   options: [
              //     { value: 'Id', label: '木制品' }
              //   ]
              // }
            },
            slots: { default: 'default_FBAOtherFeeId_1', edit: 'edit_FBAOtherFeeId_1' }
          },
          {
            field: 'Fee_1',
            title: '附加费1金额',
            width: 120,
            slots: { edit: 'edit_Fee_1' },
            editRender: { autofocus: '.define-input .el-input__inner' }
          },
          {
            field: 'Remark_1',
            title: '附加费1备注',
            width: 120,
            editRender: {
              name: '$input'
            }
          },
          {
            field: 'FBAOtherFeeId_2',
            title: '附加费项2',
            width: 120,
            editRender: {},
            slots: { default: 'default_FBAOtherFeeId_2', edit: 'edit_FBAOtherFeeId_2' }
          },
          {
            field: 'Fee_2',
            title: '附加费2金额',
            width: 120,
            slots: { edit: 'edit_Fee_2' },
            editRender: { autofocus: '.define-input .el-input__inner' }
          },
          {
            field: 'Remark_2',
            title: '附加费2备注',
            width: 120,
            editRender: {
              name: '$input'
            }
          },
          {
            field: 'FBAOtherFeeId_3',
            title: '附加费项3',
            width: 120,
            editRender: {},
            slots: { default: 'default_FBAOtherFeeId_3', edit: 'edit_FBAOtherFeeId_3' }
          },
          {
            field: 'Fee_3',
            title: '附加费3金额',
            width: 120,
            slots: { edit: 'edit_Fee_3' },
            editRender: { autofocus: '.define-input .el-input__inner' }
          },
          {
            field: 'Remark_3',
            title: '附加费3备注',
            width: 120,
            editRender: {
              name: '$input'
            }
          },
          // ---编辑
          { field: 'SettlementConfirmTotalSurcharges', title: '附加费总额', width: 90 },
          { field: 'SettlementConfirmTotal', title: '结算总额', width: 90 },
          { field: 'Profit', title: '毛利', minWidth: 80 },
          { title: '操作', slots: { default: 'actions' }, width: 140, fixed: 'right' }
        ],
        data: []// 数据源
      },
      isEdit: false,// 表格编辑状态
      returnLoading: false,
      throttledResize: null,
      // 收入详情
      showIconmeDetails: false
    }
  },
  created() {
    var end = addDays(new Date(), 0)
    var start = addDays(end, -1)
    this.pagerDto._Range_ReceiveTime = [
      DateFormat(start, 'yyyy-MM-dd'),
      DateFormat(end, 'yyyy-MM-dd')
    ]

    _getCountries().then((r) => {
      this.countryList = r
      this.serachCountryList = Object.assign(r)
    })
    _getAllPublic().then((r) => {
      this.publicChannel = r
    })
    _getCustomers().then((r) => {
      this.Customers = r
    })
    _getAllUsers().then((r) => {
      this.Users = r
    })
    _getAll().then((res) => {
      this.FBAOtherFee = res
    })
  },
  mounted() {
    this.createThrottledResize()
    window.addEventListener('resize', this.throttledResize)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.throttledResize)
  },
  methods: {
    createThrottledResize() {
      this.handleResize()
      this.throttledResize = defineThrottle(this.handleResize, 1000); // 使用lodash的throttle方法，设置节流的时间间隔为500ms
    },
    handleResize: function () {
      if(this.$refs.elFormRef) {
        this.$refs.elFormRef.$nextTick(() => {
          const viewportHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
          const offsetHeight = this.$refs.elFormRef.$el.offsetHeight || 0
          const currentHeight = viewportHeight - (206 + offsetHeight)
          this.gridTableOptions.height = Number(currentHeight) >=0 ? currentHeight : 600
          if(currentHeight < 600) this.gridTableOptions.height = 600
        })
      }
    },
    // 复选框Id
    handleSelectionChange(val) {
      this.ids = val.records.map(item => item.Id)
    },
    getData() {
      this.serachLadding = true
      _getSettlementConfirmList(this.pagerDto)
        .then((response) => {
          // this.sData = response.Result
          const ResultArr = response.Result || []
          this.gridTableOptions.data = ResultArr
          this.insertTableData(ResultArr)
          this.pagerDto.total = response.TotalCount
          this.serachLadding = false
        })
        .finally((response) => {
          this.serachLadding = false
        })
    },
    // 结算计费重
    getRecalculateCharge(settlementConfirmVolumeWeight, settlementConfirmInputWeight, weightRate) {
      // 结算实重比泡重大的时候,取结算实重
      if(Number(settlementConfirmInputWeight) >= Number(settlementConfirmVolumeWeight)) return Number(settlementConfirmInputWeight)
      // 抛重/体积重整数-（抛重/体积重整数-实重）*分泡系数
      const recalculateChargeWeight = Number(Math.ceil(settlementConfirmVolumeWeight)) - (Number(Math.ceil(settlementConfirmVolumeWeight)) - Number(Math.ceil(settlementConfirmInputWeight))) * weightRate
      const ceilRecalculateChargeWeight = Math.ceil(recalculateChargeWeight)
      const newRecalculateChargeWeight = ceilRecalculateChargeWeight > settlementConfirmInputWeight ?
            ceilRecalculateChargeWeight : Math.ceil(settlementConfirmInputWeight);
      return Number.isInteger(newRecalculateChargeWeight) ? newRecalculateChargeWeight : 0;
    },
    formatFBAOtherFee(Id) {
      // 显示附加费项对应文本
      const findObj = this.FBAOtherFee.find((item) => item.Id == Id)
      return findObj?.Name
    },
    // 附加费项change事件
    changeFBAOtherFee(scope, type) {
      const findFee = this.FBAOtherFee.find(
        (item) => item.Id === scope.row[`FBAOtherFeeId_${type}`]
      )
      this.$set(scope.row, `Fee_${type}`, findFee.Fee)
      this.$set(scope.row, `CustomerRemark_${type}`, findFee.CustomerRemark)
      this.$set(scope.row, `Remark_${type}`, findFee.Remark)
      this.$set(scope.row, `SysncJS_${type}`, findFee.SysncJS)
      this.balanceTotal(scope)
      this.$refs.gridTableRef.updateStatus(scope)
    },
    getInsertData(surchargesData) {
      const flattenedData = {}
      surchargesData.forEach((obj, index) => {
        for (const key in obj) {
          flattenedData[`${key}_${index + 1}`] = obj[key]
        }
      })
      return flattenedData
    },
    // 向表格插入数据
    async insertTableData(dataList) {
      const ids = dataList.map(item => item.Id)
      _getBatchSettlementIncidenta(ids).then(result => {
        dataList.forEach((item, index) => {
          if (result.some(i2 => i2.OrderId === item.Id)) {
            const filterData = result.filter(i3 => i3.OrderId === item.Id)
            const data = this.getInsertData(filterData)
            const newData = Object.assign({ ...item }, data)
            this.gridTableOptions.data[index] = { ...newData }
            // 更新表格数据
          }
        })
        this.$refs.gridTableRef.reloadData(this.gridTableOptions.data)
      })
    },
    // 扁平化为数组
    flatteningArr(data) {
      const resultArr = []
      let newResultArr = []
      const flatteningObj = {}
      Object.keys(data).forEach(item => {
        if (item.split('_').length === 2) {
          flatteningObj[item] = data[item]
        }
      })
      for (const key in data) {
        const match = key.match(/^(.*?)_(\d+)$/)
        if (match) {
          const prefix = match[1]
          const suffix = match[2]
          const index = parseInt(suffix) - 1
          if (!resultArr[index]) {
            resultArr[index] = {}
          }
          resultArr[index][prefix] = data[key]
        }
      }
      if (resultArr.length > 0) {
        newResultArr = resultArr.map(item => {
          if (!item.OrderId) item.OrderId = data['OrderId_1'] || data['OrderId_2'] || data['OrderId_3']
          if (!item.OrderNo) item.OrderNo = data['OrderNo_1'] || data['OrderNo_2'] || data['OrderNo_3']
          return item
        })
      }
      return newResultArr
    },
    // 修改当前行编辑内容
    hanleEditRow(rowData) {
      this.$set(rowData, 'editLoading', true)
      const data = this.flatteningArr(rowData)
      const params = {
        OrderId: rowData.Id,
        SettlementSplitWeightRate: rowData.SettlementSplitWeightRate,
        SettlementConfirmBillWeight: rowData.SettlementConfirmBillWeight,
        SettlementConfirmUnitPrice: rowData.SettlementConfirmUnitPrice,
        incidentals: data
      }
      _updateSettlementConfirmForTable(params).then(() => {
        this.$message({ type: 'success', message: '修改成功！' })
      }).finally(() => {
        rowData.editLoading = false
        this.$refs.gridTableRef.clearActived()
        this.isEdit = false
      })
    },
    // 确认
    hanleConfirmRow(row) {
      this.$set(row, 'confirmLoading', true)
      this.$confirm('是否确认该条数据?', '正在确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        _SettlementConfirmOperation(row.Id).then(() => {
          this.$message({ type: 'success', message: '已确认成功！' })
        }).finally(() => {
          row.confirmLoading = false
          this.search()
        })
      })
    },
    // 更新附加费总额
    surchargeTotal(scope) {
      const data = this.flatteningArr(scope.row)
      let surchargeNum = 0
      data.forEach((row) => {
        if (row.Fee) {
          surchargeNum += Number(row.Fee)
        }
      })
      this.$set(scope.row, 'SettlementConfirmTotalSurcharges', surchargeNum)
    },
    // 表格激活编辑-事件
    editActived() {
      this.isEdit = true
    },
    balanceTotal(scope) {
      this.surchargeTotal(scope)
      // 更新结算总额
      this.updateTotalSurcharges(scope)
    },
    updateTotalSurcharges(scope) {
      const SettlementConfirmTotalSurcharges = (scope.row.SettlementConfirmBillWeight * scope.row.SettlementConfirmUnitPrice) + scope.row.SettlementConfirmTotalSurcharges
      const newSettlementConfirmTotalSurcharges =
        Number(SettlementConfirmTotalSurcharges) >=0 ? SettlementConfirmTotalSurcharges.toFixed(2) : 0
      this.$set(scope.row, 'SettlementConfirmTotal', newSettlementConfirmTotalSurcharges)
    },
    // 更新分泡系数 =》 重算计费重
    recalculateChargeTotal() {
      const scope = this.$refs.gridTableRef.getEditRecord()
      if (!scope) return
      const data = scope.row
      // 分泡系数
      const SettlementSplitWeightRate = !Number(data.SettlementSplitWeightRate) ? scope.row.ServiceVolumnWeightSeparationRate : data.SettlementSplitWeightRate
      // console.log(data.SettlementConfirmVolumeWeight, data.SettlementConfirmInputWeight, SettlementSplitWeightRate, ':data.SettlementConfirmVolumeWeight, data.SettlementConfirmInputWeight, SettlementSplitWeightRate')
      const recalculateChargeWeight = this.getRecalculateCharge(data.SettlementConfirmVolumeWeight, data.SettlementConfirmInputWeight, SettlementSplitWeightRate)
      // 结算计费重
      this.$set(scope.row, 'SettlementConfirmBillWeight', recalculateChargeWeight)
      // 更新结算单价
      this.getUnitPrice(scope)
      // 更新结算总额
      this.updateTotalSurcharges(scope)
    },
    // 取消
    cancelRowEvent(row) {
      this.isEdit = false
      const $table = this.$refs.gridTableRef
      $table.clearActived().then(() => {
        // 还原行数据
        $table.revertData(row)
      })
    },
    // 搜索
    search(pageIndex) {
      if (pageIndex && pageIndex > 0) {
        this.pagerDto.PageIndex = pageIndex
      } else {
        this.pagerDto.PageIndex = 1
      }
      this.getData()
    },
    pagerSerach(page) {
      // if (page === 1) return
      this.pagerDto.PageIndex = page
      this.getData()
    },
    sizeChange(pageSize) {
      this.pagerDto.PageIndex = 1
      this.pagerDto.PageSize = pageSize
      this.getData()
    },
    // 批量修改附加费
    hanleSurcharges() {
      if (this.ids.length === 0) {
        this.$message({ type: 'warning', message: '请选择修改订单！' })
        return
      }
      _getBatchSettlementIncidenta(this.ids).then((res) => {
        this.surchargesData = res
        this.surchargesVisible = true
      })

      // this.surchargesData = [
      //   {
      //     MpsOrderId: 2954,
      //     CustomerOrderNumber: "FBA1XJR1MHtest21",
      //     BoxNumber: "FBA1XJR1MHtest21U1",
      //     BoxServiceNumber: "A029277440001",
      //     BoxSerialNo: 0,
      //     Length: 20,
      //     Width: 10,
      //     Height: 9,
      //     BillWidth: 10,
      //     BillHeight: 88,
      //     BillLenght: 20,
      //     BillWeight: 50,
      //     Id: 11092,
      //   },
      // ];
    },
    // 批量修改计费重
    hanleHeavyBilling() {
      if (this.ids.length === 0) {
        this.$message({ type: 'warning', message: '请选择修改订单！' })
        return
      }
      _getBatchSettlementWeight(this.ids).then((res) => {
        this.heavyBillingData = res
        this.heavyBillingVisible = true
      })
    },
    hanleCloseSurcharges() {
      this.surchargesVisible = false
    }, // 附加费弹窗取消
    hanleCloseHeavyBilling() {
      this.heavyBillingVisible = false
    },
    // 附加费修改
    hanleEditSurcharges(data) {
      _updateBatchSettlementIncidenta(data).then(() => {
        this.$message({ type: 'success', message: '保存成功！' })
        this.hanleCloseSurcharges()
      })
    },
    hanleEditHeavyBilling(data) {
      _updateBatchSettlementWeight(data).then(() => {
        this.$message({ type: 'success', message: '保存成功！' })
        this.hanleCloseHeavyBilling()
      })
    },
    // 重新获取单价
    getUnitPrice(scope) {
      const paramsData = {
        OrderId: scope.row.Id,
        PublicExpressId: scope.row.CreateOrderChannelId,
        CustomerId: scope.row.BranchCompanyId,
        TransactionTime: scope.row.ReceiveTime,
        gWeight: scope.row.SettlementConfirmBillWeight,
        ZipCode: scope.row.ReceiverZipCode
      }
      this.returnLoading = true
      _getUnitPrice(paramsData)
        .then((res) => {
          const price = typeof res === 'number' && isFinite(res) ? res : 0
          if(Number(price) >= 0 && scope.row.SettlementConfirmUnitPrice != price) {
            this.$confirm('是否更新单价?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.$set(scope.row, 'SettlementConfirmUnitPrice', price);
              // 更新结算总额
              this.updateTotalSurcharges(scope)
            })
          }
        }).finally(() => {
          this.returnLoading = false
        })
    },
    // 打开收入明细
    openIconmeDetails(data) {
      this.OrderId = 0;
      this.$set(data, 'detailLoading', true)
      if (
        !data.CustomerConfirmUnitPrice ||
        data.CustomerConfirmUnitPrice == 0
      ) {
        const paramsData = {
          OrderId: data.Id,
          PublicExpressId: data.CreateOrderChannelId,
          CustomerId: data.CustomerId,
          TransactionTime: data.ReceiveTime,
          gWeight: data.CustomerConfirmBillWeight,
          ZipCode: data.ReceiverZipCode
        }
        _getUnitPrice(paramsData)
          .then((res) => {
            const price = typeof res === 'number' && isFinite(res) ? res : 0
            if(Number(price) >= 0) data.CustomerConfirmUnitPrice = price;
          })
          .finally(() => {
            this.GetCustomerConfirm(data);
          });
      } else {
        this.GetCustomerConfirm(data);
      }
    },
    GetCustomerConfirm(data) {
      _getCustomerConfirm(data.Id)
        .then((res) => {
          this.customerData = res.mpsOrderBoxes;
          this.surchargeData = res.incidentals;
        })
        .finally(() => {
          this.itemsData = data;
          this.OrderId = data.Id;
          this.totalReceivableData = [];
          this.totalReceivableData.push({
            SettlementConfirmInputWeight: data.SettlementConfirmInputWeight,
            CustomerConfirmUnitPrice: data.CustomerConfirmUnitPrice,
            CustomerConfirmTotalSurcharges: data.CustomerConfirmTotalSurcharges,
            CustomerConfirmTotal: data.CustomerConfirmTotal,
            CustomerConfirmBillWeight: data.CustomerConfirmBillWeight,
            ApprovalNumber: data.ApprovalNumber,
            SplitWeightRate: data.SplitWeightRate,
            DeclarationMethod: data.DeclarationMethod,
          });
          this.showIconmeDetails = true;
          this.$set(data, 'detailLoading', false)
          if(!data.detailLoading) delete data.detailLoading
        });
    },
    // 取消明细弹窗
    handleIconmeDetailClose() {
      this.showIconmeDetails = false;
    },
    // 下单号计算失败提示
    getOrderBillingPrompt(list) {
      const content = `
        <table style="width: 100%; border-collapse: collapse;">
          <thead>
            <tr>
              <th style="border: 1px solid #ddd; padding: 8px; max-width: 224px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">单号</th>
              <th style="border: 1px solid #ddd; padding: 8px; max-width: 304px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">错误信息</th>
            </tr>
          </thead>
          <tbody>
            ${list.map(item => `
              <tr>
                <td style="border: 1px solid #ddd; padding: 8px; max-width: 264px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;" title="${item.SystemNo}">${item.SystemNo}</td>
                <td style="border: 1px solid #ddd; padding: 8px; max-width: 304px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;" title="${item.ResultMessage}">${item.ResultMessage}</td>
              </tr>
            `).join('')}
          </tbody>
        </table>
      `;
      this.$alert(content, '部分数据计算成功，以下单号计算失败！', {
        customClass: 'info-systemNo',
        showClose: false,
        dangerouslyUseHTMLString: true,
        confirmButtonText: '确定'
      }).then(() => {
        this.search()
      })
    },
    // 结算计费
    hanleToEnd() {
      if (this.ids.length === 0) {
        this.$message({ type: 'warning', message: '请选择订单！' })
        return
      }
      this.saveLadding = true
      _goToEnd(this.ids)
        .then((res) => {
          if (res && res.length > 0) {
            const allIsSucceed = res.every(item => item.isSucceed)
            if (allIsSucceed) {
              this.$message({ type: 'success', message: '已全部计算成功！' })
              this.search()
              return
            }
            const filterList = res.filter(item => !item.isSucceed)
            this.getOrderBillingPrompt(filterList)
            return
          }
          this.$message({ type: 'success', message: '已全部计算成功！' })
          this.search()
        })
        .finally(() => {
          this.saveLadding = false
        })
    },
    //导出结算
    ExportEnd() {
      const that = this;
      that.saveLadding = true;
      axios({
        method: "post",
        url: "http://120.24.149.148:9518/api/FBAOrder/ExportEnd",
        data: this.pagerDto,
        responseType: "blob",
        headers: {
          "Content-Type": "application/json",
          Authorization: "token 132A7468DE079C6CEB59F383A661E612",
        },
      })
        .then((res) => {
          that.saveLadding = false;
          const _res = res.data;
          const blob = new Blob([res.data], { type: res.data.type });

          var url = window.URL.createObjectURL(blob);
          var a = document.createElement("a");
          a.href = url;
          a.download = `结算.xlsx`;
          a.click();
        })
        .catch((err) => {
          this.$message({ type: "error", message: "下载excel出错" + err });
        })
        .finally(() => {
          this.saveLadding = false;
        });

      return;
    },
    // 获取多个单号
    getNumber(numbers) {
      this.pagerDto._Eq_SystemNo = numbers
    }
  }
}
</script>
<style lang="less">
.batch-warp {
  margin-bottom: 6px;
}
.grid-btn-warp {
  width: 90px;
  .view-btn {
    display: block;
    width: 100%;
    margin: 0 5px 5px 5px;
  }
}
.define-edit {
  .el-button--mini {
    padding: 7px 9px;
  }
  .details {
    margin-left: 10px;
    color: #13ce66;
    font-size: 14px;
  }
}
.settlement-table .profit-bj {
  background-color: #FFE506;
}
.info-systemNo {
  position: relative;
  width: 560px;
  max-height: 95vh;
  overflow-y: auto;
}
</style>
