
import {RegMap} from './TagRegMap'

export function isTagValueEmpty(tag,tagValue)
{
    let obj = tagValue[0]
    let regobj = RegMap[tag]
    for(let key in regobj)
    {
        if(obj[key])
            return false
    }
    return true
}

export function TagV(tag,status,value,tno,mty,t111,seqlist,countMap={})
{
	let regobj = RegMap[tag]
    let obj = value[0]
    let mval = value[1]
     //计算状态 status，是否是必填的，要参考所在序列是否是必填，上一层序列计数，来决定当前序列是否必填  
     if(seqlist && seqlist.length && status == 'M' && isTagValueEmpty(tag,value))
     {
          let curseq = seqlist[seqlist.length - 1]
          let curcnt = countMap[curseq.seqlist] || 0
          if(curseq.status == 'O' &&  curcnt==0)
          {
              status = 'O'
          }
          else if(curseq.status == 'M' && curcnt==0)
          {
              //验证上层是否有计数为O，且上层计数
              for(let i = seqlist.length - 2 ; i >=0;i--)
              {
                      let itemseq = seqlist[i]
                      let itemcnt = countMap[itemseq.seqlist] || 0
                      if(itemcnt>0)
                          break
                      if(itemseq.status == 'O' && itemcnt == 0)
                          status = 'O'
                      
 
              }
          }
     }
 
    let errmsg = null
    if(value.length == 3)
         errmsg = value[2] || {}
    else
    {
        errmsg = {}
        value.push(errmsg)
    }
    let isAllEmpty = true

    for(let key in regobj)
    {
        if(!regobj[key])
        {
            errmsg[key]=""
            continue
        }    
        let reg = regobj[key]
        let val = obj[key] 
        if(!val)
            obj[key]=undefined
        else
        {
             isAllEmpty = false
             //val = FormatAdr(val)

        }   

        if(reg.option=='O')
        {
            if(!val)
            {
                errmsg[key]=""
                if(!val && (tag=='T11R' || tag=='T11S') && (key=='s3' || key=='s4') )
                {
                    if(obj.s3||obj.s4)
                        errmsg[key]="Session Number 、ISN必须同时填写"
                    
                }
                continue
            }
            //校验值
            if(reg.line>1)
            {
                val = formatAdr(val,reg.line,reg.length)
                obj[key] = val
                let line_temp = reg.line
                if(mty== "mt700")   //特殊化处理，放开至800
                {
                    if(tag == 'T45A' || tag == 'T46A' || tag == 'T47A' ||tag == 'T49G' ||tag == 'T49H')
                        line_temp = 800
                }
                else if(mty=="mt707")
                {
                    if(tag == 'T45B' || tag == 'T46B' || tag == 'T47B' ||tag == 'T49M' ||tag == 'T49N')
                        line_temp = 800
                }
                errmsg[key]=TestAdr(val,reg.reg,line_temp,reg.length)
                continue
            }
            if(reg.content == 'AMOUNT' || reg.content == 'NUMBER' || reg.type=='d')
            {
                errmsg[key]=TestAmt(val,reg.length)
                continue
            }
            
            if(!new RegExp(`^${reg.reg}$`).test(val))
            {
                errmsg[key]="请输入正确的格式"
            }   
            continue
        }
        //必填
        if(!val)
        {
            if(status=='M') //栏位已经填了值，或者该栏位必填
                errmsg[key]="请填写必输项"
            else if(mval)
                errmsg[key]="请填写完整"
        }
        else
        {
            //校验值
            if(reg.line>1)
            {
                val = formatAdr(val,reg.line,reg.length)
                obj[key] = val
                let line_temp = reg.line
                if(mty== "mt700")   //特殊化处理，放开至800
                {
                    if(tag == 'T45A' || tag == 'T46A' || tag == 'T47A' ||tag == 'T49G' ||tag == 'T49H')
                        line_temp = 800
                }
                else if(mty=="mt707")
                {
                    if(tag == 'T45B' || tag == 'T46B' || tag == 'T47B' ||tag == 'T49M' ||tag == 'T49N')
                        line_temp = 800
                }
                errmsg[key]=TestAdr(val,reg.reg,line_temp,reg.length)
                continue
            }
            if(reg.content == 'AMOUNT' || reg.content == 'NUMBER' || reg.type=='d')
            {
                errmsg[key]=TestAmt(val,reg.length)
                continue
            }
            
            if(!new RegExp(`^${reg.reg}$`).test(val))
            {
                errmsg[key]="请输入正确的格式"
            }   
        }
    }
    if(isAllEmpty)
    {
        value[1] = ''
        if(status == 'O'){
            for(let ek in errmsg)
            {
                
                    errmsg[ek] = '' 
            }
        }
    }
    for(let ek in errmsg)
    {
        if(errmsg[ek])
            return false
    }
    let msg = gpiValidate(mty,t111,tag,tno,value)
    if(msg)
        return false
    return true
}


function FormatAdr(val)
{
    val = val.replace(/[\\r\\n]{1,2}/g,'\r\n')
    let val_bak = ""
    let lineCount = 0
    let begIndex = 0
    let cur = 0

    while(cur < val.length)
    {

    }


    return val
}

function TestAmt(amt,length)
{
    if(!/^\d+(\.\d*)?$/.test(amt))
    {
        return "请填写正确的金额"
    }
    let idx = amt.indexOf('.')
    if(idx >= 0)
    {
         if(amt.length > length + 1)
            return "数字长度过长"
    }else  
     {
        if(amt.length > length)
            return "数字长度过长"
     }     
    return ""   
}
function  formatAdr(adr,line,length){
    return adr
}
function formatAdr2(adr,line,length)
{
    let arr = []
    let i =0
    let cols = 0
    let wordBegin = 0 
    let wordEnd = 0
    let lines = 0
    let lastLineEnd = -1
    adr = adr.replace(/[\r\n]{1,2}/g,'\n')
    while(i<adr.length)
    {
        let c = adr.charAt(i)
        if(c=='\n')
        {
            lines++
            if(lines >= line) //行数达到
                break;
            arr.push(c)
            cols = 0 //换行列数清零
            wordBegin = arr.length - 1
            lastLineEnd = wordBegin - 1
        }
        else if(!/[0-9A-Za-z]/.test(c))
        {
            wordBegin = -1 //没有捕获到单词
            arr.push(c)
            cols++
        }
        else{
            //其他字符
            if(wordBegin < 0)
                wordBegin = arr.length
            arr.push(c)
            cols++
        }

        if(cols == length+1)
        {
            lines++
            if(wordBegin - lastLineEnd  == 1)   //行开始的单词，超长单词
            {
                if(lines >=line)
                    break;
                arr.splice(arr.length-1,0,'\n')
                wordBegin=arr.length - 1
                lastLineEnd = wordBegin - 1
                cols = 0
            }
            else if(wordBegin > 0)
            {
                cols = arr.length - wordBegin //回溯部分长度
                if(lines >=line)
                {
                       arr.splice(wordBegin,arr.length-wordBegin) //最后一行了，直接不要了 
                       break;
                }
                 
                arr.splice(wordBegin,0,'\n') //插入一个换行符
                lastLineEnd = wordBegin
                wordBegin+=1
            } 
            else 
            {
                if(lines >=line)
                    break;
                arr.splice(arr.length-1,0,'\n')
                wordBegin=arr.length
                lastLineEnd = wordBegin - 1
                cols = 0
            }           
        }
        i++
    }
    return arr.join('')
    // return adr
}

function TestAdr(adr,reg,line,length)
{
    let arr = adr.split(/[\r\n]{1,2}/g)

    let a1 = []
    let a2 = []
    let a3 = []

    for(let i=0;i<arr.length;i++)
    {
        
        if(arr[i].length > length)
            a1.push(i+1)
        else if(arr[i].length == 0 || /^\s+$/.test(arr[i]))
        {
            a3.push(i+1)
        }
        else if(arr[i].length <= length && !new RegExp(`^${reg}$`).test(arr[i]))
            a2.push(i+1)
        
    }
    let linemsg = ''
    if(arr.length > line)
        linemsg = `最多${line}行`
    let msg = []
    if(a1.length)
    {
        msg.push( `第${a1.join(',')}行超过${length}个字符`)
    }
    if(a2.length)
        msg.push(`第${a2.join(',')}行格式非法`)
    if(a3.length)
        msg.push(`第${a3.join(',')}行格式空白行`)
    if(linemsg)
        msg.push(linemsg)
    return msg.join(';')
}


function gpiValidate(mty,t111,tag,tno,value){
    let mval = value[1]
    let errors = value[2]
    if(!mval)
        return
    let lines = mval.split(/[\r\n]{1,2}/g)
    let msg = undefined
    if(tag=='T79' && t111=='fk' && mty=='mt199')
    {
        if(lines.length < 4)
        {
            msg = '至少有4行文字'
            errors.s1 = msg
            return msg
        }
        for(let i=0;i<lines.length;i++)
        {
            if(!lines[i].startsWith("//"))
            {
                msg = '每行必须以\"//\"起头'
                errors.s1 = msg
                return msg
            }
            if(i == 0 && !/^\/\/\d{10}\+\d{4}$/.test(lines[i]))
            {
                msg = '第一行请填写固定的日期和时间偏量'
                errors.s1 = msg
                return msg
            }
            if(i==3 && (lines[i].indexOf("/SHA") > -1 || lines[i].indexOf("/BEN") > -1))
            {
                if(lines.length ==4)
                {
                    msg = '用承担方式为shaben时，请在第五行补充//:71F:明细'
                    errors.s1 = msg
                    return msg
                }else{
                    if(!lines[i+1].startsWith("//:71F:"))
                    {
                        msg = '用承担方式为shaben时后续必须跟//:71F:明细'
                        errors.s1 = msg
                        return msg
                    }
                }

            }
        }
        //暂时屏蔽
        // let first = lines[1]
        
        // if(!/^\/[A-Z0-9]{4}\/([A-Z0-9]{4})?$/.test(first))
        // {
        //     msg = '请在第二行填写正确的状态码——"/状态码/子状态码"'
        //     errors.s1 = msg
        //     return msg
        // }
        // let firstCode = first.substring(1,5)
        // let subCode = first.substring(6)
        // if(mt199_299.indexOf(firstCode) > -1)
        // {
        //     if(firstCode == 'ACSP')
        //     {
        //         if( subCode && ACSP.indexOf(subCode)< 0)
        //         {
        //             msg = '状态码为"ACSP"时，子状态码请填写：'+ACSP.join(',')
        //             errors.s1 = msg
        //             return msg
        //         }
        //     }
        //     else if(firstCode == 'RJCT')
        //     {
        //         if(subCode && PDCR.indexOf(subCode)< 0 )
        //         {
        //             msg = '状态码为"RJCT"时，子状态码请填写：'+RJCT.join(',')
        //             errors.s1 = msg
        //             return msg
        //         }
        //     }
        // }
        // else
        // {
        //     msg = '请在第二行填写以下状态码：'+mt196_199.join(',')
        //     errors.s1 = msg
        //     return msg
        // }    
        
    }
    else if(tag=='T79' && t111=='fk' && mty=='mt299')
    {
        if(lines.length < 4)
        {
            msg = '至少有4行文字'
            errors.s1 = msg
            return msg
        }
        for(let i=0;i<lines.length;i++)
        {
            if(!lines[i].startsWith("//"))
            {
                msg = '每行必须以\"//\"起头'
                errors.s1 = msg
                return msg
            }
            if(i == 0 && !/^\/\/\d{10}\+\d{4}$/.test(lines[i]))
            {
                msg = '第一行请填写固定的日期和时间偏量'
                errors.s1 = msg
                return msg
            }
        } 
        //判断码表 
        //暂时屏蔽
        // let first = lines[1]
        
        // if(!/^\/[A-Z0-9]{4}\/([A-Z0-9]{4})?$/.test(first))
        // {
        //     msg = '请在第二行填写正确的状态码——"/状态码/子状态码"'
        //     errors.s1 = msg
        //     return msg
        // }
        // let firstCode = first.substring(1,5)
        // let subCode = first.substring(6)
        // if(mt199_299.indexOf(firstCode) > -1)
        // {
        //     if(firstCode == 'ACSP')
        //     {
        //         if( subCode && ACSP.indexOf(subCode)< 0)
        //         {
        //             msg = '状态码为"ACSP"时，子状态码请填写：'+ACSP.join(',')
        //             errors.s1 = msg
        //             return msg
        //         }
        //     }
        //     else if(firstCode == 'RJCT')
        //     {
        //         if(subCode && PDCR.indexOf(subCode)< 0 )
        //         {
        //             msg = '状态码为"RJCT"时，子状态码请填写：'+RJCT.join(',')
        //             errors.s1 = msg
        //             return msg
        //         }
        //     }
        // }
        // else
        // {
        //     msg = '请在第二行填写以下状态码：'+mt196_199.join(',')
        //     errors.s1 = msg
        //     return msg
        // }
    }
    else if((tag=='T79' && t111=='zf' && mty=='mt199')
        ||
        (tag=='T79' && t111=='zf' && mty=='mt192') 
    ) //校验状态码
    {
        let first = lines[0]
        
        if(!/^\/[A-Z0-9]{4}\/([A-Z0-9]{4})?$/.test(first))
        {
            msg = '请在第一行填写正确的状态码——"/状态码/子状态码"'
            errors.s1 = msg
            return msg
        }
        let firstCode = first.substring(1,5)
        let subCode = first.substring(6)
        if(mt192_199.indexOf(firstCode) > -1)
        {
            if(subCode && subCode != INDM)
            {
                msg = '子状态码请填写：'+INDM
                errors.s1 = msg
                return msg
            }
        }
        else
        {
            msg = '请在第一行填写以下状态码：'+mt192_199.join(',')
            errors.s1 = msg
            return msg
        }
    }else if(
        (tag=='T76' && t111=='zffk' && mty=='mt196')
        ||
        (tag=='T79' && t111=='zffk' && mty=='mt199')
        )//校验状态码
    {
        let first = lines[0]
        if(lines.length < 2)
        {
            msg = '至少为两行'
            errors.s1 = msg
            return msg
        }
        if(!/^\/[A-Z0-9]{4}\/([A-Z0-9]{4})?$/.test(first))
        {
            msg = '请在第一行填写正确的状态码——"/状态码/子状态码"'
            errors.s1 = msg
            return msg
        }
        let firstCode = first.substring(1,5)
        let subCode = first.substring(6)
        if(mt196_199.indexOf(firstCode) > -1)
        {
            if(firstCode == 'RJCR')
            {
                if( subCode && RJCR.indexOf(subCode)< 0)
                {
                    msg = '状态码为"RJCR"时，子状态码请填写：'+RJCR.join(',')
                    errors.s1 = msg
                    return msg
                }
            }
            else if(firstCode == 'PDCR')
            {
                if(subCode && PDCR.indexOf(subCode)< 0 )
                {
                    msg = '状态码为"PDCR"时，子状态码请填写：'+PDCR.join(',')
                    errors.s1 = msg
                    return msg
                }
            }
        }
        else
        {
            msg = '请在第一行填写以下状态码：'+mt196_199.join(',')
            errors.s1 = msg
            return msg
        }
    }
    

}

const mt199_299 =[
"ACCC",
"ACSP",
"RJCT",
"RETN",
]
const ACSP = [
"G000",
"G001",
"G002", 
"G003", 
"G004", 

]

const RJCT = [
"AC01", 
"AC04", 
"AC06", 
"BE01", 
"NOAS", 
"RR03", 
"FF07", 
"RC01", 
"G004", 
"RC08", 
"FOCR", 
"DUPL", 
"RR05", 
"AM06", 
"CUST", 
"MS03", 

]

const mt192_199=[   //支付发起
"DUPL",
"AGNT",
"CURR",
"CUST",
"UPAY",
"CUTA",
"TECH",
"FRAD",
"COVR",
"AM09",

]
const INDM ="INDM"

const mt196_199=[  //支付反馈
"PDCR",
"CNCL",
"RJCR",


]
const RJCR = [
"LEGL",
"AGNT",
"CUST",
"ARDT",
"NOAS",
"NOOR",
"AC04",
"AM04",
"INDM",
"FRNA",

]

const PDCR = [
"PTNA", 
"RQDA", 
"INDM", 
]


export function SwitchType(mty,t111,tag,value){
    if(!t111 || t111 == 'NONE')
        return
    if(t111 == '001')
        return 'fk'
    let mval = undefined
    if(value && value.length && value.length >1)
        mval = value[1]
    if(!mval)
        return 
    let lines = mval.split(/[\r\n]{1,2}/g)
    console.log(value)
    console.log(mval)
    console.log(lines)
    let first = lines[0] //判断第一行的码
        
    if(first.length < 5)  //长度不够
    {    
        return 
    }
    let firstCode = first.substring(1,5)
    let subCode = first.substring(6)

    if(mt196_199.indexOf(firstCode) > -1)
        return 'zffk'
    
    if(mt192_199.indexOf(firstCode) > -1)
        return 'zf'

}