<script setup lang="ts">
import { ref } from "vue";
import { httpUpload } from "/@/api/InvoiceSales/capitalClaim";
import {
  initheaders,
  columns,
  requireHeaders,
  requsetHeaderIdxs
} from "./columns-config";
import { ElMessage, ElNotification } from "element-plus";
import { responseHandle } from "/@/utils/responseHandle";
import { useNav } from "/@/layout/hooks/nav";
import { execlUpload } from "/@/components/execlUpload";
import { useCompany } from "/@/hooks/core/useCompany";

const emit = defineEmits(["onSuccess"]);

const visible = ref(false);
const loading = ref(false);
const tableData = ref([]);
const columnsConfig = columns();
const { logout } = useNav();
const { currentCompany } = useCompany();

const visibleHeader = ref(false)
const importHeader = ref([])

const handleClose = () => {
  // execlFile.value = null;
  // uploadRef.value.clearFiles();
};


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

  let headok = true;
  if (header.length !== initheaders.length) {
    headok = false;
  } else {
    initheaders.forEach((si, sii) => {
      if (si !== header[sii]) {
        headok = false;
      }
    });
  }

  if (!headok) {
    visibleHeader.value = true
    importHeader.value = [...header]
    loading.value = false;
    return;
  }
  tableData.value = [];

  let isDateError = false

  try {
    results.forEach(v1 => {
      const b = Object.values(v1);
      let model = {};
      b.forEach((si, sii) => {
        model["value" + sii] = si + "";
      });

      if(model.value6.indexOf('-') === -1){
        isDateError = true
      }

      tableData.value.push(model);
    });
    loading.value = false;

    const companies = [...new Set(tableData.value.map(({value0}) => value0))]
    if(companies.length !== 1){
     ElMessage.warning('上传数据的收款方公司必须为同一家公司')
     tableData.value = []      
     return
    }

    if(companies[0] !== currentCompany.value.companyNo){
     ElMessage.warning('上传数据的收款方公司与当前选中的业务公司不一致')
     tableData.value = []
     return
    }
 
    if(isDateError){
      tableData.value = []
      ElMessage.error("交易时间格式错误,应为:2020-01-01");
      return
    }
  } catch (e) {
    ElMessage.error("导入数据拼接有误！");
    loading.value = false;
  }
};


const mapToProp = {
  value0: 'companyNo',
  value1: 'trade_in',
  value2: 'trade_in_account',
  value3: 'NdCode',
  value4: 'poCode',
  value5: 'customerName',
  value6: 'tradeTime',
  value7: 'trade_fee',
  value8: 'balance',
  value9: 'trade_bank',
  value10: 'trade_account',
  value11: 'trade_out',
  value12: 'trade_used',
}

//提交
const handleSubmit = async () => {
  if (loading.value) return;
  loading.value = true;
  let isok = true, isnum = true, data = [];

  tableData.value.forEach(key => {
    let item = {}
    for (let i in key) {
      if (requsetHeaderIdxs.includes(i) && !key[i]) { isok = false; }
      item[mapToProp[i]] = key[i]
    }
    const newItem: Record<string, any> = { ...item, trade_type: '0' ,trade_remark: '' }
    const { companyNo, trade_in, trade_fee } = newItem
    newItem.trade_in_code = companyNo
    newItem.companyName = trade_in
    newItem.com_total = trade_fee
    data.push(newItem);
  });

  // console.log(data)
  // return

  if (!isok) {
    ElNotification({
      title: "必填字段缺失！",
      type: "error"
    });
    loading.value = false;
    return;
  }


  if (!isnum) {
    ElMessage.error("收入金额只能为正数！");
    loading.value = false;
    return;
  }




  const { code, message } = await httpUpload({ data });
  responseHandle({
    code,
    message,
    logout,
    handler: () => {
      loading.value = false;
      ElMessage.success("数据导入成功！");
      emit("onSuccess");
      visible.value = false;
    }
  });
};

const cancel = () => { tableData.value = []; };
defineExpose({ onDisplay: () => ((visible.value = true), (tableData.value = [])) });
</script>

<template>
  <el-dialog
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    v-model="visible"
    title="导入客户付款资金数据"
    width="1040px"
    top="8vh"
    center
    @close="handleClose"
  >
    <execlUpload @on-success="Uploadsuccess" v-if="tableData.length === 0" />
    <el-table
      stripe
      border
      size="small"
      :data="tableData"
      max-height="500px"
      style="width: 100%"
    >
      <el-table-column
        v-for="(si, sii) in columnsConfig"
        :type="si.type"
        :minWidth="si.minWidth"
        :fixed="si.fixed"
        :key="sii"
        :prop="si.prop"
        show-overflow-tooltip
      >
        <template #header>
          <span
            v-if="!requireHeaders.includes(si.label) || si.label === '序号'"
            >{{ 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"
    >
      <el-button size="small" @click="cancel">取消</el-button>
      <el-button
        size="small"
        type="primary"
        :loading="loading"
        @click="handleSubmit"
        >保存</el-button
      >
    </div>

    <el-dialog v-model="visibleHeader" title="导入文件表头与模板表头不一致,当前导入文件表头为:" :close-on-click-modal="false"
    :close-on-press-escape="false">
      <el-table border size="small">
        <el-table-column v-for="column in importHeader" fit :label="column.indexOf('UNKNOWN') !== -1 ? '' : column" />
      </el-table>
    </el-dialog>
  </el-dialog>
</template>

<style lang="scss" scoped>
:deep(.el-upload-list__item) {
  display: none !important;
}
</style>
