import { requiredColumns, mapPropertyToLabel } from "./columns"
import { ElMessage, ElMessageBox } from "element-plus"
import { isEmail } from "/@/utils/validate";
import { h } from "vue"
import { error } from "console";


const requiredProps = requiredColumns.map(({ prop }) => prop)

export function isValidHeader(header: any[], importHeader: any[]){
  if(header.length !== importHeader.length){
    ElMessage.warning('导入文件表头与模板不一致')
    return false
  }

  for(const index in header){
    const head = header[index].trim()
    const importHead = importHeader[index].trim()
    if(head !== importHead){
      ElMessage.warning('导入文件表头与模板不一致')
      return false
    }
  }

  return true
}


function isValidGroupNumber(results){
  const groups = [...new Set(results.map(({ group }) => group))]

  if(groups[0] != 1){
    ElMessage.warning('分组编号必须从1开始')
    return false
  }

  const max = groups[groups.length - 1]
  const nGroup = Array(Number(max)).fill(0).map((_, index) => index + 1)
  
  if(groups.length !== nGroup.length){
    // const nums = nGroup.filter(group => !groups.includes(group))
    // ,缺少分组: ' + nums.join('、')
    ElMessage.warning('分组必须为连续编号')
    return false
  }
  
  return true
}


function onDisplayErrorMessage(errors, isGroup = false){
  ElMessageBox({
    type: 'warning',
    title: isGroup ? '分组校验失败' : '数据校验失败',
    message: h('div', { style: 'display: flex, flex-direction:column' }, {
      default: () => Object.keys(errors).reduce((prev, index) => {
        return [
          ...prev,
          h('p',{}, '第' + index + (isGroup ? '组, ' : '行, ') + errors[index])
        ]
      }, [])
    })
  })
}

function isValidRequired(results: any[], currentInvoiceTypes: any[]){
  const allInvTypes = currentInvoiceTypes.map(({label}) => label)
  const errors = {}
    
  for(const sourceIndex in results){
    const item = results[sourceIndex]
    const index = item.rawIndex

    let isEmailError = false
    let isPoCodeError = false
    let isInvTypeError = false
    let isPlatformError = false

    for(const key in item){
      const value = item[key]
      if(requiredProps.includes(key) && (!value || !String(value).trim())){
        if(errors[index]) {
          errors[index] = errors[index] += '、' + mapPropertyToLabel[key]
        } else{
          errors[index] = mapPropertyToLabel[key]
        }
      } else if(key === 'email' && !isEmail(value)){
        isEmailError = true
      } else if(key === 'poCode'){
        const prefix = value.slice(0, 5)
        const suffix = value.slice(5)

        if(prefix !== 'PO-YL'){
          isPoCodeError = true
        } else if(!((/\d{2}-\d{4}-\d{4,8}$/).test(suffix))) {
         isPoCodeError = true 
        }
      } else if(key === 'invtype' && !allInvTypes.includes(value)){
        isInvTypeError = true
      } else if(key === 'platform_type' && !['toB', 'toC'].includes(value)){
        isPlatformError = true
      }
    }

    if(errors[index]){  
      errors[index] += '不能为空' 
      if(isEmailError) errors[index] += ',邮箱格式不正确'
      if(isPoCodeError) errors[index] += ',平台采购PO格式不正确'
      if(isInvTypeError) errors[index] += ',发票类型格式不正确必须为:' + allInvTypes.join('、')
      if(isPlatformError) errors[index] += ',订单平台类型格式不正确'
    }else{
      if(isEmailError) errors[index] = '邮箱格式不正确'
      if(isPoCodeError) errors[index] = '平台采购PO格式不正确'
      if(isInvTypeError) errors[index] = '发票类型格式不正确必须为'+ allInvTypes.join('、')
      if(isPlatformError) errors[index] = '订单平台类型格式不正确'
    }
  }


  if(Object.keys(errors).length === 0){
    return true
  } else {
    onDisplayErrorMessage(errors)
    return
  }
}

function isValidGroup(results: any[]){
  const groups = [...new Set(results.map(({ group }) => group))]
  
  const mapGroupToData:Record<string, any> = {}
  for(const group of groups){
    mapGroupToData[group] = results.filter(item => item.group === group)
  }

  const errors = {}

  for(const group of Object.keys(mapGroupToData)){
    const groupData = mapGroupToData[group]
    let isHasDuplicateData = false
    let isOverflow = false

    if(groupData.length > 10) { 
      isOverflow = true 
    } else {
      let map = {}
      const noDuplicateFields = []

      /* 检验平台同一组数据平台类型是一致 */
      const isHasNoDuplicatePlatformType = [...new Set(groupData.map(({ platform_type }) => platform_type))].length != 1
      if(isHasNoDuplicatePlatformType){ noDuplicateFields.push('订单平台类型') }
      /* 校验邮箱同一组数据邮箱是否一致 */
      const isHasNoDuplicateEmail =  [...new Set(groupData.map(({ email }) => email))].length != 1
      if(isHasNoDuplicateEmail){ noDuplicateFields.push('邮箱') }
       /* 校验邮箱同一组数据邮箱是否一致 */
       const isHasNoDuplicateInvType =  [...new Set(groupData.map(({ invtype }) => invtype))].length != 1
       if(isHasNoDuplicateInvType){ noDuplicateFields.push('发票类型') }
       if(noDuplicateFields.length !== 0){ errors[group] = noDuplicateFields.join('、') }



      groupData.forEach(item => {
        const { sequenceNo, poCode } = item
        /* 校验订单号+po号必须不能重复 */
        const symbol = sequenceNo + '-' + poCode
        if(map[symbol]){
          isHasDuplicateData = true
        } else{
          map[symbol] = true
        }
      })
    }

    if(errors[group]){ 
      errors[group] += ',同一分组内必须一致' 
      if(isOverflow) errors[group] += ',分组数据不能超过十条'
      if(isHasDuplicateData) errors[group] += ',分组订单编号和平台采购PO不能重复'
      
    }else{
      if(isOverflow) errors[group] = '分组数据不能超过十条'
      if(isHasDuplicateData) errors[group] = '分组订单编号和平台采购PO不能重复'
    }
  }

  if(Object.keys(errors).length === 0){
    return true
  } else {
    onDisplayErrorMessage(errors, true)
    return
  }
}


export function isImportDataValid(results: any[], currentInvoiceTypes: any[]){
  /* 校验必填字段是否填入 */
  if(!isValidRequired(results, currentInvoiceTypes)){ return false }
  /* 校验分组是否合理 */
  if(!isValidGroupNumber(results)) { return false }
  /* 校验分组数据数字是否合理 */ 
  if(!isValidGroup(results)) { return false }
  return true
}
