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

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

const visible = ref(false);
const loading = ref(false);


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


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

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

  let headOk = true;
  const initHeader = initialColumns.map(({ label }) => label)
  if (header.length !== initialColumns.length) {
    headOk = false;
  } else {
    initHeader.forEach((si, sii) => { 
      const label = header[sii].replace('*', '')
      if (si !== label) { headOk = false; }
    });
  }

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

  tableData.value = [];
  let isDateError = false
  
  try {

    const platErrors = []
    const comErrors = []
    const isDateError = []


    results.forEach((v1, index) => {
      const item: Record<string, any> = {}
      Object.keys(v1).forEach(label => { item[getPropertyAsLabel(label)] = v1[label] })
      const regex = /^\d{4}-\d{2}-\d{2}$/;
      if(!regex.test(String(item.tradeTime))){
        isDateError.push(index + 1)
      }
      // const { goodNum, com_total, comPrice, platPrice, plat_total } = item
      // if( Number(goodNum) * Number(comPrice)  !== Number(com_total)){
      //   comErrors.push(index + 1)
      // }
      // if( Number(goodNum) * Number(platPrice)  !== Number(plat_total)){
      //   platErrors.push(index + 1)
      // }
      tableData.value.push(item);
    });

    // if(platErrors.length !== 0){
    //   loading.value = false;
    //   tableData.value = []
    //   ElMessage.warning(`第${platErrors.join(',')}行,产品数量*平台收入单价必须等于平台收入总价`)
    //   return
    // } else if(comErrors.length !== 0) {
    //   loading.value = false;
    //   tableData.value = []
    //   ElMessage.warning(`第${platErrors.join(',')}行,产品数量*业务公司收入单价必须等于业务公司收入总价`)
    //   return
    // }


    const companies = [...new Set(tableData.value.map(({companyNo}) => companyNo))]
    console.log(companies)

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

     if(companies[0] !== currentCompany.value.companyNo){
      ElMessage.warning('上传数据的收款方公司与当前选中的业务公司不一致')
      tableData.value = []
      return
     }

    loading.value = false;
    if(isDateError.length !== 0){
      tableData.value = []
      ElMessage.error(`第${isDateError.join(',')}行,交易时间格式错误,格式为: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 = [];

  const requestProperties = initialColumns.filter(item => !!item.required).map(({prop}) => prop)

  tableData.value.forEach(keys => {
    let item: Record<string, any> = {}

    for (let key in keys) {
      item[key] = keys[key]
      if (requestProperties.includes(key) && !keys[key]) {  isOk = false;  }
    }
    
    data.push({ ...item, trade_fee: item.com_total, trade_type: '1', trade_remark: '' });
  });

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

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

  const { code, message } = await httpUpload({ data });
  loading.value = false;

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

const cancel = () => { tableData.value = []; };
defineExpose({ onDisplay: () => {
  console.log(requsetHeaderIdxs)
  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
  >
    <execlUpload
      v-if="tableData.length === 0"
      @on-success="Uploadsuccess" 
    />
    
    <el-table
      stripe
      border
      size="small"
      :data="tableData"
      max-height="500px"
      style="width: 100%"
    >
      <el-table-column
        v-for="(si, sii) in columnsConfig"
        :width="si.width"
        :fixed="si.fixed"
        :type="si.type"
        :prop="si.prop"
        :key="sii"
        show-overflow-tooltip
      >
        <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"
    >
      <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>
