<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 { httpBatchCheck } from "/@/api/invoiceInOut/inOutManager";
import { mapLabelToSource, mapLabelToType } from "../../config/shared";
import ImportTableColumn from "/@/components/importTableColumn/index.vue"
import { useCompany } from "/@/hooks/core";





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

const emit = defineEmits(["refresh"]);
const props = defineProps<{ visible: boolean }>()
const { getCurrentLicense } = useCompany()
const visible = useVModel(props, 'visible')
const responseHandle = useResponseHandle();
const headerState = ref({ visible: false, importColumns: [], columns: [] })

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

  let headok = true;

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

      }
    });
  }
  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 => {
      const prop = mapLabelToProp[label]
      item[prop] = tableItem[label]
    })

    result.push(item)
  }

  const license = getCurrentLicense()
  const inv_buyer_codes = [...new Set(result.map(({ buyer_code }) => buyer_code))]
  console.log(inv_buyer_codes)

  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,  check_type: mapLabelToType[item.check_type] }) })

    const isNoDiffNum = []
    tableData.value.forEach((row, index) => {
      if(Number(row.balance_num) === Number(row.check_num)){ isNoDiffNum.push(index + 1) }
    })

    if(isNoDiffNum.length !== 0){
      ElMessage.warning('第' + isNoDiffNum.join('、') + '行,盘点数量和库存一致不允许导入')
      loading.value = false
      return
    }

    const { code, message, data: _d } = await httpBatchCheck({ 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>


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

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