<template>
  <el-dialog
    :width="width"
    :title="title"
    :visible.sync="dialogVisible"
    :before-close="close"
    :close-on-click-modal="false"
  >
    <div class="surcharges-list">
      <div class="warp-left">{{ leftTitle }}</div>
      <div class="warp-right">
        <vxe-table
          ref="customerTableRef"
          border
          show-overflow
          :data="newTableData"
          height="280px"
          :span-method="rowspanMethod"
          :edit-rules="validRules"
          :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', showIcon: false }"
        >
          <!-- key需唯一值 -->
          <vxe-column
            v-for="config in tableColumn"
            :key="config.key"
            :type="config.type"
            :field="config.field"
            :title="config.title"
            :width="config.width"
            :edit-render="config.editRender"
          >
            <template #header>
              <i class="vxe-icon-edit" />{{ config.title }}
            </template>
            <template #default="scope">
              <div v-show="!config.field">
                <el-button
                  type="text"
                  size="small"
                  @click.native.prevent="handleAddSurcharge(scope)"
                >
                  新增
                </el-button>
                <el-button
                  type="text"
                  size="small"
                  class="delete"
                  @click.native.prevent="handleDeleteRow(scope)"
                >
                  移除
                </el-button>
              </div>
              <div v-if="config.isSelect">
                <span>{{
                  formatFBAOtherFee(scope.row[config.field], FBAOtherFee)
                }}</span>
              </div>
              <div v-else>
                <div v-if="config.deCheckbox">
                  <vxe-checkbox v-model="scope.row[config.field]" size="medium">
                    {{ scope.row[config.field] ? "是" : "否" }}
                  </vxe-checkbox>
                </div>
                <div v-else>
                  {{ scope.row[config.field] }}
                </div>
              </div>
            </template>
            <template #edit="scope">
              <div v-if="config.field">
                <div v-show="config.isSelect">
                  <vxe-select
                    v-model="scope.row[config.field]"
                    style="z-index: 3000"
                    :transfer="true"
                    placeholder="附加费项"
                    @change="changeFBAOtherFee(scope)"
                  >
                    <vxe-option
                      v-for="item in FBAOtherFee"
                      :key="item.Id"
                      :value="item.Id"
                      :label="item.Name"
                    />
                  </vxe-select>
                </div>
                <div v-show="!config.isSelect" class="define-input">
                  <vxe-input
                    v-model="scope.row[config.field]"
                    type="text"
                    @change="$refs.customerTableRef.updateStatus(scope)"
                  />
                </div>
              </div>
            </template>
          </vxe-column>
          <template #empty>
            <el-button
              v-show="newTableData.length === 0"
              type="text"
              icon="el-icon-plus"
              class="empty"
              @click="handleAddSurcharge"
            />
          </template>
        </vxe-table>
      </div>
    </div>
    <div class="surcharges-footer">
      <el-button size="mini" type="primary" @click="edit">确定修改</el-button>
      <el-button size="mini" @click="close">取消</el-button>
    </div>
  </el-dialog>
</template>
<script>
import { deepClone } from '@/utils'
import { _getAll } from '@/api/order/fba/index'

export default {
  name: 'SurchargesList',
  props: {
    tableData: {
      type: Array,
      default: () => []
    },
    width: {
      type: String,
      default: '1200px'
    },
    leftTitle: {
      type: String,
      default: '计费数据'
    },
    title: String,
    dialogVisible: {
      type: Boolean,
      default: false
    },
    tableColumn: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      FBAOtherFee: [], // 附加费像下拉列表数据
      newTableData: [], //
      // 校验
      validRules: {
        FBAOtherFeeId: [{ required: true, message: '请选择附加费项' }],
        CustomerRemark: [{ required: true, message: '请输入附加费标准' }],
        Fee: [{ required: true, message: '请输入整票附加费' }]
      }
    }
  },
  watch: {
    tableData: {
      handler(newVal) {
        this.newTableData = deepClone(newVal)
      },
      deep: true
    }
  },
  created() {
    _getAll().then((res) => {
      this.FBAOtherFee = res
    })
  },
  methods: {
    async edit() {
      const $table = this.$refs.customerTableRef
      const errMap = await $table.validate(true).catch((errMap) => errMap)
      if (!errMap) {
        this.$emit('edit', this.newTableData)
      }
    },
    close() {
      this.$emit('close')
    },
    // 附加费项change事件
    changeFBAOtherFee(scope) {
      const findFee = this.FBAOtherFee.find(
        (item) => item.Id === scope.row.FBAOtherFeeId
      )
      // row.Fee = findFee.Fee;
      // row.CustomerRemark = findFee.CustomerRemark;
      // row.Remark = findFee.Remark;
      // row.SysncJS = findFee.SysncJS;
      this.$set(scope.row, 'Fee', findFee.Fee)
      this.$set(scope.row, 'CustomerRemark', findFee.CustomerRemark)
      this.$set(scope.row, 'Remark', findFee.Remark)
      this.$set(scope.row, 'SysncJS', findFee.SysncJS)
      this.$refs.customerTableRef.updateStatus(scope)
    },
    formatFBAOtherFee(Id, list) {
      // 显示附加费项对应文本
      const findObj = list.find((item) => item.Id == Id)
      return findObj?.Name
    },
    // 添加附加费
    handleAddSurcharge(scope) {
      // 限制只能添加3条附加费
      const currentTableData = this.newTableData.filter(item => item.OrderId === scope.row.OrderId)
      if (currentTableData.length === 3) {
        return
      }
      if (scope.row) {
        const rowIndex = scope.rowIndex
        this.newTableData.splice(rowIndex, 0, {
          OrderId: scope.row.OrderId,
          OrderNo: scope.row.OrderNo,
          CustomerRemark: '',
          Fee: '',
          Remark: '',
          SysncJS: false
        })
        this.$set(this.newTableData)
      }
    },
    // 移除附加费
    handleDeleteRow(scope) {
      const index = scope.rowIndex
      const OrderNo = scope.row.OrderNo
      const isOrders = this.isOrderNoRepeated(this.newTableData, OrderNo)
      if (isOrders) {
        this.$message({
          type: 'warning',
          message: `不能移除（${OrderNo}）订单最后一条附加费！`
        })
      } else {
        this.newTableData.splice(index, 1)
      }
    },
    isOrderNoRepeated(list, val) {
      const filteredArr = list.filter((item) => item.OrderNo === val)
      return filteredArr.length === 1
    },
    // 通用行合并函数（将相同多列数据合并为一行）
    rowspanMethod({ row, _rowIndex, column, visibleData }) {
      const fields = ['OrderNo'] // 以订单号合并行
      const cellValue = row[column.property]
      if (cellValue && fields.includes(column.property)) {
        const prevRow = visibleData[_rowIndex - 1]
        let nextRow = visibleData[_rowIndex + 1]
        if (prevRow && prevRow[column.property] === cellValue) {
          return { rowspan: 0, colspan: 0 }
        } else {
          let countRowspan = 1
          while (nextRow && nextRow[column.property] === cellValue) {
            nextRow = visibleData[++countRowspan + _rowIndex]
          }
          if (countRowspan > 1) {
            return { rowspan: countRowspan, colspan: 1 }
          }
        }
      }
    }
  }
}
</script>
<style lang="less">
.surcharges-list {
  display: flex;

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

  .warp-right {
    // flex: 1;
    width: calc(100% - 130px);

    .delete {
      color: red;
    }
  }

  .vxe-table--render-default {
    .vxe-cell {
      padding-left: 5px;
      padding-right: 5px;
    }
  }

  .empty {
    font-size: 36px;
  }
}

.surcharges-footer {
  margin-top: 10px;
  text-align: right;
}
</style>
