import React,{Component} from 'react'
import {bindActionCreators} from 'redux';
import {connect} from 'react-redux';
import { updateTreeValue,updateRcvBic,updateSndBic,initSwiftMessageTree ,updateSwiftMessage} 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,isTagValueEmpty} from './TagValidater'

import YBIC from './Tags/YBIC'

import TempSaver from './TemplateSave'

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,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}])
            }
        }
    }

    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} = this.props
        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( rcv_bic_err_msg || crs.hasError)
        {
            //更新整个树
            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})
            this.props.actions.updateTreeValue()
            //滚动至第一个错误位置
            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)
            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 = ''
         let header3 = ''
         if(mty=='202COV')
         {
             mty='202'
             //s119=':119:COV\r\n'  锦州
             s119 = '{119:COV}'
             header3 = `{3:${s119}}`
         }   
        //锦州  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${s119}${gpistr}:EOH:\r\n${message}\r\n-\r\n`
        //南商
        message = `{1:F01${window.BANK_LOGIC_ADDRESS}0000000000}{2:I${mty}${getLogicAdress(this.props.rcv_bic_info.rcv_bic)}N}${header3}{4:\r\n${message}\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(this.props.extra.countMap)
        //     this.props.extra.s_countMap = {...this.props.extra.countMap}

        if(flag)
            this.props.history.push("preview/0")
        else 
            this.props.history.push("preview/1")
    }
    joinMessage(tags,arr,seqlist)
    {
        for(let item of tags)
        {
            if(item.tag)
            {
                if(item.tag.indexOf('15')>-1)
                {
                    //15系列字段
                    if(seqlist && this.props.extra.countMap && this.props.extra.countMap[seqlist])
                    {
                        arr.push(`:${item.tag}:`)
                    }
                }
                
                if(!item.tagValue)
                    continue
                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(item.cyclist)
            {
                for(let cyc of item.cycs)
                    this.joinMessage(cyc,arr)
            }
            else if(item.seqlist)
            {
                for(let seq of item.seqs)
                    this.joinMessage(seq,arr,item.seqlist)
            }
        }
    }
    reload =(flag)=>{

            
            let tempinr = this.props.params.key
            ServiceAPI.getTemplate(tempinr).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.mty = data.typ
                this.props.extra.msgtyp="mt"+this.mty
                if(data.txt)
                    data = data.txt
                
                
                data = JSON.parse(data)
                this.props.actions.updateRcvBic({rcv_bic:data.rcv_bic_info.rcv_bic})
                let tree = data.swift_message_tree
                this.props.actions.initSwiftMessageTree(tree);
            }).catch(err=>{
                console.log(err)
            })


            // 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
            //     console.log(data.swift_message)
            //     this.props.extra.smhinr=smhinr
            //     this.props.extra.msgtyp="mt"+data.mty
            //     this.props.extra.tdheaders=data.tdheaders
            //     this.props.extra.headers=data.headers
            //     let tree = JSON.parse(data.swift_message)
            //     this.props.actions.initSwiftMessageTree({Tags:tree,Title:data.title});
            // }).catch(err=>{
            //     console.log(err)
            // })
    }

    saveTemp=()=>{
        //存储报文模板
        const {swift_message,rcv_bic_info,snd_bic_info,swift_message_tree,extra} = this.props
        let json = {
            swift_message,rcv_bic_info,snd_bic_info,swift_message_tree,extra
        }
        let jsonStr = JSON.stringify(json)
        return jsonStr
    }
    componentWillMount()
    {
        
        let action = this.props.params.action
        let mctid  = this.props.params.mctid
        this.props.extra.mctid = mctid

        // if(!this.props.swift_message_tree)
        // {
        //     //取出暂存countMap
        //     if(this.props.extra.s_countMap)
        //         this.props.extra.countMap = {...this.props.extra.s_countMap}
        // }

        if(action == 'edit')
        {
            
            
            let mty = this.props.params.key;
            mty = mty.toLowerCase()
            if(mty.substring(0,2)!='mt')
                mty = 'mt'+mty
            if(!this.props.swift_message_tree)
            {
                let mt_config = MTFactory(mty);
                mt_config = JSON.parse(JSON.stringify(mt_config))
                this.mty=mty
                this.props.extra.msgtyp=mty
                this.props.actions.initSwiftMessageTree(mt_config);
            }
            //取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})
                
            }
            this.isdirect = false
        }
        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} = 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
        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={true} snd_bic={window.BANK_BIC} err_msg={null} 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={false} 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
                                    }
                                    
                                       <TempSaver getTemplateJSON={this.saveTemp} mty={mty} mctid={this.props.extra.mctid} style={{marginRight:'1em',width:'8em'}}/>
                                        <br/>
                                        <br/>
                                   
                                    {
                                    !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>
                    <h2 style={{textAlign:'center'}}>
                        {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 action={this.props.params.action} extra={this.props.extra} enLock={false} 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} = state.swift;
  return {
    swift_message,rcv_bic_info,snd_bic_info,swift_message_tree,extra
  };
};

function mapDispatchToProps(dispatch) {
  return {
    actions: bindActionCreators({ updateTreeValue,updateRcvBic,updateSndBic,initSwiftMessageTree,updateSwiftMessage }, 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> )
    }
}

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} 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} 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} enLock={this.props.enLock} updateTreeValue={this.props.updateTreeValue} pattern={item} seqlist={this.props.seqlist}  key={item.seqlist+','+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.seqs.push(obj) 
        
        this.props.updateTreeValue()
    }
    removeItem=(index)=>{
        
        let subtree = this.props.pattern
        subtree.seqs.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)
    }
    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,seqlist:this.props.seqlist},
            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,status,val,this.props.pattern.tno,this.props.mty,this.props.seqlist,this.props.extra.countMap)
                this.setState({tagValue:this.props.pattern.tagValue,isEmpty:this.isEmpty(this.props.pattern.tagValue)})
                //this.props.updateTreeValue()
                }
            )
        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)
    }
}