<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 { mapGoodLabelToType } from "/@/utils/status";
import { isImportDataValid } from "./validator";
import { useResponseHandle } from "/@/hooks";
import { useVModel } from "@vueuse/core";


import ErrorDialog from "/@/components/ErrorDialog/index.vue"
import ImportTableColumn from "/@/components/importTableColumn/index.vue"


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

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

const errorState = ref({ visible: false, list: [], title: '' })
const headerState = ref({ visible: false, importColumns: [], columns: [] })

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]) { 

        console.log(si.label, header[sii])
        headok = false; 
      }
    });
  }

  if (!headok) {
    headerState.value.visible = true
    headerState.value.importColumns = [...header]
    headerState.value.columns = columns.slice(1).map(({ label }) => label)
    loading.value = false;
    return;
  }

  tableData.value = [];

  const result = []
  for (const tableItem of results) {

    const item = {}
    Object.keys(tableItem).forEach((label, index) => {
      const prop = mapLabelToProp[label.replace('_1', '')]
      let value = tableItem[label]
      if (label === '发票类型') {
        value = value.replace('(', '（')
        value = value.replace(')', '）')
      }

      item[prop] = value ? String(value).trim() : value
    })

    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_price: '',
        inv_unit: '',
        inv_subprice: '',
        inv_type: '',
        inv_good_name: item.goodName,
        inv_seller_code: item.seller_code,
        inv_buyer_code: item.buyer_code,
        inv_seller_name: item.seller_name,
        inv_buyer_name: item.buyer_name,
        relaArr: [{ id: item.relaGoodNo, num: item.relaGoodNum }],
        type: mapLabelToType[item.type],
        platform_type: '2',
        goodType: mapGoodLabelToType[item.goodType],
        cat_code: '0',
        cat_name: '0',
        channel: '3',
        source: '1',
        // unit: '0',
        tax: '0',
        inv_tax: '0',
        inv_cat_code: '0',
      })
    })

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

    if (code == 1004 && _d) {
      errorState.value.visible = true
      errorState.value.list = _d
      errorState.value.title = message
      return
    }

    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>

    <ErrorDialog 
      v-model:visible="errorState.visible" 
      :list="errorState.list" 
      :title="errorState.title" 
    />

    <ImportTableColumn 
      v-model:visible="headerState.visible" 
      :import-columns="headerState.importColumns"
      :columns="headerState.columns" />
  </ElDialog>
</template>

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