<script setup lang="ts">
import { reactive, ref, shallowRef, unref } from "vue";
import { httpBatchOrderList } from "/@/api/InvoiceSales/invoiceApply";
import { responseHandle } from "/@/utils/responseHandle";
import { useNav } from "/@/layout/hooks/nav";
import { ElMessage } from "element-plus";
import { useColumns } from "./columns";
import { useTypeOptions } from "/@/utils/status";

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

const { columns } = useColumns();

columns.value = columns.value.slice(1);

const { logout } = useNav();
const loading = ref(false);
const selected = ref([]);
const tableRef = ref();

const pagination = reactive({
  total: 0,
  pageSize: 15,
  currentPage: 1,
  background: true,
  pageSizes: [15, 50, 100]
});

const props = defineProps<{
  payload: object;
}>();

const sourceText = shallowRef("");
//列表展示
async function onSearch(sequenceNo = []) {
  loading.value = true;
  const { currentPage: page, pageSize: size } = pagination;
  const { code, data, message } = await httpBatchOrderList({
    ...props.payload,
    sequenceNo: sequenceNo.join(","),
    customerNo: 'GS2404151642335170',
    is_comon: "1",
    inv_is: "1",
    cat_status: "2",
    inv_status: "0",
    status: '3',
    page,
    size
  });

  responseHandle({
    code,
    message,
    logout,
    handler: () => {
      // const { li } = data ?? {};
      selected.value = data ?? [];
      // pagination.total = count ?? 0;
      sourceText.value = "";
    }
  });
  loading.value = false;
}

const $space = " ";
const $wrap = "\n";
const replaceTextWrapAndSpace = function (text = "") {
  if (!text) return "";
  let _text = text;
  const hasSpace = _text.includes($space);
  const hasWrap = _text.includes($wrap);
  if (hasSpace) _text = _text.split($space).join("");
  if (hasWrap) _text = _text.split($wrap).join("");
  return _text;
};

function handleEnter() {
  const text = replaceTextWrapAndSpace(sourceText.value);
  /* 去掉回车和空格 **/
  if (text.length === 0) {
    ElMessage.warning("不能解析空文本");
    sourceText.value = text;
    return;
  }

  /* 统一替换字符 **/
  const parserText = text.replace(/[，。；、; .]/g, ",");
  const sequenceNo = parserText.split(",");
  onSearch(sequenceNo);
}

function handleConfirm() {
  if (selected.value.length === 0) {
    return ElMessage.error("至少添加一个销售订单！");
  }

  //商品数量或开票金额为空
  const noConfirm = selected.value.filter(o => o.winv_fee === "0.00");
  const noInvNum = selected.value.filter(o => String(o.winv_num) === "0");

  if (noConfirm.length !== 0) {
    return ElMessage.error(`销售订单 ${noConfirm[0].sequenceNo} 开票金额为零`);
  }

  if (noInvNum.length !== 0) {
    return ElMessage.error(`销售订单 ${noInvNum[0].sequenceNo} 开票数量为零`);
  }

  emit("confirm", unref(selected));
}
</script>

<template>
  <div relative>
    <ElInput
      :rows="4"
      v-model="sourceText"
      style="margin-bottom: 10px"
      placeholder="输入销售单编码(小于100条)，系统支持的分割符为逗号(,)、句号(.)、分号(;)、顿号(、)，回车后开始解析。"
      type="textarea"
      @keydown.enter="handleEnter"
    />

    <div v-loading="loading">
      <PureTable
        ref="tableRef"
        border
        align="left"
        row-key="id"
        table-layout="auto"
        :size="'small'"
        :data="selected"
        :columns="columns"
        max-height="560px"
        :header-cell-style="{ background: '#fafafa', color: '#606266' }"
      >
        <template #platform_type="scope">
          <el-tag>{{
            useTypeOptions.find(
              ({ value }) => value === scope.row.platform_type
            )?.label || "--"
          }}</el-tag>
        </template>
      </PureTable>
    </div>

    <div class="flex justify-end mt-10px">
      <el-button type="primary" @click="handleConfirm" size="small"
        >保存</el-button
      >
    </div>
  </div>
</template>

<style lang="scss" scoped>
:deep(.el-pagination) {
  justify-content: flex-start !important;
}

.search {
  padding: 0px !important;
}
</style>
