<script setup lang="ts">
import { ElMessage } from "element-plus";
import { computed, ref, unref } from "vue";
import { order_columns, order_status } from "../../config/configs";
import { INPUT_MAX_LENGTH } from "/@/utils/global";
import SalesModal from "./sales-modal.vue";
const props = defineProps<{
  readonly?: boolean;
}>();

const emit = defineEmits(["create-btn-click"]);
const saleOrderList = ref<Array<Record<string, string>>>([]);
const disabled = computed(() => !props.readonly);

const mapSequenceNoToWapyfee = ref<Record<string, string>>({});

const saleModalRef = ref<InstanceType<typeof SalesModal>>(null);

function addSaleOrder(sales: Array<Record<string, string>>) {
  sales.forEach(sale => {
    const { sequenceNo, wpay_fee } = sale;
    if (!mapSequenceNoToWapyfee.value[sequenceNo]) {
      mapSequenceNoToWapyfee.value[sequenceNo] = wpay_fee;

      saleOrderList.value.push(sale);
    }
  });
}

function handleCreate() {
  const orderArr: any = [];
  const keys = Object.keys(mapSequenceNoToWapyfee.value);

  keys.forEach(sequenceNo =>
    orderArr.push({
      sequenceNo,
      trad_fee: mapSequenceNoToWapyfee.value[sequenceNo]
    })
  );

  if (!orderArr.length) return ElMessage.error("请添加关联订单");

  emit("create-btn-click", orderArr);
}

function handleDelete(sequenceNo: string) {
  delete mapSequenceNoToWapyfee.value[sequenceNo];
  saleOrderList.value = saleOrderList.value.filter(
    row => row.sequenceNo !== sequenceNo
  );
}
</script>

<template>
  <div>
    <div flex justify-between items-center>
      <h1 my-4>添加关联订单:</h1>
      <el-button
        v-if="disabled"
        type="primary"
        size="small"
        @click="() => saleModalRef.onDisplay(unref(saleOrderList))"
        >添加
      </el-button>
    </div>

    <el-table :data="saleOrderList" size="small">
      <el-table-column
        v-for="(col, index) in order_columns"
        :key="index"
        :label="col.label"
        :prop="col.prop"
        :width="col.width"
        show-overflow-tooltip
      >
        <template #default="{ row }">
          <el-input
            size="small"
            placeholder="此次认领金额"
            v-if="col.label === '此次认领'"
            v-model="mapSequenceNoToWapyfee[row.sequenceNo]"
            v-bind="INPUT_MAX_LENGTH"
          />

          <el-tag v-else-if="col.prop === 'status'">
            {{ order_status.find(p => String(row.status) === p.value)?.label }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="操作">
        <template #="{ row }">
          <el-button type="danger" link @click="handleDelete(row.sequenceNo)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <div flex justify-end mt-3 v-if="disabled">
      <el-button type="primary" size="small" @click="handleCreate"
        >保存</el-button
      >
    </div>

    <SalesModal ref="saleModalRef" @save-click-button="addSaleOrder" />
  </div>
</template>
