<script setup lang="ts">
import { ref } from "vue";
import { httpList } from "/@/api/InvoiceSales/invoiceApply";
import { inv_columns } from "../../returnTicket/config/configs";
import { httpBatchapplyred, httpApplyred } from "/@/api/InvoiceSales/redInk";
import { useAsync } from "/@/hooks";

const emit = defineEmits(["reload"]);

const visible = ref(false);
const selectInvioces = ref<Array<Record<string, string>>>([]);
const handleSelectionChange = values => (selectInvioces.value = values);

const success = () => {
  visible.value = false;
  emit("reload");
};

const initalPagination = {
  pageSize: 15,
  currentPage: 1,
  total: 0
};

const {
  data,
  pagination,
  getPaginationParams,
  run: invoicelistRun,
  loading
} = useAsync<Array<Record<string, string>>>({
  initalData: [],
  isList: true,
  initalPagination
});

const requestInvoicelist = () => {
  invoicelistRun(
    httpList({
      status: "3",
      ...getPaginationParams()
    })
  );
};

const { run: batchApplyRedRun, loading: batchApplyRedLoading } = useAsync({
  success
});

const { run: applyRedRun, loading: applyRedLoading } = useAsync({
  success
});

const requestBatchApplyred = () => {
  const invArr = selectInvioces.value.map(({ invNo }) => invNo);

  if (invArr.length === 1) {
    return applyRedRun(
      httpApplyred({
        invNo: invArr[0]
      })
    );
  }

  batchApplyRedRun(
    httpBatchapplyred({
      invArr
    })
  );
};

function handleSizeChange() {
  pagination.currentPage = 1;
  requestInvoicelist();
}

defineExpose({
  onDisplay() {
    visible.value = true;
    requestInvoicelist();
  }
});
</script>

<template>
  <el-dialog
    title="创建红冲发票"
    center
    v-model="visible"
    :close-on-click-modal="false"
  >
    <el-table
      :data="data"
      row-key="invNo"
      v-loading="loading"
      @selection-change="handleSelectionChange"
      max-height="520px"
    >
      <el-table-column type="selection" align="center" width="40px" />
      <el-table-column
        v-for="inv in inv_columns"
        :key="inv.prop"
        v-bind="inv"
        show-overflow-tooltip
        reserve-selection
    /></el-table>

    <el-pagination
      v-model:current-page="pagination.currentPage"
      v-model:page-size="pagination.pageSize"
      :total="pagination.total"
      @current-change="() => requestInvoicelist()"
      @size-change="handleSizeChange"
      layout="sizes, prev, pager, next"
      :page-sizes="[15, 50, 100]"
    />

    <div w-full flex justify-end mt-2>
      <el-button type="primary" size="small" @click="requestBatchApplyred"
        >确定</el-button
      >
      <el-button size="small" @click="() => (visible = false)">取消</el-button>
    </div>
  </el-dialog>
</template>
