import React, { Component } from 'react';
import {
    Table, Button, Col, Row, Input, Select, message, Pagination, Card, Tabs
} from 'antd';
import { $http } from '../../containers/config/https';
import Editfield from './EditField'
import CBDataLink from './CBDataLink'
import CBDataImport from './CBDataImport'
import store from '../../store';
import './style/index.less';
import CommonPagination from 'components/pagination/index';
const Option = Select.Option
const TabPane = Tabs.TabPane;
class CBData extends Component {
    constructor(props) {
        super(props);
        this.state = {
            data: [],
            editField: [],
            columns: [],
            findField: {
                TotalCount: 0,
                Data: [],
            },
            rowId: "",
            detailInfo: {},
            ClassName: "",
            ClassTitle: "",
            total: 0,
            page: 1,
            pageSize: 20,
            TableWidth: 0,
            LinkTableData: [],
            remoteSearchArr: {}
        };
        this.FindFieldVal = {
            DataAvail: ""
        }
    }

    componentWillReceiveProps(nextProps) {
        let ClassName = ""
        if (nextProps.ClassName !== undefined) {
            ClassName = nextProps.ClassName
        } else {
            ClassName = ""
        }

        if (ClassName === this.state.ClassName) {

            if (ClassName !== "") {
                this.getColumn(ClassName)
                this.getFindField(ClassName)
                this.getData(ClassName)
                this.GetLinkTableData(ClassName)
            }
            return
        }
        let ClassTitle = ""
        this.setState({
            ClassName: ClassName,
            ClassTitle: ClassTitle,
            rowId: "",
            data: [],
            editField: [],
            columns: [],
            findField: {
                TotalCount: 0,
                Data: [],
            },
            detailInfo: {},

            total: 0,
            page: 1,
            pageSize: 10,
            TableWidth: 0
        })
        this.FindFieldVal = { DataAvail: "" }
        if (ClassName !== "") {
            this.getColumn(ClassName)
            this.getFindField(ClassName)
            this.getData(ClassName)
            this.GetLinkTableData(ClassName)
        }
    }

    componentDidMount() {
        let ClassName = "";
        if (this.props.location) {
            if (this.props.location.state) {
                ClassName = this.props.location.state.ClassName ? this.props.location.state.ClassName : "";
            }

        } else {
            if (this.props.paras) {
                ClassName = this.props.paras.ClassName ? this.props.paras.ClassName : "";
            } else {
                ClassName = this.props.ClassName ? this.props.ClassName : "";
            }

        }
        if (ClassName === "") return
        //let ClassName = this.props.ClassName ? this.props.ClassName:"";
        //let ClassTitle = this.props.ClassTitle ? this.props.ClassTitle:"";
        let ClassTitle = ""
        this.setState({
            ClassName: ClassName,
            ClassTitle: ClassTitle
        })
        this.getColumn(ClassName)
        this.getFindField(ClassName)
        this.getData(ClassName)
        this.GetLinkTableData(ClassName)
        // 初始化设置table的高度以及表体的高度
        if (document.querySelector('.ant-table-body')) {
            document.querySelector('.ant-table-body').style.height = store.getState().tableHeight.y + 80 + 'px'
        }
    }

    getColumn = (ClassName) => {
        let data = {
            params: [{ ClassName: ClassName }]
        }
        $http.post("urlS", this, {
            code: "4002",
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    this.setState({
                        columns: res.result.Data,
                        TableWidth: res.result.tableWidth
                    })
                } else {
                    message.error('失败：' + res.errorMessage);
                }
            },
            error: function (error) {
                message.error('失败：' + error);
            }
        })
    }

    getFindField = (ClassName) => {
        const hospDr = this.props.hospDr ? this.props.hospDr : ""
        const groupDr = this.props.groupDr ? this.props.groupDr : ""
        let data = {
            params: [{
                ClassName: ClassName,
                groupId: groupDr,
                hospitalId: hospDr
            }]
        }
        $http.post("urlS", this, {
            code: "4001",
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    var findField = res.result.Data
                    var remoteSearchArr = {}
                    for (var i = 0; i < findField.length; i++) {
                        var findFieldItem = findField[i]
                        var remoteSearch = findFieldItem.remoteSearch
                        if (remoteSearch != "Y") {
                            continue
                        }
                        var code = findFieldItem.Code
                        var data = findFieldItem.Data
                        var remoteSearch = findFieldItem.remoteSearch
                        var dataCopy = []
                        if (data.length > 100) {
                            var dataCopy = data.slice(0, 100)
                        }
                        remoteSearchArr[code] = dataCopy
                    }
                    this.setState({ findField: res.result, remoteSearchArr: remoteSearchArr })

                } else {
                    message.error('失败：' + res.errorMessage);
                }
            },
            error: function (error) {
                message.error('失败：' + error);
            }
        })
    }

    getData = (ClassName) => {
        let { page, pageSize } = this.state;
        const hospDr = this.props.hospDr ? this.props.hospDr : ""
        const groupDr = this.props.groupDr ? this.props.groupDr : ""
        let data = {
            params: [{
                ClassName: ClassName,
                FindFieldVal: this.FindFieldVal,
                groupId: groupDr,
                hospitalId: hospDr
            }],
            pagination: [{
                pageSize: pageSize,
                currentPage: page,
                sortColumn: "",
                sortOrder: ""
            }]
        }
        $http.post("urlS", this, {
            code: "4003",
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    this.setState({ data: res.result.Data })
                    this.setState({ total: res.result.TotalCount })
                } else {
                    message.error('失败：' + res.errorMessage);
                }
            },
            error: function (error) {
                message.error('失败：' + error);
            }
        })
    }

    getEditField = () => {
        let data = {
            params: [{ ClassName: this.state.ClassName }]
        }
        $http.post("urlS", this, {
            code: "4004",
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    this.setState({ editField: res.result })
                } else {
                    message.error('失败：' + res.errorMessage);
                }
            },
            error: function (error) {
                message.error('失败：' + error);
            }
        })
    }

    handleSubmit = () => {

    }

    getAllData() {
        this.getData(this.state.ClassName)
    }

    onClickRow = (record) => {
        //给右边的编辑form传值
        this.refs.editfield.resetFields()
        return {
            onClick: () => {
                if (this.state.rowId === "") {
                    this.setState({
                        rowId: record.ID,
                    });
                } else {
                    if (this.state.rowId !== record.ID) {
                        this.setState({
                            rowId: record.ID,
                        });
                    } else {
                        this.setState({
                            rowId: "",
                            detailInfo: {},
                        });
                    }
                }

            },
        };
    }

    setRowClassName = (record) => {
        return record.ID === this.state.rowId ? 'clickRowStyle' : '';
    }

    tableOnChange = (selectedRowKeys, selectedRows) => {
    }

    setConfig = () => {
        // 打开抽屉
        this.child.showDrawer();
    }

    resetEditFieldData = () => {
        this.setState({
            rowId: "",
            detailInfo: {}
        });
    }

    // 调用子组件的连接事件
    onRef = (ref) => {
        this.child = ref
    }

    onChangeCode = (FieldName, e) => {
        var FindFieldVal = this.FindFieldVal
        FindFieldVal[FieldName] = e.target.value
        this.FindFieldVal = FindFieldVal

    }

    onChangeSwitch = (checked, e) => {
        var FindFieldVal = this.FindFieldVal
        if (checked) {
            checked = "Y"
        } else {
            checked = "N"
        }
        FindFieldVal[e.currentTarget.id] = checked
        this.FindFieldVal = FindFieldVal
    }

    FindData = () => {
        this.setState({
            page: 1
        })
        let ClassName = this.state.ClassName;
        //let ClassName = this.props.ClassName ? this.props.ClassName:"";
        let { pageSize } = this.state;
        let data = {
            params: [{
                ClassName: ClassName,
                FindFieldVal: this.FindFieldVal
            }],
            pagination: [{
                pageSize: pageSize,
                currentPage: 1,
                sortColumn: "",
                sortOrder: ""
            }]
        }
        $http.post("urlS", this, {
            code: "4003",
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    this.setState({ data: res.result.Data })
                    this.setState({ total: res.result.TotalCount })
                } else {
                    message.error('失败：' + res.errorMessage);
                }
            },
            error: function (error) {
                message.error('失败：' + error);
            }
        })
    }

    SelectChange = (FieldName, value) => {
        if (+value === 0) {
            value = ""
        }
        var FindFieldVal = this.FindFieldVal
        FindFieldVal[FieldName] = value
        this.FindFieldVal = FindFieldVal
    }

    VisibleChange = (FieldName, value) => {
        if (+value === 0) {
            value = ""
        }
        var dataArr = []
        var fieldData = this.state.findField.Data
        var remoteSearchArr = this.state.remoteSearchArr
        for (var i = 0; i < fieldData.length; i++) {
            var fieldDataItem = fieldData[i]
            var code = fieldDataItem.Code
            var data = fieldDataItem.Data
            if (code != FieldName) continue
            var count = 0
            for (var j = 0; j < data.length; j++) {
                var dataItem = data[j]
                var desc = dataItem.Desc
                var alias = dataItem.Alias
                var flag = (desc.toLowerCase().indexOf(value.toLowerCase()) >= 0) || (alias.toLowerCase().indexOf(value.toLowerCase()) >= 0)
                if (!flag) continue
                count = count + 1
                if (count <= 100) {
                    dataArr.push(dataItem)
                } else {
                    break
                }
            }
        }
        remoteSearchArr[FieldName] = dataArr
        this.setState({ remoteSearchArr: remoteSearchArr })
    }

    GetComponent = (FieldItemData, key) => {
        var remoteSearchArr = this.state.remoteSearchArr
        if (FieldItemData.Type === "DR") {
            var code = FieldItemData.Code
            var fieldItemDataArr = []
            var remoteSearch = FieldItemData.remoteSearch
            if (remoteSearch == "Y") {
                var fieldItemDataArr = remoteSearchArr[code]
            } else {
                var fieldItemDataArr = FieldItemData.Data
            }
            return (
                <Select
                    allowClear={true}
                    key={key}
                    placeholder=""
                    showSearch
                    optionFilterProp="children"
                    onChange={this.SelectChange.bind(this, FieldItemData.Code)}
                    onSearch={this.VisibleChange.bind(this, FieldItemData.Code)}
                    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
                    }}
                    style={{ width: '70%' }}
                >
                    {

                        //FieldItemData.Data&&FieldItemData.Data.length&&FieldItemData.Data.map((d,index) => {
                        //        console.log("ababa")
                        //        return <Option key={d.ID} alias={d.Alias}>{d.Desc}</Option>
                        //}) 
                        fieldItemDataArr && fieldItemDataArr.length && fieldItemDataArr.map((d, index) => {
                            return <Option key={d.ID} alias={d.Alias}>{d.Desc}</Option>
                        })
                    }
                </Select>
            )
        } else if ((FieldItemData.Type === "Text") || (FieldItemData.Type === "Integer")) {
            return (
                //<Input value={this.state.FindFieldVal[FieldItemData.Code]?this.state.FindFieldVal[FieldItemData.Code]:""} key={key} placeholder="请输入" id={FieldItemData.Code} style={{width: '60%', marginRight: '10px'}} onChange={this.onChangeCode.bind(this,FieldItemData.Code)} /> 
                <Input
                    key={key}
                    placeholder="请输入"
                    id={FieldItemData.Code}
                    ref={FieldItemData.Code}
                    style={{ width: '60%', marginRight: '10px' }}
                    onChange={this.onChangeCode.bind(this, FieldItemData.Code)}
                    onPressEnter={this.FindData}
                />

            )
        } else if (FieldItemData.Type === "Radio") {
            return (
                //{/*<Switch  checkedChildren="是" unCheckedChildren="否"  value={this.state.FindFieldVal[FieldItemData.Code]==="Y"?true:false} key={key}  id={FieldItemData.Code} style={{marginRight: '10px'}} onChange={this.onChangeSwitch}/>  */}
                <Select
                    key={key}
                    placeholder=""
                    optionFilterProp="children"
                    onChange={this.SelectChange.bind(this, FieldItemData.Code)}
                    filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                    style={{ width: '70%' }}
                >
                    <Option value="">全部</Option>
                    <Option value="Y">是</Option>
                    <Option value="N">否</Option>
                </Select>
            )
        }

    }

    // 页码改变的回调，参数是改变后的页码及每页条数
    PageChange = (page, pageSize) => {
        this.setState({ page: page, pageSize: pageSize }, () => {
            // 重新调用查询方法
            let ClassName = this.state.ClassName
            this.getData(ClassName)
        });
    }

    // 条数改变的回调
    onShowSizeChange = (current, size) => {
        this.setState({ page: current, pageSize: size }, () => {
            // 重新调用查询方法
            let ClassName = this.state.ClassName
            this.getData(ClassName)
        });
    }

    GetLinkTableData = (ClassName) => {
        let data = {
            params: [{ ClassName: ClassName }]
        }
        $http.post("urlS", this, {
            code: "4014",
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    this.setState({
                        LinkTableData: res.result
                    })
                } else {
                    message.error('失败：' + res.errorMessage);
                }
            },
            error: function (error) {
                message.error('失败：' + error);
            }
        })
    }

    DataAvailChange = (value, option) => {
        var FindFieldVal = this.FindFieldVal
        FindFieldVal.DataAvail = value
        this.FindFieldVal = FindFieldVal
    }

    ImportData = () => {
        this.DataImport.DrawerShow()
    }

    render() {
        if (this.state.ClassName === "") return <div></div>
        var fieldData = this.state.findField.Data
        const hospDr = this.props.hospDr ? this.props.hospDr : ""
        const groupDr = this.props.groupDr ? this.props.groupDr : ""
        return (
            <div className='db-data-body'>
                <br />
                <Row type="flex" justify="space-between">
                    <Col span={24}>
                        <div>
                            <Card >
                                <Row type="flex" >
                                    {
                                        fieldData.map((value, key) => {
                                            if (value.Code === "DataAvail") {
                                                return (
                                                    <Col span={4} key={key}>
                                                        {"状态"}:  <Select
                                                            key={key}
                                                            placeholder=""
                                                            ref="DataAvail"
                                                            defaultValue=""
                                                            optionFilterProp="children"
                                                            onChange={this.DataAvailChange}
                                                            filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                                                            style={{ width: '70%' }}
                                                        >
                                                            <Option value="">全部</Option>
                                                            <Option value="1">可用</Option>
                                                            <Option value="0">不可用</Option>
                                                        </Select>

                                                    </Col>
                                                )
                                            } else {
                                                return (
                                                    <Col span={4} key={key}>
                                                        {value.Desc}:  {this.GetComponent(value, key)}
                                                    </Col>
                                                )
                                            }
                                        })
                                    }
                                    <Col span={2}>
                                        <Button type="primary" onClick={this.FindData}>查询</Button>
                                    </Col>
                                    <Col span={2}>
                                        <Button type="primary" onClick={this.ImportData}>数据导入</Button>
                                        <input type='file' accept='.xlsx, .xls' style={{ display: 'none' }} onChange={this.onImportExcel} onClick={this.handleClick} ref={el => this.fileInput = el} />
                                    </Col>
                                </Row>
                            </Card>
                        </div>
                    </Col>
                </Row>
                <Row type="flex" justify="space-between">
                    <Col span={10}>
                        <Card>
                            <div>
                                <Table
                                    dataSource={this.state.data}
                                    columns={this.state.columns}
                                    rowClassName={this.setRowClassName}
                                    pagination={false}
                                    bordered
                                    onRow={this.onClickRow}
                                    rowKey={(data) => {
                                        return data.ID
                                    }}
                                    scroll={{ x: this.state.TableWidth, y: store.getState().tableHeight.y + 100 }}
                                //rowSelection={{onChange:this.tableOnChange,type:"radio"}}

                                />
                                {/* 分页: total--总条数  defaultCurrent--默认的当前页 hideOnSinglePage--只有一页时隐藏分页器 */}
                                <CommonPagination size="small" current={this.state.page} total={this.state.total} search='search'
                                    onShowSizeChange={this.onShowSizeChange} complete={true} dataSource={this.state.data}
                                    onChange={this.PageChange} pageSize={20} />
                            </div>
                        </Card>
                    </Col>

                    <Col span={14}>
                        <div>
                            {
                                this.state.LinkTableData.length === 0 ?
                                    (<Card> <Editfield detailInfo={this.state.detailInfo} rowId={this.state.rowId} className={this.state.ClassName} hospDr={hospDr} groupDr={groupDr} handelThis={this} ref="editfield" /></Card>)
                                    : (
                                        <Tabs type="card">
                                            <TabPane tab="基本信息" key="1">
                                                <div style={{ padding: '0px 25px' }}>
                                                    <Editfield detailInfo={this.state.detailInfo} rowId={this.state.rowId} className={this.state.ClassName} hospDr={hospDr} groupDr={groupDr} handelThis={this} ref="editfield" />

                                                </div>
                                            </TabPane>
                                            {
                                                this.state.LinkTableData.map((value, key) => {
                                                    //CBDataLink
                                                    return (
                                                        <TabPane tab={value.Desc} key={key + 2}>
                                                            <CBDataLink RefId={this.state.rowId} ClassName={value.Code} handelThis={this} ref={value.Code} />
                                                        </TabPane>
                                                    )
                                                })
                                            }
                                        </Tabs>
                                    )
                            }
                        </div>
                    </Col>
                </Row>
                {/* 新增配置 */}
                <CBDataImport className={this.state.ClassName} ClassTitle={"导数据"} ref={(dataImport) => this.DataImport = dataImport} />
            </div>
        );
    }
}

export default CBData;
