import React,{Component} from 'react'
import {bindActionCreators} from 'redux';
import {connect} from 'react-redux';
import { updateTreeValue,updateRcvBic,updateSndBic,initSwiftMessageTree ,updateSwiftMessage,initGpiConf} from '../store/modules/swift/swift_action';

import ServiceAPI from './ServiceAPI'
import MessageValidater from './MessageValidater'

import { Form, Input, DatePicker,Row, Col,Button,Icon ,Select,Spin,Steps,Affix,Popconfirm,notification} from 'antd';
const FormItem = Form.Item;

import MTFactory from './MT'

import TagSet from "./Tags"

import {DeepCopy,getLogicAdress} from './Utils'

import {TagV,SwitchType,isTagValueEmpty} from './TagValidater'
import GPIConfig from '../constants/GPIConfig'

import YBIC from './Tags/YBIC'

const Option = Select.Option;

const Step = Steps.Step;


const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 14 },
    };

export  class SWFPage extends Component
{
    
    constructor(props)
    {
        super(props)
        this.state = {rcv_bic:props.rcv_bic,rcv_bic_msg:''}
    }
    
    
    onSave=()=>{
        let msg = []
        this.swfmsg.getValue(msg)
        console.log(msg)
    }

    validateAllMessage=(tags,rs,seqlist=[])=>
    {
        const mty = this.props.params.mty||this.props.extra.msgtyp
        for(let item of tags)
        {
            if(item.tag)
            {
                if(!item.tagValue)
                {
                    item.tagValue = [{},'',{}]
                }
                if(!TagV("T"+item.tag,item.status,item.tagValue,item.tno,mty,this.props.params.t111||this.props.extra.reload_t111,seqlist,this.props.extra.countMap))
                {
                        rs.hasError = true
                        console.log(item.tag)
                        console.log(item.tagValue)
                }
                
            }else if(item.cyclist)
            {
                for(let cyc of item.cycs)
                    this.validateAllMessage(cyc,rs,seqlist)
            }
            else if(item.seqlist)
            {
                for(let seq of item.seqs)
                    this.validateAllMessage(seq,rs,[...seqlist,{status:item.status,seqlist:item.seqlist}])
            }
        }
    }
    scrollError(){
        setTimeout(()=>{
            let obj = document.getElementsByClassName("has-error")
            obj = obj.length?obj[0]:undefined
            if(obj)
            {
                // let oPos = obj.offsetTop - 50
                // document.documentElement.scrollTop = oPos
                // document.body.scrollTop = oPos
                obj.scrollIntoView()
            }
        },100)
    }

    toSwiftMessage=()=>{
        //
        let msg = []
        this.swfmsg.getValue(msg)
        let str = `{4:\r\n${msg.map(item=>`${item.name}:${item.value}\r\n`).join('')}}`
        console.log(str)
        //写循环添加
        const {swift_message_tree,gpi} = this.props
        //判断gpi 信息
        let t111_errmsg = ""
        let t121_errmsg = ""
        if(gpi.inited)
        {
            if(!gpi.t111.value && gpi.t111.required)
            {
                t111_errmsg = '请选择GPI标识类型'
            }
            if(!gpi.t121.value && gpi.t121.required)
            {
                t121_errmsg = '请填写UETR!'
            }
            if(gpi.t121.value)
            {
                let val  = gpi.t121.value
                if(val !=autogenerate && !/^[0-9a-zA-Z]{8}-[0-9a-zA-Z]{4}-[0-9a-zA-Z]{4}-[0-9a-zA-Z]{4}-[0-9a-zA-Z]{12}$/.test(val))
                {
                    t121_errmsg = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx(8-4-4-4-12)"
                } 
            } 
        }

        let tags = swift_message_tree.Tags;
        let arr = []
        let crs = {}
        this.validateAllMessage(tags,crs)
        let rcv_bic_err_msg = validateRCV_BIC(this.props.rcv_bic_info.rcv_bic)
        let snd_bic_err_msg = validateRCV_BIC(this.props.snd_bic_info.snd_bic)

        if(snd_bic_err_msg || rcv_bic_err_msg || crs.hasError || t121_errmsg || t111_errmsg)
        {
            //更新整个树
            notification.error({description:'输入存在错误，请按照提示检查！',message:'错误'})
            this.props.actions.updateSndBic({snd_bic:this.props.snd_bic_info.snd_bic,err_msg:snd_bic_err_msg?snd_bic_err_msg.replace("收","发"):''})
            this.props.actions.updateRcvBic({rcv_bic:this.props.rcv_bic_info.rcv_bic,err_msg:rcv_bic_err_msg})
            gpi.inited && this.props.actions.initGpiConf({  //有gpi 才初始化
                inited:true,
                t111:{...gpi.t111,err_msg:t111_errmsg},
                t121:{...gpi.t121,err_msg:t121_errmsg}
            })
            this.props.actions.updateTreeValue()
            //滚动至第一个错误位置
            this.scrollError()
            return 
        }
        //做整体关联检查
        let wholeErrorMessage = MessageValidater(this.props.extra.msgtyp,swift_message_tree)
        if(wholeErrorMessage)
        {
            notification.error({description:'输入存在错误，请按照提示检查！',message:wholeErrorMessage})
            return 
        }
        this.joinMessage(tags,arr)
        let message = arr.join('\r\n').replace(/[\r\n]{1,2}/g,'\r\n')
        // if(this.props.extra.tdheaders)
        // {
        //     message = `${this.props.extra.tdheaders}:EOH:\r\n${message}\r\n-\r\n`
        // }
        // else
        //  if(this.props.extra.headers)
        // {
        //     message= `${this.props.extra.headers}{4:\r\n${message}`
        // }
        // else {
          //  message = `{1:${getLogicAdress(this.props.snd_bic_info.snd_bic)}0000000000}{2:I${this.props.params.key.substring(2)}${getLogicAdress(this.props.rcv_bic_info.rcv_bic)}N}{4:\r\n${message}\r\n}`
          let gpistr = ':121:ID for UUID generation: TRNPAY3\r\n'
          let mty = this.props.extra.msgtyp.substring(2)
          mty = mty.toUpperCase()
          if(mty!='103'&& mty!='202' && mty!='202COV')
            gpistr= ''
         let s119 = ''
         if(mty=='202COV')
         {
             mty='202'
             s119=':119:COV\r\n'
         }
         
         if(gpi.inited && gpi.t121.value )
        {
                gpistr = ':121:'+gpi.t121.value +"\r\n"   
        }  
        let t111str = ""
        if(gpi.inited && gpi.t111.value )
            t111str = ':111:'+gpi.t111.value +"\r\n"
          message = `:MT:${mty}\r\n:IO:${this.props.rcv_bic_info.rcv_bic}\r\n:II:${this.props.snd_bic_info.snd_bic}\r\n:MP:N\r\n${t111str}${s119}${gpistr}:EOH:\r\n${message}\r\n-\r\n`
        // }
        console.log(message)
        this.props.actions.updateSwiftMessage(message)
        
        let flag = (this.props.params.rcvbic && this.props.params.rcvbic!='NONE') || this.props.params.action=='redit'
        if(flag)
            this.props.history.push("preview/0")
        else 
            this.props.history.push("preview/1")
    }

    getTagValue(item)
    {
        if(typeof item.tagValue =='string' && item.tagValue)
                return item.tagValue
        else if(typeof item.tagValue[1] =='string' && item.tagValue[1])
        {
                let tagValue = item.tagValue[1]
                return tagValue
        }
        return ""
    }
    joinMessage(tags,arr,seqlist,deep=0)
    {
        for(let item of tags)
        {
            if(item.tag)
            {
                if(!item.tagValue)
                    continue
                if(item.tag.indexOf('15')>-1)
                {
                    //15系列字段
                    if(seqlist && this.props.extra.countMap && this.props.extra.countMap[seqlist])
                    {
                        arr.push(`:${item.tag}:`)
                    }
                }
                if(typeof item.tagValue =='string' && item.tagValue)
                    arr.push(`:${item.tag}:${item.tagValue}`)
                else if(typeof item.tagValue[1] =='string' && item.tagValue[1])
                {
                    let tagValue = item.tagValue[1]
                    arr.push(`:${item.tag}:${tagValue}`)
                }else if(this.props.extra.msgtyp == 'mt103')
                {
                    if(deep == 0)
                    {
                        let tag19value = this.getTagValue(tags[18])
                        if(tag19value == 'BEN' || tag19value == 'SHA')
                        {
                            if(item.tno == "7" && item.tag=='33B' && !this.getTagValue(item))
                            {
                                arr.push(`:33B:`)
                            }
                        }

                    }
                }
                if( item.tno=='2' && (this.props.extra.msgtyp == 'mt199' || this.props.extra.msgtyp == 'mt299'))
                {
                    let tag21value = this.getTagValue(item)
                    if(!tag21value)
                        arr.push(`:21:NONREF`)
                }
            }else if(item.cyclist)
            {
                let beginLength = arr.length
                for(let cyc of item.cycs)
                    this.joinMessage(cyc,arr,seqlist,deep+1)
                let endLength = arr.length
                if(deep==0 && endLength == beginLength && this.props.extra.msgtyp == 'mt103' && item.cyclist == '20')
                {
                        let tag19value = this.getTagValue(tags[18])
                        if(tag19value == 'BEN' || tag19value == 'SHA')
                        {
                            arr.push(':71F:')
                        }
                    
                }
            }
            else if(item.seqlist)
            {
                for(let seq of item.seqs)
                    this.joinMessage(seq,arr,item.seqlist,deep+1)
            }
        }
    }
    reload =(flag)=>{

            
            let smhinr = this.props.params.key
            ServiceAPI.getSMH(smhinr).then(data=>{
                
                if(typeof data=='string')
                {
                    data = JSON.parse(data)
                }
                if(data.errorCode !== '0000')
                    return 
                data = data.data
                if(typeof data=='string')
                {
                    data = JSON.parse(data)
                }
                this.props.actions.updateRcvBic({rcv_bic:data.rcv_bic})
                this.props.actions.updateSndBic({snd_bic:data.snd_bic})
                //更新报文树
                this.mty="mt"+data.mty.toLowerCase()
                console.log(data.swift_message)
                this.props.extra.smhinr=smhinr
                this.props.extra.msgtyp="mt"+data.mty.toLowerCase()
                this.props.extra.tdheaders=data.tdheaders
                this.props.extra.headers=data.headers
                let tree = JSON.parse(data.swift_message)
                let gpiconf = {
                    inited:false,
                    t111:{visible:false,value:'',err_msg:'',read:true,required:true},
                    t121:{visible:false,value:'',err_msg:'',read:true,required:true},
                    title:''
                }
                if(data.t111)
                {
                    gpiconf.inited = true
                    gpiconf.t111.visible=true
                    gpiconf.t111.value = data.t111
                    let msgtyp = this.props.extra.msgtyp
                    msgtyp = msgtyp.toUpperCase()
                    if( msgtyp == 'MT202COV')
                    {
                        gpiconf.t111.read = false
                    }
                }
                if(data.t121)
                {
                    gpiconf.inited = true
                    gpiconf.t121.visible = true
                    gpiconf.t121.value = data.t121
                    let msgtyp = this.props.extra.msgtyp
                    msgtyp = msgtyp.toUpperCase()
                    if(data.t121 == autogenerate &&  msgtyp == 'MT202COV')
                    {
                        gpiconf.t121.value = ""   //清理掉202COV的自动生成标记
                    }
                }
                if(gpiconf.inited)
                    this.props.actions.initGpiConf(gpiconf)
                if(data.t111)
                {
                    let tno = 0
                    if(this.mty == 'mt199')
                        tno = 3
                    else if(this.mty == 'mt192')
                        tno = 4
                    else if(this.mty == 'mt196')
                        tno = 3
                    else if(this.mty == 'mt299')
                        tno = 3
                    let tagValue = undefined
                    let tag = undefined
                    if(tno && tree.length >= tno)
                    {
                        tagValue = tree[tno - 1].tagValue
                        tag = tree[tno - 1].tag
                    }
                    console.log(`${this.props.extra.msgtyp},${data.t111},${tag},${tagValue}`)   
                    let t111_type = SwitchType(this.props.extra.msgtyp,data.t111,tag,tagValue)
                    
                    this.props.extra.reload_t111 = t111_type
                }
                this.props.actions.initSwiftMessageTree({Tags:tree,Title:data.title});
            }).catch(err=>{
                console.log(err)
            })
    }
    componentWillMount()
    {
        
        let action = this.props.params.action
        let mctid  = this.props.params.mctid
        this.props.extra.mctid = mctid
        
        if(action == 'edit')
        {
            
            let mty = this.props.params.key;
            mty = mty.toLowerCase()
            if(mty.substring(0,2)!='mt')
                mty = 'mt'+mty
            
            let t111 = this.props.params.t111
            let gpiconf = GPIConfig(mty,t111)
            
            if(!this.props.swift_message_tree)
            {
                let mt_config = MTFactory(mty);
                mt_config = JSON.parse(JSON.stringify(mt_config))
                //给192 止付  11s默认填值
                if(mty == 'mt192' &&  t111=='zf' && mt_config )
                {
                    mt_config.Tags[2].tagValue[0].s1 = '103'
                }
                this.mty=mty
                this.props.extra.msgtyp=mty
                this.props.actions.initSwiftMessageTree(mt_config);
            }
            
            if(!this.props.gpi.inited && gpiconf)
            {
                this.props.actions.initGpiConf({inited:true,
                    t111:{...gpiconf.t111,err_msg:''},
                    t121:{...gpiconf.t121,err_msg:''},
                    title:gpiconf.title
                }) // 初始化gpiinf
            }
            //取BIC
            let rcvbic = this.props.params.rcvbic
            if(!rcvbic || rcvbic != 'NONE')
            {
                this.isdirect= true;
                if(!this.props.swift_message_tree)
                    this.props.actions.updateRcvBic({rcv_bic:rcvbic})
                
            }
            let sndbic = this.props.params.sndbic
            if(!sndbic || sndbic != 'NONE')
            {
                if(!this.props.swift_message_tree)
                    this.props.actions.updateSndBic({snd_bic:sndbic})
                
            }
        }
        else if(action == 'redit' || action == 'redit2')
        {
            //后端加载SWIFT报文
            this.isdirect= true;
            if(this.props.swift_message_tree)
                return ; //已经拥有编辑树
            this.reload(1)
        }
        
        
    }
  
    render()
    {   
        const {swift_message,rcv_bic_info,snd_bic_info,swift_message_tree,gpi} = this.props
        if(!swift_message_tree)
        {
            return <div style={{textAlign:'center'}}><Spin size="large" /></div>
        }
        let tags = swift_message_tree.Tags;
        let title = swift_message_tree.Title
        const mty = this.props.params.mty||this.props.extra.msgtyp
        const t111 = this.props.params.t111 || this.props.extra.reload_t111
        console.log("mty:"+mty+";t111:"+t111)
        if(mty == 'mt192' && (this.props.params.t111=='zf' || this.props.extra.reload_t111 == 'zf'))
        {
            if(tags.length>=4)
            {
                tags[3].status = 'M'
            }
        }
        let show21Req = false
        if(mty=='mt199')
        {
            if(t111=='fk' || t111 == 'zffk' || t111 == 'zf')
                show21Req = true
        }else if(mty == 'mt192')
        {
            if(t111 == 'zf')
                show21Req = true
        }
        else if(mty == 'mt196')
        {
            if(t111 == 'zffk')
                show21Req = true
        }else if(mty == 'mt299')
        {
            if(t111 == 'fk')
                show21Req = true
        }
        if(show21Req)
        {
            if(tags.length>=2)
            {
                tags[1].status = 'M' //21场设为必填
            }
        }
        let flag1 = (this.props.params.rcvbic && this.props.params.rcvbic!='NONE') || this.props.params.action=='redit' || this.props.params.action=='redit2'
        let flag2 = (this.props.params.sndbic && this.props.params.sndbic!='NONE') || this.props.params.action=='redit' || this.props.params.action=='redit2'
        return   (<div>
                    <Row style={{marginTop:'3em'}}>
                        <Col span={3}/>
                        <Col span={18}>
                                {
                                !flag1?
                                <Steps current={1}>
                                    <Step title="选择类型" description="选择报文类型" />
                                    <Step title="报文编辑" description="编辑报文栏位值" />
                                    <Step title="预览报文" description="预览报文" />
                                    <Step title="编辑完成" description="已完成提交" />
                                </Steps>
                                :
                                <Steps current={0}>
                                    <Step title="报文编辑" description="编辑报文栏位值" />
                                    <Step title="预览报文" description="预览报文" />
                                    <Step title="编辑完成" description="已完成提交" />
                                </Steps>
                                }
                        </Col>
                        <Col span={3}/>
                    </Row>
                     <Row style={{marginTop:"3em"}}>
                        <Col span={3}>
                        </Col>
                        <Col span={8}>
                       
                        <SNDBIC  flag={flag2} snd_bic={snd_bic_info.snd_bic} err_msg={snd_bic_info.err_msg} onChange={(val,msg)=>{snd_bic_info.snd_bic=val;snd_bic_info.err_msg=msg}}/>
                        </Col>
                    </Row>
                    <Row style={{}}>
                        <Col span={3}>
                        </Col>
                        <Col span={8}>
                       {/*<FormItem label="收报行BIC" required {...formItemLayout}>
                                {
                                    this.props.params.action=='redit' || (this.props.params.rcvbic && this.props.params.rcvbic!='NONE')?
                                        <p style={{fontWeight:'bolder',fontSize:'1.2em',paddingBottom:'0em',paddingLeft:'1em',borderBottom:'1px solid #37b8f2'}}>{rcv_bic}</p>
                                        :
                                        <Input placeholder="收报行BIC"  maxLength={11}  value={rcv_bic} onChange={e=>this.props.actions.updateRcvBic(e.target.value)}/>
                                }
                        </FormItem> */}
                        <RCVBIC  flag={flag1} rcv_bic={rcv_bic_info.rcv_bic} err_msg={rcv_bic_info.err_msg} onChange={(val,msg)=>{rcv_bic_info.rcv_bic=val;rcv_bic_info.err_msg=msg}}/>
                        </Col>
                        <Col span={10} />
                        <Col span={3}>
                            <Affix offsetTop={150}>
                                <div style={{textAlign:'right'}}>
                                    <Button  type="primary"   icon="check" title="save" style={{marginRight:'1em',width:'8em'}} onClick={this.toSwiftMessage} >Next  </Button>
                                    <br/>
                                    <br/>
                                    {
                                    this.props.params.action == 'redit'||this.props.params.action == 'redit2'?
                                    <div>
                                        <Popconfirm placement="topLeft" title={"将丢失编辑的内容，确定重新加载？"} onConfirm={this.reload}>
                                            <Button  type="ghost"   icon="reload" title="reload" style={{marginRight:'1em',width:'8em'}}>Reload</Button>
                                        </Popconfirm>
                                        <br/>
                                        <br/>
                                    </div>
                                    :null
                                    }
                                    {
                                    !this.isdirect?
                                    <Popconfirm placement="topLeft" title={"将丢失编辑的内容，确定返回？"} onConfirm={()=>this.props.history.goBack()}>
                                        <Button  type="ghost"   icon="cross" title="cancel" style={{marginRight:'1em',width:'8em'}} >Return</Button>
                                    </Popconfirm>
                                    :null
                                    }
                                </div>
                            </Affix>
                        </Col>
                    </Row>
                    {
                    gpi.inited?
                    <Row>
                        <Row>
                            <Col span={8} offset={3}>
                                <T111 {...gpi.t111} t111={this.props.params.t111||this.props.extra.reload_t111} action={this.props.params.action} mty={mty} onChange={(val,err_msg)=>{gpi.t111.value=val;gpi.t111.err_msg=err_msg}}/>
                            </Col>
                        </Row>
                        <Row>
                            <Col span={16} offset={3}>
                                <T121 {...gpi.t121} t111={this.props.params.t111||this.props.extra.reload_t111} action={this.props.params.action} mty={mty} onChange={(val,err_msg)=>{gpi.t121.value=val;gpi.t121.err_msg=err_msg}}/>
                            </Col>
                        </Row>
                    </Row>
                    :null
                    }
                    <h2 style={{textAlign:'center'}}>
                        {gpi.inited && gpi.title ? gpi.title:
                             title.indexOf("MT")==0?title:`${mty.toUpperCase()} ${title}`}
                    </h2>
                    <Row >
                        <Col span={3}></Col>
                        <Col span={18}>
                        <Row style={{padding:'0.8em 0em',fontSize:'1.2em',backgroundColor:'#5eaee3',color:'white',marginBottom:'2em'}}>
                            <Col span={1} style={{}}><span style={{fontWeight:'bolder',color:'white',marginLeft:'0.5em'}}><Icon type="plus-circle-o" style={{fontSize:'1.2em'}} /></span></Col>
                            {/*<Col span={2} style={{}}><span style={{fontWeight:'bolder'}}>{"Status"}</span></Col>*/}
                            <Col span={3} style={{}}>
                                    <span style={{fontWeight:'bolder'}}>{"Tag"}</span>
                            </Col>
                            <Col span={4} style={{}}><span style={{fontWeight:'bolder'}}>{"Field Name"}</span></Col>
                            <Col span={15}>
                                <span style={{fontWeight:'bolder'}}>{"Content"}</span>
                            </Col>
                            <Col span={1} style={{textAlign:'center'}}><span  style={{fontWeight:'bolder'}}>{"NO."}</span></Col>
                        </Row>
                        <SWFMessage t111={this.props.params.t111||this.props.extra.reload_t111} action={this.props.params.action} extra={this.props.extra} enLock={this.props.params.action=='redit'} updateTreeValue={this.props.actions.updateTreeValue} pattern={tags} ref={ref=>this.swfmsg = ref} mty={mty}/>
                        </Col>
                        <Col span={3}></Col>

                    </Row>
                    </div>
                    )
    }
}

const mapStateToProps = (state) => {
  const {swift_message,rcv_bic_info,snd_bic_info,swift_message_tree,extra,gpi} = state.swift;
  return {
    swift_message,rcv_bic_info,snd_bic_info,swift_message_tree,extra,gpi
  };
};

function mapDispatchToProps(dispatch) {
  return {
    actions: bindActionCreators({ updateTreeValue,updateRcvBic,updateSndBic,initSwiftMessageTree,updateSwiftMessage,initGpiConf }, dispatch)
  };
}

export default connect(mapStateToProps, mapDispatchToProps)(SWFPage)

function validateRCV_BIC(val)
{
    let err_msg = ""
        if(!val)
            err_msg ='请填写收报行BIC'
        else if(!/^[A-Z]{4}[A-Z]{2}[A-Z0-9]{2}([A-Z0-9]{3})?$/.test(val)) 
        {
            err_msg ='请填写正确BIC'
        }
        return err_msg
}

class SNDBIC extends Component{
    constructor(props)
    {
        super(props)
        this.state = {snd_bic:props.snd_bic,err_msg:this.props.err_msg}
    }
    onChange = val=>{
        if((!val && !this.state.snd_bic) || val == this.state.snd_bic)
            return 
        let err_msg = validateRCV_BIC(val)
        
        this.props.onChange(val,err_msg)
        this.setState({snd_bic:val,err_msg})
    }
    componentWillReceiveProps(nextProps)
    {
        this.setState({snd_bic:nextProps.snd_bic,err_msg:nextProps.err_msg})
    }
    render()
    {
       return (<FormItem 
        help={this.state.err_msg}
        validateStatus={this.state.err_msg?'error':null}
       label="发报行BIC" required {...formItemLayout}>
                                {
                                    this.props.flag ?
                                        <p style={{fontWeight:'bolder',fontSize:'1.2em',paddingBottom:'0em',paddingLeft:'1em',borderBottom:'1px solid #37b8f2'}}>{this.state.snd_bic}</p>
                                        :
                                        <Input  addonAfter={ <YBIC pty="jz" onSelect={obj=>this.onChange(obj.bic)} /> }  placeholder="发报行BIC"  maxLength={11}  value={this.state.snd_bic} onChange={e=>this.onChange(e.target.value)}/>
                                }
       </FormItem> )
    }
}

class RCVBIC extends Component{
    
    constructor(props)
    {
        super(props)
        this.state = {rcv_bic:props.rcv_bic,err_msg:this.props.err_msg}
    }
    onChange = val=>{
        if((!val && !this.state.rcv_bic) || val == this.state.rcv_bic)
            return
        let err_msg = validateRCV_BIC(val)
        
        this.props.onChange(val,err_msg)
        this.setState({rcv_bic:val,err_msg})
    }
    componentWillReceiveProps(nextProps)
    {
        this.setState({rcv_bic:nextProps.rcv_bic,err_msg:nextProps.err_msg})
    }
    render()
    {
       return (<FormItem 
        help={this.state.err_msg}
        validateStatus={this.state.err_msg?'error':null}
       label="收报行BIC" required {...formItemLayout}>
                                {
                                    this.props.flag?
                                        <p style={{fontWeight:'bolder',fontSize:'1.2em',paddingBottom:'0em',paddingLeft:'1em',borderBottom:'1px solid #37b8f2'}}>{this.state.rcv_bic}</p>
                                        :
                                        <Input  addonAfter={ <YBIC onSelect={obj=>this.onChange(obj.bic)} /> }  placeholder="收报行BIC"  maxLength={11}  value={this.state.rcv_bic} onChange={e=>this.onChange(e.target.value)}/>
                                }
       </FormItem> )
    }
}

class T111 extends Component{
    constructor(props)
    {
        super(props)
        this.state = {value:props.value,err_msg:props.err_msg}
    }
    componentWillReceiveProps(nextProps)
    {
        this.setState({value:nextProps.value,err_msg:nextProps.err_msg})
    }
    onChange = val=>{
        if((!val && !this.state.value) || val == this.state.value)
            return
        let err_msg = ''
        if(!val && this.props.required)
            err_msg = '请选择GPI标识类型'
        
        this.props.onChange(val,err_msg)
        this.setState({value:val,err_msg})
    }
    render()
    {
       const {mty,t111} = this.props
        let lbl = 'GPI'
        if(mty == 'mt103' || mty=='mt202' || mty=='mt202cov')
            lbl = '111'
        else if(mty=='mt199')
        {
            if(t111=='fk' || t111 == 'zffk' || t111 == 'zf')
                lbl = '111'
        }else if(mty == 'mt192')
        {
            if(t111 == 'zf')
                lbl = '111'
        }
        else if(mty == 'mt196')
        {
            if(t111 == 'zffk')
                lbl = '111'
        }else if(mty == 'mt299')
        {
            if(t111 == 'fk')
                lbl = '111'
        }
        let codes = ['001','002']
        if(mty == 'mt103')
            codes = ['001']
       return  <FormItem help={this.state.err_msg}
       validateStatus={this.state.err_msg?'error':null}
                    label={lbl} required={this.props.required} {...formItemLayout}>
                            
                            <Select size="large" placeholder="选择GPI标识" disabled={this.props.read} value={this.state.value||undefined} style={{ width: '100%' }} onChange={this.onChange}>
                                {
                                    codes.map(val=>(
                                        <Option  value={val} key={val}>{val}</Option>
                                    ))                     
                                }
                            </Select>
                            
                </FormItem> 
    }
}
const autogenerate = "ID for UUID generation: TRNPAY3"
class T121 extends Component{
    constructor(props)
    {
        super(props)
        this.state = {value:props.value,err_msg:props.err_msg}
    }
    componentWillReceiveProps(nextProps)
    {
        this.setState({value:nextProps.value,err_msg:nextProps.err_msg})
    }
    onChange = e=>{
        let val = e.target.value
        if((!val && !this.state.value) || val == this.state.value)
            return
        
        let err_msg = ""
        if(!val && this.props.required  )
        {
            err_msg = "请填写UETR!"
        }
        if(val && val != autogenerate && !/^[0-9a-zA-Z]{8}-[0-9a-zA-Z]{4}-[0-9a-zA-Z]{4}-[0-9a-zA-Z]{4}-[0-9a-zA-Z]{12}$/.test(val))
        {
            err_msg = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx(8-4-4-4-12)"
        }        
        this.props.onChange(val,err_msg)
        this.setState({value:val,err_msg})
    }
    autoClick = e=>{
        let val = autogenerate
        let err_msg = ""
        this.props.onChange(val,err_msg)
        this.setState({value:val,err_msg})
    }
    render()
    {
        let sty = {}
        if(this.state.value == autogenerate)
        {
            sty = {color:'blue'}
        }
        const {mty,t111} = this.props
        let lbl = "UETR"
        if(mty == 'mt103' || mty=='mt202' || mty=='mt202cov')
            lbl = '121'
        else if(mty=='mt199')
        {
            if(t111=='fk' || t111 == 'zffk' || t111 == 'zf')
                lbl = '121'
        }else if(mty == 'mt192')
        {
            if(t111 == 'zf')
                lbl = '121'
        }
        else if(mty == 'mt196')
        {
            if(t111 == 'zffk')
                lbl = '121'
        }else if(mty == 'mt299')
        {
            if(t111 == 'fk')
                lbl = '121'
        }
        
        let helpButtonShow = true
        if(mty == 'mt202cov' || (t111 && t111!='NONE'))
            helpButtonShow = false

    return  <FormItem         labelCol={{span:3}}  wrapperCol={{span:12}}
       help={this.state.err_msg||(!helpButtonShow?'':"点击右侧按钮，可由系统自动生成UETR")}
        validateStatus={this.state.err_msg?'error':"tip"}      
       label={lbl} required={this.props.required} >
                <Input style={sty} addonAfter={!helpButtonShow?null:<Button type="primary" size="small" icon="circle-o-down" title="系统自动生成"  onClick={this.autoClick}/>}  placeholder="UETR:xxxxxxxx-xxxx-xxxx-xxxxxxxxxxxxxxxx(8-4-4-4-12)"  maxLength={36} onChange={this.onChange} value={this.state.value} />
       </FormItem> 
    }
}

export  class MessageArea extends Component{
    fields=[]
    type=-1
    isEnd=false
    name = ""
    cells=[]
    
    constructor(props)
    {
        super(props)
    }
    
    output(buff)
    {
       // this.cells=[] //清空成员
        const fields = this.props.pattern
        return ( 
           <div>
               {
                    fields.map((item,index)=>{
                            if(item.tag)
                                return <Tag extra={this.props.extra} action={this.props.action} t111={this.props.t111} enLock={this.props.enLock} updateTreeValue={this.props.updateTreeValue} pattern={item} seqlist={this.props.seqlist} key={item.tno}  mty={this.props.mty}/>
                            if(item.cyclist)
                                return <CYCList extra={this.props.extra} action={this.props.action} t111={this.props.t111} enLock={this.props.enLock} updateTreeValue={this.props.updateTreeValue} pattern={item} seqlist={this.props.seqlist} key={item.cyclist+','+index}  mty={this.props.mty}/>
                            if(item.seqlist)
                                return <SEQList extra={this.props.extra} action={this.props.action} t111={this.props.t111} enLock={this.props.enLock} updateTreeValue={this.props.updateTreeValue} pattern={item} seqlist={this.props.seqlist} key={item.seq+','+index}  mty={this.props.mty}/>
                            return null
                    })
               }
        </div>
        );
    }
    clonePO(po)
    {
        return DeepCopy(po)
    }
    getValue(arr)
    {
        for(let cell of this.cells)
        {
            cell.getValue(arr);
        }
    }
    pushItem(item,pos)
    {
        if(pos === undefined)
            this.fields.push(item)
        else
            this.fields.splice(pos,1,item);
    }
    pushAll(items)
    {

    }
}

export const TAG=0
export const CYC=1
export const SEQ=2
export const CYCLIST=3
export const SEQLIST=4
export const MESSAGE=5

export  class SWFMessage extends MessageArea
{
    constructor(props)
    {
        super(props)
        this.type = MESSAGE
    }

    
    render()
    {
        return this.output()
    }
}


export  class CYCList extends MessageArea
{
    constructor(props)
    {
        super(props)
        this.type = CYCLIST
        // this.fields.push(this.clonePO(this.props.pattern))
        // this.state = {fields:this.fields}
    }

    addItem=()=>{
        let subtree = this.props.pattern
        let obj = this.clonePO(subtree.pattern)
        subtree.cycs.push(obj) 
        //subtree.cycs = [...subtree.cycs]
        //通知刷新
        this.props.updateTreeValue()
    }
    removeItem=(index)=>{
        // this.fields.splice(index,1);
        // this.setState({fields:this.fields})
        let subtree = this.props.pattern
        subtree.cycs.splice(index,1)
        //subtree.cycs = [...subtree.cycs]

        //通知刷新
        this.props.updateTreeValue()

    }
    getValue(arr)
    {
        
        for(let cell of this.cells)
            cell.getValue(arr)
    }
    output()
    {
        let subtree = this.props.pattern
        return (
                <div>
                    <Row>
                        <Col span={1}>
                            <Button onClick={this.addItem} size="small" type="primary"  shape="circle" icon="retweet" title="Add Cycle"/>
                        </Col>
                        <Col>
                            <p><span style={{fontWeight:'bolder',fontSize:'1.5em'}}>-----></span></p> 
                        </Col>
                    </Row>
                    {
                        subtree.cycs.map((cyc,index)=>{
                         return (
                              <div style={{position:'relative'}} key={index}>
                                {index==0?null:
                                    <Button style={{position:'absolute',top:'0.35em',zIndex:99}} onClick={()=>this.removeItem(index)} size="small"   shape="circle" icon="cross" title="Remove Cycle"/>
                                }
                                <Cyc extra={this.props.extra} action={this.props.action} seqlist={this.props.seqlist} updateTreeValue={this.props.updateTreeValue} pattern={cyc}   mty={this.props.mty} />
                            </div>)
                        })
                    }
                    <Row>
                        <Col span={1}></Col>
                        <Col>
                        <p style={{paddingLeft:'2em',position:'relative',top:'-1.4em'}}><span style={{fontWeight:'bolder',fontSize:'1.5em'}}>-----|</span></p>
                        </Col>
                    </Row>
                </div>
        )
    } 
    render()
    {
        return this.output()
    }   
}

export  class Cyc extends MessageArea
{
    constructor(props)
    {
        super(props)
        this.type = CYC
    }
    
    output()
    {
        return (
                <div>
                   
                    {
                        super.output()
                    }
                    
                </div>
        )
    }
    render()
    {
        return this.output()
    }

}

export  class Seq extends MessageArea
{
    constructor()
    {
        super()
        this.type = SEQ
    }
    output()
    {
        return (
                <div>
                   
                    {
                        super.output()
                    }
                    
                </div>
        )
    }
    render()
    {
        return this.output()
    }
    
}

export  class SEQList extends MessageArea
{
    constructor()
    {
        super()
        this.type = SEQLIST
    }

    addItem=()=>{
        let subtree = this.props.pattern
        let obj = this.clonePO(subtree.pattern)
        subtree.cycs.push(obj) 
        
        this.props.updateTreeValue()
    }
    removeItem=(index)=>{
        
        let subtree = this.props.pattern
        subtree.cycs.splice(index,1)
        //通知刷新
        this.props.updateTreeValue()

    }
    getValue(arr)
    {
        
        for(let cell of this.cells)
            cell.getValue(arr)
    }
    output()
    {
        let subtree = this.props.pattern
        let seqlist = this.props.seqlist?[...this.props.seqlist,{seqlist:subtree.seqlist,status:subtree.status}]:[{seqlist:subtree.seqlist,status:subtree.status}]
        return (
                <div>
                    <Row>
                        <Col span={1}>
                            {
                            subtree.cyccnt==1?
                            <Button onClick={this.addItem} size="small" type="primary"  shape="circle" icon="retweet" title="Add Cycle"/>
                            :null
                            }
                        </Col>
                        <Col>
                            <p style={{fontWeight:'bolder',fontSize:'1.5em'}}>
                               <span>{subtree.desp}</span>
                            </p> 
                        </Col>
                    </Row>
                    {
                        subtree.seqs.map((seq,index)=>{
                         return (
                              <div style={{position:'relative'}} key={index}>
                                {index==0 || subtree.cyccnt==0?null:
                                    <Button style={{position:'absolute',top:'0.35em',zIndex:99}} onClick={()=>this.removeItem(index)} size="small"   shape="circle" icon="cross" title="Remove Cycle"/>
                                }
                                <Seq extra={this.props.extra} action={this.props.action} seqlist={seqlist} updateTreeValue={this.props.updateTreeValue} pattern={seq}   mty={this.props.mty} />
                            </div>)
                        })
                    }
                    <Row>
                        <Col span={1}></Col>
                        <Col>
                        <p style={{paddingLeft:'2em',position:'relative',top:'-1.4em'}}><span style={{fontWeight:'bolder',fontSize:'1.5em'}}>{subtree.cyccnt==0?`End Of ${subtree.desp}`:subtree.desp.replace(/^[->]/,'------|')}</span></p>
                        </Col>
                    </Row>
                </div>
        )
    } 
    render()
    {
        return this.output()
    }   
}


export  class Tag extends MessageArea
{
    constructor(props)
    {
        super(props)
        this.type = TAG
        this.isEnd=true
        // this.pattern = props.pattern
        // if(this.pattern.letter)
        // {
        //     this.name = this.pattern.letter[0]
        // }else
        //     this.name = this.pattern.tag
        // this.state = {name:this.name}
        this.state={tagValue:this.props.pattern.tagValue,isEmpty:this.isEmpty(this.props.pattern.tagValue)}
    }
    componentWillMount()
    {
        if(this.props.seqlist && !this.isEmpty(this.state.tagValue))
        {
            let {countMap={}} = this.props.extra
            for(let seqlbl of this.props.seqlist )
            {
                let key = seqlbl.seqlist
                if(!countMap[key])
                    countMap[key] = 1
                else
                    countMap[key]++
            }
            this.props.extra.countMap = countMap
        }
    }
    componentWillUnmount()
    {
        if(this.props.seqlist)
        {
            if(this.isEmpty(this.state.tagValue))
                return
            let {countMap} = this.props.extra
            if(!countMap)
                return
            for(let seqlbl of this.props.seqlist )
            {
                let key = seqlbl.seqlist
                if(countMap[key])
                    countMap[key]--
            }
        }
    }
    isEmpty(tagValue)
    {
          if(!tagValue)
            return true
          if(!tagValue.length || tagValue.length < 1)
                return true
           return isTagValueEmpty("T"+this.props.pattern.tag,tagValue)
    }

    onValue = val=>{
                this.props.pattern.tagValue = val

                let {status} = this.props.pattern
                let {countMap} = this.props.extra
                if(this.props.seqlist)
                {
                   if(!countMap)
                   {
                        countMap = {}
                        this.props.extra.countMap = countMap
                   }
                  // let mval = val && val.length? val[1] : ''
                   let val_old = this.state.tagValue
                  // let mval_old = val_old && val_old.length? val_old[1] : ''
                   if(!this.state.isEmpty && this.isEmpty(val))
                   {
                       for(let seqlbl of this.props.seqlist ) //计数减1
                       {
                           let key = seqlbl.seqlist
                           if(countMap[key])
                               countMap[key]--
                       }
                   }
                   else if(this.state.isEmpty && !this.isEmpty(val))
                   {
                       for(let seqlbl of this.props.seqlist ) //计算加1
                       {
                           let key = seqlbl.seqlist
                           if(!countMap[key])
                               countMap[key]=1
                           else
                               countMap[key]++
                       }
                   }
                  
                }

                TagV("T"+this.props.pattern.tag,this.props.pattern.status,val,this.props.pattern.tno,this.props.mty,this.props.t111,this.props.seqlist,this.props.extra.countMap)
                this.setState({tagValue:this.props.pattern.tagValue,isEmpty:this.isEmpty(this.props.pattern.tagValue)})
                //this.props.updateTreeValue()
    }
    output()
    {
        let comp = TagSet("T"+this.props.pattern.tag,{action:this.props.action,enLock:this.props.enLock,mty:this.props.mty,status:this.props.pattern.status,value:this.props.pattern.tagValue,desp:this.props.pattern.label,t111:this.props.t111,seqlist:this.props.seqlist},
            this.onValue
            )
        if(!comp)
            return null;
        
        return comp
    }
    render()
    {
        let pattern = this.props.pattern
        return (
            <Row style={{backgroundColor:this.props.pattern.tagValue && this.props.pattern.tagValue[1]?'#DDD':null}}>
                <Col span={1} style={{marginTop:'0.6em'}}><span style={{fontWeight:'bolder'}}></span></Col>
                {/*<Col span={2} style={{marginTop:'0.6em'}}><span style={{fontWeight:'bolder'}}>{pattern.status}</span></Col>*/}
                <Col span={3} style={{marginTop:'0.6em',position:'relative'}}>
                       {
                       pattern.status=='M'?    
                       <h3 style={{color:'#fc561f',position:'absolute',left :'-0.5em'}}>*</h3>
                       :null
                       }
                       {
                        !(pattern.letter && pattern.letter.length)?
                        <span style={{fontWeight:'bolder'}}>{pattern.tag}</span>
                        :
                        <FormItem>
                            <Select size="large" value={pattern.tag} style={{ width: 80 }} onChange={tag=>{pattern.tag =tag ;pattern.tagValue=[{},'',{}];this.props.updateTreeValue()}}>
                                {
                                    pattern.letter.map(item=>{
                                        return   <Option key={item} value={item}>{item}</Option>

                                    })
                                }
                            </Select>
                        </FormItem>
                       }
                </Col>
                <Col span={4} style={{marginTop:'0.6em'}}><span style={{fontWeight:'bolder'}}>{pattern.label}</span></Col>
                <Col span={15}>
                    {this.output()}
                </Col>
                <Col span={1} style={{textAlign:'center',marginTop:'0.6em'}}><span  style={{fontWeight:'bolder'}}>{pattern.tno}</span></Col>
            </Row>
        )
    }
    getValue(arr)
    {
        let obj = {};
        obj.name = this.name;
        obj.value = this.tagValue;
        arr.push(obj)
    }
}