<script setup lang="ts">
import { ref } from "vue";
import { httpList } from "/@/api/InvoiceSales/currentcyAssOrderRecord";
import { ElMessage, ElTable } from "element-plus"
import { useAsync } from "/@/hooks/core"

const emit = defineEmits(['list'])
const props = defineProps<{
  platformType: string,
  customerNo: String,
  companyNo: string
}>();

const sourceText = ref("");
const tableRef = ref<InstanceType<typeof ElTable> | null>(null);
const { run, data, loading } = useAsync({ isList: true, success: (data) => params.value.total = data.count });

const initialParams = {
  page: 1,
  size: 100,
  total: 0,
  pay_status: '1',
  status: [0],
  good_status: 2
}


const sendStatusOptions = [
  { value: "0", label: "待与供应商确认" },
  { value: "1", label: "待入库" },
  { value: "2", label: "部分入库" },
  { value: "3", label: "入库完成" },
  { value: "4", label: "已取消订单" }
];

const state = ref(1)

const list = ref<any[]>([]);
const params = ref({ ...initialParams });

function handleList() {
  if (!data.value || data.value.length === 0) {
    ElMessage.warning("至少添加一条通用订单");
    return;
  }

//   const isHasWaitSupplierConfirm = data.value.some(({cgd}) => cgd.cgd_status === '0')

// if (isHasWaitSupplierConfirm) {
//   ElMessage.warning("不能添加采购单状态为`待与供应商确认`的通用订单");
//   return;
// }

  emit('list', data.value)
  data.value = [];
}

const requestList = async (orderCode: string[]) => run(httpList({
  orderCode,
  ...params.value,
  platform_type: props.platformType,
  customerNo: props.customerNo,
  companyNo: props.companyNo,
  status: Number(state.value) === -1 ? [-1, ...params.value.status] : params.value.status
}));


const $space = " ";
const $wrap = "\n";
function replaceTextWrapAndSpace(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;
}

async function handleEnter() {
  const text = replaceTextWrapAndSpace(sourceText.value);
  /* 统一替换字符 **/
  const parserText = text
    .replace(/[，。；、; .]/g, ",")
    .replace(/(^,*)|(,*$)/g, "");
  const orderCode = parserText.split(",");
  /* 去掉回车和空格 **/
  if (parserText.length === 0 || orderCode.length === 0) {
    ElMessage.warning("不能解析空文本");
    sourceText.value = text;
    return;
  }

  await requestList(orderCode);
  sourceText.value = "";
}

const retrun_status = [
  { value: 1, label: "已回款" },
  { value: -1, label: "无回款限制" }
];

</script>

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

  <ElCol :span="4" style="width:100%">
    <ElSelect v-model="state" size="small" placeholder="关联已回款状态">
      <ElOption v-for="{ label, value } in retrun_status" :label="label" :value="value" :key="value" />
    </ElSelect>
  </ElCol>

  <ElTable ref="tableRef" border size="small" :data="data" class="mt-[10px]" @selection-change="val => list = val"
    v-loading="loading" max-height="500px">
    <ElTableColumn label="通用订单编号" min-width="160" prop="tyCode" show-overflow-tooltip />
    <ElTableColumn label="确认单编号" min-width="160" prop="orderCode" show-overflow-tooltip />
    <ElTableColumn label="销售订单主编号" min-width="160" prop="cxCode" show-overflow-tooltip />
    <ElTableColumn label="商品编号" min-width="160" prop="goodNo" show-overflow-tooltip />
    <ElTableColumn label="商品名称" min-width="160" prop="goodName" show-overflow-tooltip />
    
    <ElTableColumn label="采购单状态" min-width="130" show-overflow-tooltip>
      <template #default="scope">
        <el-tag>
          {{ sendStatusOptions.find(({value}) => value === scope.row.cgd.cgd_status)?.label || '--' }}
        </el-tag>
      </template>
    </ElTableColumn>


    <ElTableColumn label="类目编码" min-width="130" show-overflow-tooltip>
      <template #default="scope">
        {{ scope.row.good ? scope.row.good.inv_cat_code : '' }}
      </template>
    </ElTableColumn>
    <ElTableColumn label="货物和劳务名称" min-width="130" show-overflow-tooltip>
      <template #default="scope">
        {{ scope.row.good ? scope.row.good.inv_cat_name : '' }}
      </template>
    </ElTableColumn>
    <ElTableColumn label="开票商品名称" min-width="160" show-overflow-tooltip>
      <template #default="scope">
        {{ scope.row.good ? scope.row.good.inv_good_name : '' }}
      </template>
    </ElTableColumn>
    <ElTableColumn label="开票税率" min-width="80" show-overflow-tooltip>
      <template #default="scope">
        {{ scope.row.good ? scope.row.good.inv_tax : '' }}
      </template>
    </ElTableColumn>

    <ElTableColumn label="申请人" prop="apply_name" width="100px" show-overflow-tooltip />
    <ElTableColumn label="买入方公司" min-width="160" prop="customerName" show-overflow-tooltip />
    <ElTableColumn label="卖出方公司" min-width="160" prop="companyName" show-overflow-tooltip />
    <ElTableColumn label="下单数量" width="80" prop="goodNum" show-overflow-tooltip>
      <template #default="scope"> {{ scope.row.qrd ? scope.row.qrd.goodNum : "" }}</template>
    </ElTableColumn>
    <ElTableColumn label="销售单价" width="80" prop="goodPrice" show-overflow-tooltip>
      <template #default="scope">{{ scope.row.qrd ? scope.row.qrd.goodPrice : "" }}</template>
    </ElTableColumn>

    <!-- 
    <ElTableColumn label="关联已回款状态" width="110" prop="pay_status" show-overflow-tooltip>
      <template #default="scope">
        <ElTag>
          {{ retrun_status.find(c => c.value == scope.row.qrd.pay_status)?.label || '--' }}
        </ElTag>
      </template>
    </ElTableColumn> 
    -->

    <ElTableColumn label="关联已回款状态" width="110" prop="pay_status" show-overflow-tooltip>
      <template #default="scope">
        <ElTag>
          {{ String(scope.row.status) === '-1' ? '未回款' : '已回款' }}
        </ElTag>
      </template>
    </ElTableColumn>

    <ElTableColumn label="税率" width="80" prop="goodPrice" show-overflow-tooltip>
      <template #default="scope">{{ scope.row.qrd ? `${scope.row.qrd.tax}%` : "" }}</template>
    </ElTableColumn>

    <ElTableColumn label="下单时间" width="100" prop="addtime" show-overflow-tooltip />
  </ElTable>

  <div class="flex justify-end w-full mt-[10px]">
    <ElButton type="primary" size="small" @click="handleList">添加</ElButton>
  </div>
</template>
