import React,{Component} from 'react';
// import PropTypes from 'prop-types';

import { Switch, Form, Input, Row, Col, Button, message,DatePicker,Select } from 'antd';

import moment from 'moment';
import { $http } from '../../containers/config/https';
import { Util } from '../../tools';

// const FormItem = Form.Item;
// const RadioGroup = Radio.Group;
const Option = Select.Option;

const EditFieldLink = Form.create()(   
class  extends Component {
    constructor(props) {
        super(props);
        this.state = {
            editField:[],
            fetching:false,
            data:[],
            value:"",
            selectData:{},
            detailInfo:{},
            rowId:"",
            ColNum:6,
            ClassName:"",
            RefId:"",
            
        };
    }
    normalizeAll=(value, prevValue)=>{
        return value
    }
    GetCom=(fieldItem)=>{

        const { getFieldDecorator } = this.props.form;
        let detailInfo = this.state.detailInfo ? this.state.detailInfo : {};
        var code=detailInfo[fieldItem.Code]
        if(typeof detailInfo[fieldItem.Code]==="undefined"){
                code=""
        }
        var type=fieldItem.Type
        var ReadOnlyFlag=fieldItem.ReadOnlyFlag
        var disabled=false
        if(ReadOnlyFlag==="Y") disabled=true
        if(type==="Text"){
            return (
                {...getFieldDecorator(fieldItem.Code, {
                initialValue:code,
                rules: fieldItem.rules,
            })(<Input disabled={disabled} style={{ width: '100%' }} />)
            }
            )
        }else if(type==="Radio"){
            return (
            
            {...getFieldDecorator(fieldItem.Code, {
                initialValue: code==="Y"?true:false,
                valuePropName: 'checked',
                rules: fieldItem.rules,
                normalize:(value, prevValue)=>{
                    return  value
                }
            })(<Switch disabled={disabled} checkedChildren="是" unCheckedChildren="否"  />)
            }
            )
        }else if(type==="Date"){
            var date=""
            if(fieldItem.Code==="StartDate"){
                date=code ? moment(code, 'YYYY-MM-DD') : moment(new Date(), 'YYYY-MM-DD')
            }else{
                date=code ? moment(code, 'YYYY-MM-DD') : null
            }
            
            return (
                {...getFieldDecorator(fieldItem.Code, {
                    initialValue:date,
                    rules: fieldItem.rules,
                })(<DatePicker disabled={disabled} format="YYYY-MM-DD"/>)
                }
                )
        }else if(type==="DR"){
            return this.GetSelect(fieldItem,detailInfo);
        }else if(type==="Select"){
            return this.GetSelectOther(fieldItem,detailInfo);
        }else if(type==="Time"){
            var rules=[]
            rules.push(fieldItem.rules)
            rules.push({
                validator: this.validateTime
          })
            return (
                {...getFieldDecorator(fieldItem.Code, {
                    initialValue:code,
                    rules: rules,
                    })(<Input disabled={disabled} />)
            }
            )
        }else{
            return (
                {...getFieldDecorator(fieldItem.Code, {
                    initialValue:code,
                    rules: fieldItem.rules,
                    })(<Input disabled={disabled} />)
                }
            )
        }
    }
    validateTime=(rule,time,callback)=>{
        if(time==="") return 
        for(var i=0;i<time.length;i++){
            var ascCode=time[i].charCodeAt()
            if(((ascCode<48)||(ascCode>57))&&(ascCode!==58)){
                callback("时间格式不正确")
            }
        }
        var timeArr=time.split(":")
        if(timeArr.length===3){
            if((timeArr[0]>="24")||(timeArr[1]>="60")||(timeArr[2]>="60")){
                callback("时间格式不正确")
            }
        }else if(timeArr.length===2){
            if((timeArr[0]>="24")||(timeArr[1]>="60")){
                callback("时间格式不正确")
            }
        }else{
            callback("时间格式不正确")
        }
        callback()
    }
    getEditField=(className)=>{
        let data = {
            params: [{ClassName:className}]
        }
        $http.post("urlS",this, {
            code: "4004",
            data: data,
            success: function (res) { 
                if (+res.errorCode === 0) {
                   var fieldArr=[]
                   fieldArr=res.result.Data
                   this.setState({
                       editField:fieldArr,
                       ColNum:res.result.ColNum
                    })
                } else {
                    message.error('失败：' + res.errorMessage);
                }
            }
        })    
    }
    handleChange=()=>{

    }
    handleFocus=()=>{

    }
    handleBlur=()=>{

    }
    GetSelect=(fieldItem,detailInfo)=>{
        const { selectData } = this.state;
        const { getFieldDecorator ,getFieldValue,setFieldsValue} = this.props.form;
        //let detailInfo = this.state.detailInfo
        var code=detailInfo[fieldItem.Code]
        if(typeof detailInfo[fieldItem.Code]==="undefined"){
             code=""
        }
        var ReadOnlyFlag=fieldItem.ReadOnlyFlag
        var disabled=false
        if(ReadOnlyFlag==="Y") disabled=true
        var PrevLevelField=fieldItem.PrevLevelField
        var prevLevelFieldJson=[]
        if(PrevLevelField!==""){
            var prevLevelFieldArr=PrevLevelField.split("^")
            for(var i=0;i<prevLevelFieldArr.length;i++){
                var jsonObj={}
                jsonObj.field=prevLevelFieldArr[i]
                var fieldVal=getFieldValue(prevLevelFieldArr[i])
                jsonObj.fieldVal=""
                if(typeof fieldVal!=="undefined") jsonObj.fieldVal=fieldVal
                prevLevelFieldJson.push(jsonObj)
            }
        }
        return (
            {...getFieldDecorator(fieldItem.Code, {
                initialValue:code,
                rules: fieldItem.rules,
                normalize:(value, prevValue)=>{

                    if(value===0){
                        value=""
                    }
                    return value
                }
            })(
            
            <Select
            allowClear={true}
            placeholder=""
            showSearch
            optionFilterProp="children"
            onChange={(value, option)=>{
                var editFieldArr=this.state.editField
                var fieldName=fieldItem.Code
                var count=0
                var fieldJson={}
                var fieldObj;
                for(var i=0;i<editFieldArr.length;i++){
                    fieldObj=editFieldArr[i]
                    fieldJson[fieldObj.Code]=fieldObj
                }
                var fieldNameArr=[]
                fieldNameArr[0]=fieldName
                var index=0
                while((index>=0)&&(fieldNameArr[index]!=="")){
                    fieldObj=fieldJson[fieldNameArr[index]]
                    var NextField=fieldObj.NextLevelField
                    if(NextField!==""){
                        var NextFieldArr=NextField.split("^")
                        for(var i=0;i<NextFieldArr.length;i++){
                            var valObj={}
                            valObj[NextFieldArr[i]]=""
                            setFieldsValue(valObj)
                            fieldNameArr[fieldNameArr.length]=NextFieldArr[i]
                        }
                        index=index+1
                    }else{
                        index=-1
                    }
                    count=count+1
                    if(count>10){
                        break;
                    }
                }
            }}
            onFocus={this.handleFocus}
            onBlur={this.handleBlur}
            disabled={disabled}
            filterOption={(input, option) => {
                var desc=option.props.children
                var alias=option.props.alias
                var flag=(desc.toLowerCase().indexOf(input.toLowerCase()) >= 0)||(alias.toLowerCase().indexOf(input.toLowerCase()) >= 0)
                var prevvalue=option.props.prevvalue
                var prevFieldValue=""
                if(typeof prevvalue!=="undefined"){
                    prevFieldValue=getFieldValue(PrevLevelField)
                    flag=flag &&(prevFieldValue===prevvalue)
                }
                //
                return flag
            }}
            style={{ width: '100%' }}
            >
            { 
                selectData[fieldItem.Code]&&selectData[fieldItem.Code].length&&selectData[fieldItem.Code].map((d) => { 
                    if(fieldItem.Code==="LocDr"){
                        //debugger
                    }
                    if(PrevLevelField===""){
                        return (
                            <Option key={d.ID} alias={d.Alias}  >{d.Desc}</Option>
                        )
                    }else{
                        var flag=1
                        for(var i=0;i<prevLevelFieldJson.length;i++){
                            var prevvalue=d[prevLevelFieldJson[i].field]?d[prevLevelFieldJson[i].field]:""
                            var prevFieldValue=prevLevelFieldJson[i].fieldVal
                            if((prevFieldValue==="")||(prevvalue===prevFieldValue)){
                                
                            }else{
                                flag=0
                               
                            }
                        }
                        
                        if(flag===1){
                            return (
                                <Option key={d.ID} alias={d.Alias} prevvalue={prevvalue} >{d.Desc}</Option>
                            )
                        }else{
                            return null;
                        }
                     }
                    return null;
                   
                }) 
            }
            </Select>
            )
        }
        );
    }
    GetSelectOther=(fieldItem,detailInfo)=>{
        const { selectData} = this.state;
        const { getFieldDecorator } = this.props.form;
        //let detailInfo = this.state.detailInfo
        var code=detailInfo[fieldItem.Code]
        if(typeof detailInfo[fieldItem.Code]==="undefined"){
             code=""
        }
        var ReadOnlyFlag=fieldItem.ReadOnlyFlag
        var disabled=false
        if(ReadOnlyFlag==="Y") disabled=true
        return (
            {...getFieldDecorator(fieldItem.Code, {
                initialValue:code,
                rules: fieldItem.rules,
                normalize:(value, prevValue)=>{
                    if(+value===0){
                        value=""
                    }
                    return value
                }
            })(
            
            <Select
            placeholder=""
            optionFilterProp="children"
            onChange={this.handleChange}
            onFocus={this.handleFocus}
            onBlur={this.handleBlur}
            disabled={disabled}
            filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
            style={{ width: '100%' }}
            >
            { 
                  selectData[fieldItem.Code]&&selectData[fieldItem.Code].length&&selectData[fieldItem.Code].map(d => <Option key={d.ID}>{d.Desc}</Option>) 
            }
            </Select>
            )
        }
        );
    }
    getSelectData=(className)=>{
        let data = {
            params: [{ClassName:className}]
        }
        $http.post("urlS",this, {
            code: "4007",
            data: data,
            success: function (res) { 
                if (+res.errorCode === 0) {
                   var selectData=res.result
                   this.setState({selectData:selectData})
                } else {
                    message.error('失败：' + res.errorMessage);
                }
            },
            error:function (error) {
                message.error('失败：' + error);
            }
        })    
    }
    componentWillMount() {
        this.setState({
            rowId:this.props.rowId,
            ClassName:this.props.ClassName,
            RefId:this.props.RefId,
            detailInfo:{}
        },()=>{
            this.getEditField(this.props.ClassName)
            this.getSelectData(this.props.ClassName)
            if(this.props.rowId!==""){
                this.GetItemData(this.props.ClassName,this.props.rowId)
            }
        })
    }
    handelSave=()=>{
		const userData=sessionStorage.userData?JSON.parse(sessionStorage.userData):{}
        const { form: { validateFields } } = this.props;
		validateFields((errors, values) => {
            //转换values  里的Radio类型的字段的值,true转换成Y,false转换成N
            let editField=this.state.editField
            for(var i=0;i<editField.length;i++){
                var itemField=editField[i]
                if(itemField.Type==="Radio"){
                    if(values[itemField.Code]===true){
                        values[itemField.Code]="Y"
                    }else{
                        values[itemField.Code]="N"
                    }
                }
            }
		    if (errors === null) {
                let data = {
                    params: []
            }
            var dataObj={}
            dataObj.ClassName=this.props.ClassName
            dataObj.UserDr=userData.userID
            let ItemObj = JSON.parse(JSON.stringify(values));
            var ID=this.state.detailInfo.ID
            if(typeof ID ==="undefined"){
                ItemObj.ID=""
            }else{
                ItemObj.ID=ID
            }
            ItemObj.RefId=this.state.RefId
            dataObj.Item=ItemObj
            // 处理需要传递的obj
            data.params.push(Util.disposeData(dataObj));
            $http.post("urlADS",this, {
                    code: 4015,
                    data: data,
                    success: function (res) { 
                            if (+res.errorCode === 0 ) {
                                // 提示
                                message.success('保存成功');
                                // 新增或编辑成功重置form表单
                                
                                this.props.handelThis.getData(this.state.ClassName,this.state.RefId)
                                this.props.handelThis.setState({
                                    visible: false,
                                  });
                                this.resetFields();
                                
                            } else {
                                message.error("保存失败:" + res.errorMessage);
                            }
                    }
            })
            }else {
                 return;
            }
        })
    }
   // 重置表单
    resetFields=()=> {
        this.setState({
            rowId: "",
            detailInfo:{},
        });
    }
    //props 改变时调用此方法
    componentWillReceiveProps(nextProps){
        
        if(this.props.handelThis.state.visible===false) return 
        var rowId="",ClassName="",RefId=""
        if(nextProps.rowId !== undefined){
            rowId=nextProps.rowId
        }else{
            rowId=""
        }

        if(nextProps.RefId !== undefined){
            RefId=nextProps.RefId
        }else{
            RefId=""
        }
        if(nextProps.ClassName !== undefined){
            ClassName=nextProps.ClassName
        }else{
            ClassName=""
        }
        if((this.state.ClassName===nextProps.ClassName)&&(this.state.rowId===nextProps.rowId)){
            //return 
        }
        this.setState({
            RefId:RefId,
            className:ClassName,
            rowId: rowId,
            detailInfo:{}
        })
        this.getEditField(ClassName)
        this.getSelectData(ClassName)
        if(rowId!==""){
            this.GetItemData(ClassName,rowId)
        }
    }
    GetItemData=(ClassName,RowId)=>{
        let data = {
            params: [{ClassName:ClassName,ID:RowId}]
        }
        $http.post("urlS",this, {
            code: "4017",
            data: data,
            success: function (res) { 
                if (+res.errorCode === 0) {
                    var itemData=res.result
                    this.setState({
                        detailInfo:itemData,
                    });
                } else {
                    message.error('失败：' + res.errorMessage);
                }
            },
            error:function (error) {
                message.error('失败：' + error);
            }
        }) 
    }
    render() {
        /*const formItemLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 8 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 16 },
            },
        };
        const tailFormItemLayout = {
            wrapperCol: {
                xs: {
                span: 24,
                offset: 0,
                },
                sm: {
                span: 24,
                offset: 1,
                },
            },
        };*/
        let ColWidth=Math.ceil(24/this.state.ColNum)
        return (
            <div>
                <Form onSubmit={this.handleSubmit} layout="vertical" >
                    <Row gutter={24} >
                            {
                                this.state.editField.length>0?this.state.editField.map((value,key)=>{
                                        return (
                                            <Col span={ColWidth} key={key} >
                                             <Form.Item key={key} label={value.Desc} style={{height: '65px'}} >
                                               {this.GetCom(value)}
                                            </Form.Item>
                                            </Col>
                                        )
                                }):""
                            }
                            </Row>
                            <Row>
                            <Col span={8} ></Col>
                            <Col span={8} >
                                <Button onClick={this.handelSave} type="primary">保存</Button>
                            </Col> 
                            <Col span={8} >
                                <Button type="primary" onClick={this.resetFields}>重置</Button>
                            </Col>
                            </Row>
                        </Form>
                        </div>
        );
    }
})

export default EditFieldLink;