<script setup lang="ts">
import { ref } from "vue";
import { ElMessage } from "element-plus"
import { execlUpload as excelUpload } from "/@/components/execlUpload";
import { validateImportHeader, formatImportData, validateData, showErrorSet } from "./config/utils";
import { httpAdd } from "/@/api/postSupplierOrder/sendOrder";
import { columns } from "./config/template";
import { useAsync } from "/@/hooks";
import { useRouter } from "vue-router";
import { useCompany } from "/@/hooks/core/useCompany";

const list = ref<Array<Record<string,string>>>([]);

const { push } = useRouter();

const { run, loading } = useAsync({
  success:() => push('/postSupplierOrder/sendOrder')
})

const { currentCompany } = useCompany()

function handleImportData({ results, header }) { 
  // 校验表头
  if (!validateImportHeader(columns, header)) return;

  // 处理数据 模板映射成键值对
  const data = formatImportData(results);

  const companies = [...new Set(data.map(item => item.companyNo))];
  if (companies.length > 1) { 
    ElMessage.warning('上传多条数据业务公司必须一致')
    return;
  }

  if (companies[0] !== currentCompany.value.companyNo) { 
    ElMessage.warning('上传数据的业务公司与选中的业务公司不一致');
    return;
  }

  // 校验数据
  const { errorSet, isValid } = validateData(data);
  if (!isValid) { showErrorSet(errorSet); }
  list.value = data;
}

function onSubmit() {
  if(list.value.length > 100){
    ElMessage.warning('导入发货运单不能超过100条')
    return;
  }
  
  const companies = [...new Set(list.value.map(item => item.companyNo))];
  if (companies.length > 1) { 
    ElMessage.warning('上传多条数据业务公司必须一致')
    return;
  }

  if (companies[0] !== currentCompany.value.companyNo) { 
    ElMessage.warning('上传数据的业务公司与选中的业务公司不一致');
    return;
  }

  const { errorSet, isValid } = validateData(list.value);
  if (!isValid) { showErrorSet(errorSet); return; }

  const parameter = list.value.map(({ outChildCode, supplierNo, companyNo, post_fee, remark }) => ({
     outChildCode, supplierNo, companyNo, remark ,post_fee:Number(post_fee).toFixed(2)
  }))

  run(httpAdd({list: parameter}));
}
</script>

<template>
  <div class="padding-container bg-white" v-loading="loading">
    <el-tabs class="px-[10px]">
      <el-tab-pane label="批量导入发货运单">
         <excel-upload style="width:100%" @on-success="handleImportData" v-if="list.length === 0" />

        <el-table border size="mini" class="my-[10px]" :data="list">
          <el-table-column v-for="column in columns" v-bind="column" :key="column.prop" show-overflow-tooltip />
        </el-table>

        <div class="flex my-[10px]" v-if="list.length !== 0">
          <el-button class="ml-auto" @click="list = []">取消</el-button>
          <el-button type="primary" class="ml-auto" @click="onSubmit">保存</el-button>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>
