<script setup lang="ts">
import { ref, h } from "vue";
import { ElButton, ElDialog, ElMessage } from "element-plus";
import { execlUpload } from "/@/components/execlUpload";
import { useResponseHandle } from "/@/hooks";
import { useVModel } from "@vueuse/core";

import { columns, mapLabelToProp } from "./columns-config";
import { isImportDataValid } from "./validator";
import { httpAdd } from "/@/api/invoiceInOut/inOutManager";
import { mapLabelToSource, mapLabelToType } from "../../config/shared";
import { mapLabelToInvtype } from "/@/utils/status";



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

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

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],
        source: mapLabelToSource[item.source], 
        type: mapLabelToType[item.type],
        buyer_name: item.inv_buyer_name,
        buyer_code: item.inv_buyer_code,
        platform_type: '1',
        channel: '1',
        goodType: '1'
      })
    })

    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="订单商品导入"
    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>
      <el-button
        size="small"
        type="primary"
        :loading="loading"
        @click="handleSubmit"
        >保存</el-button
      >
    </div>
  </ElDialog>
</template>

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