<script setup lang="ts">
import { ref } from "vue";
import { ElMessage } from "element-plus";
import { execlUpload } from "/@/components/execlUpload";
import { httpInvoiceBatch } from "/@/api/purchase/invoiceRelation";
import { useResponseHandle } from "/@/hooks";
import {
  columns,
  getHeaders
} from "./columns-config";

const visible = ref(false);
const loading = ref(false);
const tableData = ref([]);
const emit = defineEmits(["onSuccess"]);
const { mapLabelToProp, initHeader, requireFields } = getHeaders()
const responseHandle = useResponseHandle();

const Uploadsuccess = ({ results, header }) => {
  loading.value = true;
  if (results.length === 0) {
    ElMessage.error("表格无有效数据！");
    loading.value = false;
    return;
  }

  if(header.length !== initHeader.length){
    ElMessage.warning('导入表头与模板不一致');
    loading.value = false;
    return
  }

  for(const index in initHeader){
    if(initHeader[index] !== header[index]){
      console.log(initHeader[index], header[index])
      ElMessage.warning('导入表头与模板不一致');
      loading.value = false;
      return
    }
  }

  const data = []
  for(const item of results){
    const keys = Object.keys(item)
    const newItem = {}
    keys.forEach(key => { newItem[mapLabelToProp.get(key)] = item[key] })
    data.push(newItem)
  }

  loading.value = false;
  const requiredProps = requireFields.map(({ prop }) => prop)
  const requiredMessage = requireFields.map(({ label }) => label).join('、')


  const requiredLines = []
  for(const index in data){
    const item = data[index]
    const keys = Object.keys(item)

    keys.forEach((key) => {
      if(requiredProps.includes(key) && String(item[key]).trim() === '' && requiredLines.indexOf(Number(index) + 1) === -1){
        requiredLines.push(Number(index) + 1)
      }
    })
  }

  if(requiredLines.length > 0){
    ElMessage.error(`第 ${requiredLines.join(",")} 行，${requiredMessage}不能为空。`);
    loading.value = false;
    return;
  }

  tableData.value = data
}


//提交
const handleSubmit = async () => {
  if (loading.value) return;
  let list = []
  const errors = []

  tableData.value.forEach(({goodOpenCatCode}, index) => {
    const reg = /^\d+(\.\d+)?$/;
    if(!goodOpenCatCode || !reg.test(String(goodOpenCatCode).trim())){ errors.push(index + 1) }
  })

  if(errors.length !== 0){
    ElMessage.warning('只允许导入有类目信息的采购单')
    return
  }

  
  tableData.value.forEach(item => {
    const { itemId, code, num, total_amount, good_price } = item
    list.push({ itemId, code, num, good_price, total_amount, remark: '' })
  });

  loading.value = true;
  const { code, message } = await httpInvoiceBatch({ order_type: '2', list });
  loading.value = false;


  responseHandle({
    code,
    message,
    handler: () => {
      ElMessage.success("数据导入成功！");
      emit("onSuccess");
      visible.value = false;
    }
  });
};


const cancel = () => {
  tableData.value = [];
};
defineExpose({
  onDisplay: () => ((visible.value = true), (tableData.value = []))
});
</script>

<template>
  <el-dialog
    :close-on-click-modal="false"
    v-model="visible"
    title="批量导入发票与订单关联结果"
    width="1040px"
    top="8vh"
    center
  >
    <execlUpload @on-success="Uploadsuccess" v-if="tableData.length === 0" />

    <el-table
      :data="tableData"
      stripe
      border
      max-height="500px"
      size="small"
      style="width: 100%"
    > 
      <el-table-column v-for="(column, index) in columns" :key="index" :label="column.label" :prop="column.prop" :width="column.width" show-overflow-tooltip>
        <template #header>
          <span v-if="!column.required">
            {{ column.label }}
          </span>

          <p v-else>
            <span style="color: #f56c6c; font-size: 14px">* </span>
            {{ column.label }}
          </p>
        </template>

        <template #="{ row }">
          <template v-if="column.child">
            <el-table-column   v-for="children in column.child" :prop="children.prop" :label="children.label" :width="children.width" show-overflow-tooltip>
              <template #header>
                <span v-if="!children.required">
                  {{ children.label }}
                </span>
              
                <p v-else>
                  <span style="color: #f56c6c; font-size: 14px">* </span>
                  {{ children.label }}
                </p>
              </template>
            </el-table-column>
          </template>

          <template v-else>{{ row[column.prop] }}</template>
        </template>
      </el-table-column>
    </el-table>
    <div
      flex
      justify-end
      gap-2
      v-if="tableData.length !== 0"
      style="padding: 10px 0 0 0"
    >
      <el-button size="small" @click="cancel">取消</el-button>
      <el-button
        size="small"
        type="primary"
        :loading="loading"
        @click="handleSubmit"
        >保存</el-button
      >
    </div>
  </el-dialog>
</template>

<style lang="scss" scoped>
:deep(.el-upload-list__item) {
  display: none !important;
}
</style>
