<template>
  <el-dialog
    top="0"
    width="60%"
    title="详情"
    :visible.sync="dialogVisible"
    :before-close="detailClose"
    :close-on-click-modal="false"
  >
    <div 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
            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" title="箱号" />
            <vxe-column field="OpInputWeight" title="收货实重KG" :width="120" />
            <vxe-column field="OpLength" title="长CM" :width="120" />
            <vxe-column field="OpWidth" title="宽CM" :width="120" />
            <vxe-column field="OpHeight" title="高CM" :width="120" />
            <vxe-column field="VolumeWeight" title="计费泡重" :width="120" />
            <vxe-column field="GoodsNames" title="操作备注" :width="140" />
          </vxe-table>
        </div>
      </div>
      <!-- 客户确认数据 -->
      <div class="warp-action">
        <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"
            :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' }"
            :footer-method="footerMethodCustomer"
            @checkbox-all="handleSelectionCustomer"
            @checkbox-change="handleSelectionCustomer"
          >
            <vxe-column type="checkbox" width="45" />
            <vxe-column field="BoxNumber" title="箱号" width="180" />
            <vxe-column
              field="SettlementWeight"
              title="结算实重KG"
              :edit-render="{ autofocus: '.vxe-input--inner' }"
            >
              <template #edit="{ row }">
                <vxe-input
                  v-model="row.SettlementWeight"
                  name="SettlementWeight"
                  :disabled="isSettlementConfirm"
                  type="text"
                />
              </template>
            </vxe-column>
            <vxe-column
              field="SettlementLenght"
              title="长CM"
              :edit-render="{ autofocus: '.vxe-input--inner' }"
            >
              <template #edit="{ row }">
                <vxe-input
                  v-model="row.SettlementLenght"
                  name="SettlementLenght"
                  :disabled="isSettlementConfirm"
                  type="text"
                />
              </template>
            </vxe-column>
            <vxe-column
              field="SettlementWidth"
              title="宽CM"
              :edit-render="{ autofocus: '.vxe-input--inner' }"
            >
              <template #edit="{ row }">
                <vxe-input
                  v-model="row.SettlementWidth"
                  name="SettlementWidth"
                  :disabled="isSettlementConfirm"
                  type="text"
                />
              </template>
            </vxe-column>
            <vxe-column
              field="SettlementHeight"
              title="高CM"
              :edit-render="{ autofocus: '.vxe-input--inner' }"
            >
              <template #edit="{ row }">
                <vxe-input
                  v-model="row.SettlementHeight"
                  name="SettlementHeight"
                  :disabled="isSettlementConfirm"
                  type="text"
                />
              </template>
            </vxe-column>
            <vxe-column
              field="SettlementVolumeWeight"
              title="计费泡重"
              :edit-render="{ autofocus: '.vxe-input--inner' }"
            >
              <template #edit="{ row }">
                <vxe-input
                  v-model="row.SettlementVolumeWeight"
                  name="SettlementVolumeWeight"
                  :disabled="isSettlementConfirm"
                  type="text"
                />
              </template>
            </vxe-column>
            <vxe-column
              field="SettlementVolumeFactor"
              title="分泡系数"
              :edit-render="{ autofocus: '.vxe-input--inner' }"
              width="140"
            >
              <template #edit="{ row }">
                <vxe-input
                  v-model="row.SettlementVolumeFactor"
                  name="SettlementVolumeFactor"
                  :disabled="isSettlementConfirm"
                  type="text"
                />
              </template>
            </vxe-column>
          </vxe-table>
          <div class="flex cost-warp">
            <span>最终确认计费重</span>
            <el-input
              v-model="propsTotalReceivableData[0].SettlementConfirmBillWeight"
              class="cost"
              :disabled="isSettlementConfirm"
              :class="{ 'mr17': getLengthNum }"
              placeholder="请输入内容"
            />
          </div>
        </div>
      </div>
      <!-- 附加费 -->
      <div class="flex mb-12">
        <div class="warp-left">附加费</div>
        <div class="warp-right">
          <vxe-table
            class="surcharge-table"
            border
            show-overflow
            show-footer
            :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' }"
            :footer-method="footerSurchargeMethod"
          >
            <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>
            <vxe-column
              field="Id"
              title="附加费项"
              :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"
                  placeholder="附加费项"
                  :transfer="true"
                  :disabled="isSettlementConfirm"
                  @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="附加费标准"
              :edit-render="{ autofocus: '.vxe-input--inner' }"
            >
              <template #edit="{ row }">
                <span v-if="SurchargeType == '结算'">
                  <vxe-input
                    v-model="row.JSRemark"
                    type="text"
                    :disabled="isSettlementConfirm"
                    placeholder="附加费标准"
                  />
                </span>
                <span v-else>
                  <vxe-input
                    v-model="row.CustomerRemark"
                    type="text"
                    :disabled="isSettlementConfirm"
                    placeholder="附加费标准"
                  />
                </span>
              </template>
            </vxe-column>
            <vxe-column
              field="Fee"
              title="费项附加费总额"
              :edit-render="{ autofocus: '.vxe-input--inner' }"
            >
              <template #edit="{ row }">
                <vxe-input
                  v-model="row.Fee"
                  type="text"
                  :disabled="isSettlementConfirm"
                  placeholder="请填入计费值"
                />
              </template>
            </vxe-column>
            <vxe-column
              field="Remark"
              title="备注"
              :edit-render="{ autofocus: '.vxe-input--inner' }"
              width="140"
            >
              <template #edit="{ row }">
                <vxe-input
                  v-model="row.Remark"
                  type="text"
                  :disabled="isSettlementConfirm"
                  placeholder="备注"
                />
              </template>
            </vxe-column>
            <vxe-column v-if="getLengthNum" width="17" />
            <!-- <vxe-column field="SysncJS" title="计入销售成本" width="120">
              <template #header
                ><i class="vxe-icon-edit"></i>计入销售成本
              </template>
              <template #default="{ row }">
                <vxe-checkbox v-model="row.SysncJS" size="medium">{{
                  row.SysncJS ? "是" : "否"
                }}</vxe-checkbox>
              </template>
            </vxe-column> -->
            <template #empty>
              <el-button
                v-show="propsSurchargeData.length === 0"
                type="text"
                icon="el-icon-plus"
                class="empty"
                @click="handleAddSurcharge"
              />
            </template>
          </vxe-table>
        </div>
      </div>
      <!-- 应收金额 -->
      <div class="flex mb-12">
        <div class="warp-left">应收总额</div>
        <div class="flex-1">
          <el-table :data="propsTotalReceivableData" height="98px" border>
            <el-table-column
              prop="SettlementConfirmBillWeight"
              label="计费重量KG"
              :show-overflow-tooltip="true"
            >
              <!-- <template slot-scope="scope">
                <el-input
                  v-model="scope.row.SettlementConfirmBillWeight"
                  size="small"
                  placeholder="计费重量KG"
                />
              </template> -->
            </el-table-column>
            <el-table-column
              prop="SettlementConfirmUnitPrice"
              label="单价"
              :show-overflow-tooltip="true"
            >
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.SettlementConfirmUnitPrice"
                  size="small"
                  placeholder="单价"
                  :disabled="isSettlementConfirm"
                  @input="changeSettlementConfirmTotal"
                />
              </template>
            </el-table-column>
            <el-table-column
              prop="SettlementConfirmTotalSurcharges"
              label="附加费总额"
              :show-overflow-tooltip="true"
            >
              <template slot-scope="scope">
                <div v-if="scope.row.SettlementConfirmTotalSurcharges > 0">
                  {{ scope.row.SettlementConfirmTotalSurcharges }}
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="SettlementConfirmTotal"
              label="应收总额"
              :show-overflow-tooltip="true"
            >
              <template slot-scope="scope">
                <div v-if="scope.row.SettlementConfirmTotal > 0">
                  {{ scope.row.SettlementConfirmTotal }}
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="flex flex-1 total-receivable">
          <el-button
            v-show="!isSettlementConfirm"
            size="mini"
            type="primary"
            :loading="saveLadding"
            @click="edit"
          >确定修改</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'

export default {
  name: 'DetailISettlement',
  components: { DefineDescriptions },
  props: {
    width: {
      type: String,
      default: '65%'
    },
    title: String,
    dialogVisible: {
      type: Boolean,
      default: false
    },
    isSettlementConfirm: {
      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: '件数' }
      ], // 基本信息
      multipleCustomer: [], // 客户确认数据选中数据
      currentInput: {
        value: '',
        field: ''
      }, // 当前的复制内容
      propsCustomerData: [],
      propsSurchargeData: [], // 附加费
      FBAOtherFee: [], // 附加费数据
      propsTotalReceivableData: [
        {
          SettlementConfirmInputWeight: 0,
          SettlementConfirmUnitPrice: 0,
          SettlementConfirmTotalSurcharges: 0,
          SettlementConfirmTotal: 0,
          SettlementConfirmBillWeight: 0
        }
      ], // 应收总额
      saveLadding: false,
      timerBlur: null,
      lengthNum: 0
    }
  },
  computed: {
    getOrderId() {
      return this.orderId
    },
    getLengthNum() {
      return this.lengthNum >= 5
    }
  },
  watch: {
    customerData(val) {
      // 子组件内部客户数据
      this.propsCustomerData = deepClone(val)
      if (this.propsCustomerData.length > 0) {
        this.lengthNum = this.propsCustomerData.length
        this.$nextTick().then(() => {
          this.$refs.customerRef.$el.addEventListener(
            'blur',
            this.defineBlur,
            true
          )
        })
      }
    },
    totalReceivableData(val) {
      this.propsTotalReceivableData = deepClone(val)
    },
    surchargeData(val) {
      this.propsSurchargeData = deepClone(val)
    }
  },
  created() {
    _getAll().then((res) => {
      this.FBAOtherFee = res
    })
  },
  beforeDestroy() {
    // 销毁
    clearTimeout(this.timerBlur)
    this.timerBlur = null
    if (this.$refs.customerRef) { this.$refs.customerRef.$el.removeEventListener('blur', this.defineBlur) }
  },
  methods: {
    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)
    },
    cancelLoading() {
      this.saveLadding = false
    },
    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
        })
      }
    },
    // 复制内容到全部
    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
          })
          cloneCurrentInput = null
        })
        .catch(() => {
          cloneCurrentInput = null
        })
    },
    // 添加附加费
    handleAddSurcharge() {
      if (this.isSettlementConfirm) {
        return
      }
      // 限制只能添加3条附加费
      if (this.propsSurchargeData.length === 3) {
        return
      }
      this.propsSurchargeData.push({
        FBAOtherFeeId: null,
        CustomerRemark: '',
        Fee: '',
        Remark: '',
        SysncJS: false
      })
    },
    // 移除附加费
    handleDeleteRow(index, data) {
      if (this.isSettlementConfirm) {
        return
      }
      this.propsSurchargeData.splice(index, 1)
    },
    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].SettlementConfirmTotalSurcharges = surchargeNum
      // 应收总额
      this.changeSettlementConfirmTotal()
    },
    // 更新单价 =》应收总额更新
    changeSettlementConfirmTotal() {
      const propsTotalReceivableData = this.propsTotalReceivableData[0]
      this.propsTotalReceivableData[0].SettlementConfirmTotal =
        propsTotalReceivableData.SettlementConfirmBillWeight *
          propsTotalReceivableData.SettlementConfirmUnitPrice +
        propsTotalReceivableData.SettlementConfirmTotalSurcharges
    },
    sumNumGather(list, field) {
      let count = 0
      list.forEach(item => {
        count += Number(item[field])
      })
      return count
    },
    // 仓库收货数据汇总
    footerMethodCustomerStore({ columns, data }) {
      return [
        columns.map((column, columnIndex) => {
          if (columnIndex === 0) {
            return '汇总'
          }
          if (columnIndex === 1) {
            return `${this.sumNumGather(data, 'BillWeight')}`
          } 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) {
            return `${this.sumNumGather(data, 'BillWeight')}`
          } else if (columnIndex === 6) {
            return `${this.sumNumGather(data, 'VolumeWeight')}`
          }
          return '-'
        })
      ]
    }
  }
}
</script>
<style lang="less">
.batch-warp {
  margin-bottom: 6px;
}
.details-content {
  .flex {
    display: flex;
  }
  .flex-1 {
    flex: 1;
  }
  .mb-12 {
    margin-bottom: 15px;
  }
  .empty {
    font-size: 36px;
  }
  .vxe-table--render-default {
    .vxe-cell {
      padding-left: 5px;
      padding-right: 5px;
    }
  }

  .warp-action {
    text-align: right;
    margin-bottom: 6px;
  }

  .warp-left {
    flex-basis: 130px;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #f2f6fc;
    color: #737272;
    font-weight: bold;
  }
  .warp-right {
    flex: 1;
    .delete {
      color: red;
    }
  }

  .cost-warp {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    background-color: #f2f6fc;
    // padding: 5px 6px 5px 0;
    border: 1px solid #dfe6ec;
    border-top: none;
    // padding: 10px 0;
    .cost {
      padding: 5px 6px 5px 6px;
      margin-left: 6px;
      width: 140px;
      background-color: #e6f7ff;
      &.mr17 {
        margin-right: 17px;
      }
    }
  }
  .total-receivable {
    justify-content: flex-end;
    align-items: flex-end;
    padding-right: 20px;
    padding-bottom: 10px;
  }
}
.details-content .el-table__header th {
  background-color: #f2f6fc;
  color: #737272;
}
.details-content .el-table .cell {
  padding-right: 5px;
  padding-left: 5px;
}
.details-content .el-input--medium .el-input__inner {
  padding: 0 8px;
}
.customer-table {
  position: relative;
  table {
    tbody,thead,tfoot {
      > tr {
        td.col--last,th.col--last {
          background-color: #e6f7ff;
        }
      }
    }
  }
}
.surcharge-table {
  position: relative;
  table {
    tbody,thead,tfoot {
      > tr {
        td.vxe-body--column:nth-child(5),th.vxe-header--column:nth-child(5),td.vxe-footer--column:nth-child(5) {
          background-color: #e6f7ff;
        }
      }
    }
  }
}
</style>
