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

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


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

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

const { getCurrentLicense } = useCompany()
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;
  console.log(header.length, columns.length - 1)

  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]
      let value = tableItem[label]

      if (label === '发票类型') {
        value = value.replace('(', '（')
        value = value.replace(')', '）')
      }

      // const labels = ['税率', '销售方公司纳税号', '购买方纳税号', '单位']
      // if (labels.includes(label.replace('_1', ''))) {

      //   if ((prop || "").includes('inv_')) {
      //     item[prop.replace('inv_', '')] = value
      //   } else {
      //     const prop = mapLabelToProp[label.replace('_1', '')]
      //     item[prop] = value
      //   }
      // } else {
      // }

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

    result.push(item)
  }

  const license = getCurrentLicense()
  const inv_buyer_codes = [...new Set(result.map(({ inv_buyer_code }) => inv_buyer_code))]
  if (inv_buyer_codes.length !== 1) {
    ElMessage.warning('导入数据的购买方公司必须一致')
    return
  }

  if (inv_buyer_codes[0] !== license) {
    ElMessage.warning('导入数据购买方公司与当前选择公司不一致')
    return
  }

  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],
        goodType: mapGoodLabelToType[item.goodType],

        inv_num: Number(item.inv_num).toFixed(8),
        inv_subprice: Number(item.inv_subprice).toFixed(8),
        inv_subtotal: Number(item.inv_subtotal).toFixed(8),
        inv_price: Number(item.inv_price).toFixed(8),
        inv_total: Number(item.inv_tax_total).toFixed(8),

        platform_type: "1",
        channel: "2",
        relaArr: [{  
          id: item.relaGoodNo, 
          num: item.relaGoodNum 
        }]
      })
    })

    // console.log(list)
    // return

    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
    @close="tableData = []"
  >
    <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>
