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

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

import { $http } from '../../containers/config/https';
import { Util } from '../../tools';
import CBDataModel from './CBDataModel'
import * as XLSX from 'xlsx';
// const FormItem = Form.Item;
// const RadioGroup = Radio.Group;
const Option = Select.Option;

const TableDataForm = Form.create()(
class  extends Component {
    constructor(props) {
        super(props);
        this.state = {
            selectRowid:"",
            selectRowObj:{},
            basicClassData:[],
            proModuleData:[],
            frequeUseData:[],
            className:"",
            classTitle:"",
            visible:false

        };
        this.clientWidth=1400
    }
    componentWillMount() {
        this.GetFormData()
        this.GetFrequeUseClass()
        //this.GetProductModule()
    }
    GetFormData=()=>{
        let data = {
            params: [{}]
        }
        $http.post("urlS",this, {
            code: "4025",
            data: data,
            success: function (res) { 
                if (+res.errorCode === 0) {
                    this.setState({
                        basicClassData:res.classData,
                        proModuleData:res.proModuleData
                    })
                    
                } else {
                    message.error('失败：' + res.errorMessage);
                }
            }
        }) 
    }
    handleSubmit=()=>{
        
    }
    //props 改变时调用此方法
    componentWillReceiveProps(nextProps){
        var selectRowid=""
        if(nextProps.selectRowid !== undefined){
            selectRowid=nextProps.selectRowid
        }else{
            selectRowid=""
           
        }
        if(selectRowid===""){
            this.setState({
                selectRowObj:{}
            })
            return 
        }
        
        let data = {
            params: [{ID:selectRowid}]
        }
        $http.post("urlS",this, {
            code: "4012",
            data: data,
            success: function (res) { 
                if (+res.errorCode === 0) {
                   this.setState({
                        selectRowObj:res.result
                    })
                } else {
                    message.error('失败：' + res.errorMessage);
                }
            }
        })    
    }
    // 重置表单
    resetFields=()=> {
        this.props.form.resetFields(); //清空所有
        this.props.handelThis.resetEditFieldData()
        this.setState({
            selectRowid:"",
            selectRowObj:{}
        })
    }
    handelSave=()=>{
		const userData=sessionStorage.userData?JSON.parse(sessionStorage.userData):{}
        const { form: { validateFields } } = this.props;
		validateFields((errors, values) => {
		    if (errors === null) {
                let data = {
                    params: []
            }
            let ItemObj = JSON.parse(JSON.stringify(values));
            var ID=this.state.selectRowObj.ID
            if(typeof ID ==="undefined"){
                
            }else{
                ItemObj.ID=ID
            }
            if(ItemObj.FrequeUse){
                ItemObj.FrequeUse="Y"
            }else{
                ItemObj.FrequeUse="N"
            }
            ItemObj.CreateUserDr=userData.userID
            // 处理需要传递的obj
            data.params.push(Util.disposeData(ItemObj));
            $http.post("urlADS",this, {
                    code: 4011,
                    data: data,
                    success: function (res) { 
                        if (+res.errorCode === 0 ) {
                            // 提示
                            message.success('保存成功');
                            // 新增或编辑成功重置form表单
                            this.resetFields();
                            
                            this.props.handelThis.setState({
                                page: 1
                            },()=>{
                                this.props.handelThis.getClassData(ItemObj.Code,"",true)
                            })
                        }else{
                            message.error("保存失败:" + res.errorMessage);
                        }
                    }
            })
            }else {
                return;
            }
        })
    }
    handleData=(className,classTitle)=>{
        
        let data = {
            params: [
                {
                    ClassName:className
                }
            ]
        }
        $http.post("urlADS",this, {
            code: "4019",
            data: data,
            success: function (res) { 
                if (+res.errorCode === 0) {
                    this.setState({
                        className:className,
                         classTitle:classTitle,
                    })
                    this.refs.CBDataModel.setState({
                        visible:true
                     })
                } else {
                    message.error(res.errorMessage);
                }
            }
        })    
    }
    GetFrequeUseClass=()=>{
        let data = {
            params: [{}]
        }
        $http.post("urlS",this, {
            code: "01010004",
            data: data,
            success: function (res) { 
                if (+res.errorCode === 0) {
                    this.setState({
                        frequeUseData:res.result
                    })
                    
                } else {
                    message.error('失败：' + res.errorMessage);
                }
            }
        }) 
    }
    ExportExcelModel=()=>{
        const hospDr=""
        const groupDr=""
        var className=this.state.selectRowObj.Code
        if(className==="") return 
        let data = {
            params: [{
                ClassName:className,
                groupId:groupDr,
                hospitalId:hospDr
            }]
        }
        $http.post("urlS",this, {
            code: "4004",
            data: data,
            success: function (res) { 
                if (+res.errorCode === 0) {
                    var fieldData=res.result.Data
                    var fieldJson={}
                    for(var j=0;j<fieldData.length;j++){
                        if(fieldData[j].ReadOnlyFlag==="Y") continue
                        fieldJson[fieldData[j].Code]=fieldData[j].Desc
                    }
                    var fieldarr=[]
                    fieldarr[0]=fieldJson
                    const wopts = { bookType: 'xlsx', bookSST: false, type: 'binary' };//这里的数据是用来定义导出的格式类型
                    const wb = { SheetNames: ['Sheet1'], Sheets: {}, Props: {} };
                    
                    wb.Sheets['Sheet1'] = XLSX.utils.json_to_sheet(fieldarr);//通过json_to_sheet转成单页(Sheet)数据
                    var obj=new Blob([this.s2ab(XLSX.write(wb, wopts))], { type: "application/octet-stream" })
                    this.saveAs(obj, className+"模板" + '.' + (wopts.bookType=="biff2"?"xls":wopts.bookType));
                   console.log(res)
                } else {
                    message.error('失败：' + res.errorMessage);
                }
            }
        })  
    }
    saveAs=(obj, fileName)=>{
        var tmpa = document.createElement("a");
        tmpa.download = fileName || "下载";
        tmpa.href = URL.createObjectURL(obj); //绑定a标签
        tmpa.click(); //模拟点击实现下载
        setTimeout(function () { //延时释放
            URL.revokeObjectURL(obj); //用URL.revokeObjectURL()来释放这个object URL
        }, 100);
    }
    s2ab(s) {
        if (typeof ArrayBuffer !== 'undefined') {
            var buf = new ArrayBuffer(s.length);
            var view = new Uint8Array(buf);
            for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
            return buf;
        } else {
            var buf = new Array(s.length);
            for (var i = 0; i != s.length; ++i) buf[i] = s.charCodeAt(i) & 0xFF;
            return buf;
        }
    }
    render() {
        
        const { getFieldDecorator } = this.props.form;
        return (
            <div>
                <Form onSubmit={this.handleSubmit} layout="vertical" >
                    <Row gutter={24} >
                        <Col span={8} >
                            <Form.Item  label="表名" style={{height: '60px'}} >
                                {getFieldDecorator("Code", {
                                    initialValue:this.state.selectRowObj.Code?this.state.selectRowObj.Code:"",
                                    rules: [{required:true,message:"表名不能为空"}],
                                    })(
                                        <Select
                                            showSearch
                                            style={{ width: '80%' }}
                                            placeholder="Select a person"
                                            optionFilterProp="children"
                                            disabled={this.state.selectRowObj.Code?true:false}
                                            filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                                        >
                                        { 
                                            this.state.basicClassData.map(d => <Option key={d.ID}>{d.Desc}</Option>) 
                                        }   
                                        </Select>    
                                    )
                                }             
                            </Form.Item>
                        </Col>
                        <Col span={8} >
                            <Form.Item  label="描述" style={{height: '60px'}} >
                                {getFieldDecorator("Descripts", {
                                    initialValue:this.state.selectRowObj.Descripts?this.state.selectRowObj.Descripts:"",
                                    rules: [{required:true,message:"描述不能为空"}],
                                    })(<Input  style={{ width: '80%' }} />)
                                }
                                                
                            </Form.Item>
                        </Col>
                        <Col span={8} >
                            <Form.Item  label="产品模块" style={{height: '60px'}} >
                                {getFieldDecorator("ProductModuleDr", {
                                    initialValue:this.state.selectRowObj.ProductModuleDr?this.state.selectRowObj.ProductModuleDr:"",
                                    rules: [{required:true,message:"产品模块不能为空"}],
                                    })(
                                        <Select
                                            showSearch
                                            style={{ width: '80%' }}
                                            placeholder="请选择产品模块"
                                            optionFilterProp="children"
                                            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)
                                               
                                                return flag
                                            }}
                                        >
                                        { 
                                            this.state.proModuleData.map((d) => { 
                                                return (
                                                    <Option key={d.id} alias={d.descriptsSPCode}>{d.descripts}</Option>
                                                )
                                                
                                            }) 
                                        }   
                                        </Select>    
                                    )
                                }             
                            </Form.Item>
                        </Col>
                        <Col span={8} >
                            <Form.Item  label="备注" style={{height: '60px'}} >
                                {getFieldDecorator("Notes", {
                                    initialValue:this.state.selectRowObj.Notes?this.state.selectRowObj.Notes:"",
                                    rules: "",
                                    })(<Input  style={{ width: '80%' }} />)
                                }
                                                
                            </Form.Item>
                        </Col>
                        <Col span={8} >
                            <Form.Item  label="安全等级" style={{height: '60px'}} >
                                {getFieldDecorator("SafeClassificat", {
                                    initialValue:this.state.selectRowObj.SafeClassificat?this.state.selectRowObj.SafeClassificat:"",
                                    rules: "",
                                    })(<Input  style={{ width: '80%' }} />)
                                }
                                                
                            </Form.Item>
                        </Col>
                        <Col span={8} >
                            <Form.Item  label="列数" style={{height: '60px'}} >
                                {getFieldDecorator("ColNum", {
                                    initialValue:this.state.selectRowObj.ColNum?this.state.selectRowObj.ColNum:4,
                                    rules: "",
                                    })(<Input  style={{ width: '80%' }} />)
                                }
                                                
                            </Form.Item>
                        </Col>
                        <Col span={8} >
                            <Form.Item  label="简写" style={{height: '60px'}} >
                                {getFieldDecorator("ShortDesc", {
                                    initialValue:this.state.selectRowObj.ShortDesc,
                                    rules: "",
                                    })(<Input  style={{ width: '80%' }} />)
                                }
                                                
                            </Form.Item>
                        </Col>   
                        <Col span={8} >
                            <Form.Item  label="常用标志" style={{height: '60px'}} >
                                {getFieldDecorator("FrequeUse", {
                                    initialValue: this.state.selectRowObj.FrequeUse==="Y"?true:false,
                                    valuePropName: 'checked',
                                    normalize:(value, prevValue)=>{
                                    return  value
                                }
                                     })(<Switch checkedChildren="是" unCheckedChildren="否"  />)
                                 }         
                                </Form.Item>
                        </Col> 
                        
                    </Row>
                    <Row>
                        <Col span={8} >
                            <Button onClick={this.handelSave} type="primary">保存</Button>
                        </Col> 
                        <Col span={8} >
                            <Button type="primary" onClick={this.resetFields}>重置</Button>
                        </Col>
                        <Col span={6} >
                            <Button type="primary" onClick={this.ExportExcelModel}>Excel模板导出</Button>
                        </Col>
                    </Row>
                </Form>
                <br />
                <br />
                <Card title={"常用表"}>
                <br />
                <Row gutter={24} >
                    {
                        this.state.frequeUseData.map((val,key)=>{
                            return (
                                <Col span={4} key={key}><Button key={key} type="primary" size="large" onClick={this.handleData.bind(this,val.className,val.desc)}>{val.desc}</Button></Col>
                            )
                        })
                    }         
                </Row>             
                </Card>
                <CBDataModel clientWidth={this.clientWidth} ClassName={this.state.className} ClassTitle={this.state.classTitle} ref="CBDataModel" />
           
            </div>    
        );
    }
}
)

export default TableDataForm;