import { h } from "vue";
import { columns } from "./template";
import { ElMessage, ElMessageBox } from "element-plus";

/**
 * 校验表头和导入表的表头是否一致
 * @param header 原表头
 * @param importHeader 导入表的表头
 * @return { Boolean }
 * 
*/
export function validateImportHeader(header: Array<any>, importHeader: Array<any>) {
  // console.log(header.length, importHeader);
  if (header.length !== importHeader.length) {
    ElMessage.warning('导入的模板格式不正确');
    return false;
  }

  for (const index in header) {
    // console.log(header[index].label, importHeader[index])
    if (header[index].label === importHeader[index]) continue;
    ElMessage.warning('导入的模板格式不正确');
    return false;
  }


  return true;
}


const mapTemplatePropToProp = columns.reduce((prev, curr) => ({ ...prev, [curr.label]: curr.prop }), {})
export function formatImportData(results: Array<any>) {
  const data: Array<any> = [];
  for (const result of results) {
    const item = {};
    for (const key in result) {
      item[mapTemplatePropToProp[key]] = result[key];
    }
    data.push(item);
  }
  return data;
}



const mapPropToLabel = columns.reduce((prev, curr) => ({ ...prev, [curr.prop]: curr.label }), {})
const requiredProps = columns.filter(item => item.required).map(item => item.prop);
const numberProps = columns.filter(item => item.number).map(item => item.prop);
const isEmpty = (value: string) => value === '' || value.trim() === '';


const number_reg_exp = /^\d+(\.\d+)?$/;
const reg = new RegExp("[`~!@#$^&*()=|{}':;',\\[\\].<>/?~！@#￥……&*（）——|{}【】‘；：”“’。，、？]")

export function validateData(data: Array<Record<string, string>>) {
  let errorSet = [];
  for (const index in data) {
    let error: string[] = [];
    const item = data[index];
    for (const prop in item) {
      let value = String(item[prop]);
      
      if (requiredProps.includes(prop) && isEmpty(value)) { // 校验必填
        error.push(`${mapPropToLabel[prop]}不能为空`)
      }

      if (numberProps.includes(prop) && (number_reg_exp.test(value) === false)) {
        error.push(`${mapPropToLabel[prop]}必须为数字`)
      }


      if(prop === 'remark'){
        // 1. 回车空格替换
        value =  value.replace(/[\s\r\n]+/g, '')
        item[prop] = value;
        // 2. 不能有标点符号
        if(reg.test(value)){
          error.push(`${mapPropToLabel[prop]}不能包含标点符号`)
        }
      }
    }
    if (error.length !== 0) { errorSet.push({ index: Number(index) + 1, error: error.join(',') }) }
  }

  return {
    errorSet,
    isValid: errorSet.length === 0
  };
}


export function showErrorSet(errorSet: Array<Record<string, string>>) {
  const errorList = errorSet.map(item => `第 ${item.index} 行：${item.error}`);
  ElMessageBox({
    title: '数据校验失败', type: 'warning',
    message: h('div', null, errorList.map(error => h('p', null, error))),
  })
}
