<script setup lang="ts">
import { ref } from "vue";
import { columns, mapLabelToProp } from "./columns-config";
import { httpAdd } from "/@/api/invoiceInOut/inOutManager";
import { ElButton, ElDialog, ElMessage } from "element-plus";
import { execlUpload } from "/@/components/execlUpload";
import { mapLabelToType } from "../../config/shared";
import { mapLabelToInvtype } from "/@/utils/status";
import { isImportDataValid } from "./validator";
import { useResponseHandle } from "/@/hooks";
import { useVModel } from "@vueuse/core";


const props = defineProps<{ visible: boolean }>()
const emit = defineEmits(["refresh"]);

const tableData = ref([]);
const loading = ref(false);

const visible = useVModel(props, 'visible')
const responseHandle = useResponseHandle();

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

  let headok = true;

  if (header.length !== columns.length - 1) {
    headok = false;
  } else {
    columns.slice(1).forEach((si, sii) => {
      if (si.label !== header[sii]) { 
        headok = false; 
      }
    });
  }

  if (!headok) {
    ElMessage.error("表头与导入模板不匹配！");
    loading.value = false;
    return;
  }

  tableData.value = [];

  const result = []
  for(const tableItem of results){
    const item = {}
    Object.keys(tableItem).forEach(label => {
      const prop = mapLabelToProp[label]
      item[prop] = tableItem[label]
    })
    result.push(item)
  }

  if(isImportDataValid(result)){ tableData.value = result }
  loading.value = false;
};

//提交
const handleSubmit = async () => {
  try {
    if (loading.value) return;
    loading.value = true;

    const list = [];

    tableData.value.forEach(item => {
      list.push({ 
        ...item, 
        inv_type: mapLabelToInvtype[item.inv_type],
        relaArr: [{ id: 1, num: item.num }],
        type: mapLabelToType[item.type],
        platform_type: '2',
        goodType: '1',
        cat_code: '0',
        cat_name: '0',
        channel: '3',
        source: '1',
        unit: '0',
        tax: '0'
      })
    })

    const { code, message, data: _d } = await httpAdd({ list });

    loading.value = false;

    responseHandle({
      code,
      message,
      noMessage: false,
      handler: () => {
        ElMessage.success("数据导入成功！");
        emit("refresh");
        visible.value = false;
      }
    });
  } catch (err) { 
    console.log(err)
  }
};
const cancel = () => {
  tableData.value = [];
};
</script>

<template>
  <ElDialog
    v-model="visible"
    :close-on-click-modal="false"
    title="C端无发票订单出库"
    width="1040px"
    top="8vh"
    center
  >
    <execlUpload style="margin-bottom: 10px" @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="(si, sii) in columns"
        :minWidth="si.minWidth"
        show-overflow-tooltip
        :fixed="si.fixed"
        :prop="si.prop"
        :type="si.type"
        :key="sii"
      >
        <template #header>
          <span v-if="!si.required">
            {{ si.label }}
          </span>
          
          <p v-else>
            <span style="color: #f56c6c; font-size: 14px">* </span>
            {{ si.label }}
          </p>
        </template>
      </el-table-column>
    </el-table>
    <div
      flex
      justify-end
      gap-2
      v-if="tableData.length !== 0"
      style="padding: 10px 0 0 0"
    >
      <ElButton size="small" @click="cancel">取消</ElButton>
      <ElButton
        size="small"
        type="primary"
        :loading="loading"
        @click="handleSubmit"
      >保存</ElButton>
    </div>
  </ElDialog>
</template>

<style lang="scss" scoped></style>
