// 基础数据
import React, { Component } from 'react';
import { Tabs, Switch, Checkbox, Input, Row, Col, Button, message, Table, DatePicker, Select, Card } from 'antd';
import CBDataModel from './CBDataModel'
import { $http } from '../../containers/config/https';
import store from '../../store';
import TableDataForm from './TableDataForm'
import TableDataSelectMethod from './TableDataSelectMethod'
import TableDataGetDataMethod from './TableDataGetDataMethod'
import TableDataEditField from './TableDataEditField'
import ReactDOM from 'react-dom'
import CommonPagination from 'components/pagination/index';
const TabPane = Tabs.TabPane;

class TableDataConfig extends Component {
    constructor(props) {
        super(props);
        this.state = {
            ClassData: [],
            FieldData: [],
            ClassName: "",
            ClassTitle: "",
            selectedRowKeys: [],
            code: "",
            desc: "",
            total: 0,
            page: 1,
            pageSize: 20,
            editdata: "",
            TableData: {},
            selectRowid: ""
        };
        this.clientWidth = 1400
        this.classColumns = [
            {
                key: 1,
                title: '表名',
                dataIndex: 'Code',
                width: 150,
                align: "center"
            },
            {
                key: 2,
                title: '表描述',
                dataIndex: 'Descripts',
                width: 150,
                align: "center"
            }
        ]
        this.fieldColumns = [
            {
                key: 1,
                title: '字段名',
                dataIndex: 'Code',
                width: 20,
                align: "center"
            },
            {
                key: 2,
                title: '字段描述',
                dataIndex: 'Descripts',
                width: 80,
                align: "center",
                render: (text, record, index) => {
                    var Descripts = record.Descripts
                    return (
                        <Input value={Descripts} onChange={this.DescriptsChange.bind(this, record, index)}></Input>
                    )
                }
            },
            {
                key: 3,
                title: '字段类型',
                dataIndex: 'CompType',
                width: 50,
                align: "center",
                render: (text, record, index) => {
                    if (record.CompType === "Text") {
                        return (
                            <Input disabled={true} />
                        )
                    } else if (record.CompType === "Radio") {
                        return (
                            <Switch checkedChildren="是" unCheckedChildren="否" />
                        )
                    } else if (record.CompType === "Date") {
                        return (
                            <DatePicker disabled={true} format="YYYY-MM-DD" />
                        )
                    } else if (record.CompType === "DR") {
                        return (
                            <Select style={{ width: 80 }} disabled={true} />
                        )
                    } else if (record.CompType === "Select") {
                        return (
                            <Select style={{ width: 80 }} disabled={true} />
                        )
                    }
                    else {
                        return (
                            <Input disabled={true} />
                        )
                    }
                }
            },
            {
                key: 4,
                title: '查询标志',
                dataIndex: 'FindFlag',
                width: 40,
                align: "center",
                render: (text, record, index) => {
                    var FindFlag = record.FindFlag
                    if (FindFlag === "Y") {
                        FindFlag = true
                    } else {
                        FindFlag = false
                    }
                    return (
                        <Checkbox checked={FindFlag} onChange={this.CheckOnChange.bind(this, record, index, 'FindFlag')}></Checkbox>
                    )
                }
            },
            {
                key: 5,
                title: '编辑标志',
                dataIndex: 'EditFlag',
                width: 40,
                align: "center",
                render: (text, record, index) => {
                    var EditFlag = record.EditFlag
                    if (EditFlag === "Y") {
                        EditFlag = true
                    } else {
                        EditFlag = false
                    }
                    var disabled = false
                    if (+record.ChangeEditFlag === 0) {
                        disabled = true
                    }
                    return (
                        <Checkbox checked={EditFlag} disabled={disabled} onChange={this.CheckOnChange.bind(this, record, index, 'EditFlag')}></Checkbox>
                    )
                }
            },
            {
                key: 6,
                title: '列输出标志',
                dataIndex: 'ColumnFlag',
                width: 40,
                align: "center",
                render: (text, record, index) => {
                    var ColumnFlag = record.ColumnFlag
                    if (ColumnFlag === "Y") {
                        ColumnFlag = true
                    } else {
                        ColumnFlag = false
                    }
                    return (
                        <Checkbox checked={ColumnFlag} onChange={this.CheckOnChange.bind(this, record, index, 'ColumnFlag')}></Checkbox>
                    )
                }
            }, {
                key: 7,
                title: '只读标志',
                dataIndex: 'ReadOnlyFlag',
                width: 40,
                align: "center",
                render: (text, record, index) => {
                    var ReadOnlyFlag = record.ReadOnlyFlag
                    if (ReadOnlyFlag === "Y") {
                        ReadOnlyFlag = true
                    } else {
                        ReadOnlyFlag = false
                    }
                    return (
                        <Checkbox checked={ReadOnlyFlag} onChange={this.CheckOnChange.bind(this, record, index, 'ReadOnlyFlag')}></Checkbox>
                    )
                }
            },
            {
                key: 8,
                title: '列宽',
                dataIndex: 'ColumnWidth',
                width: 50,
                align: "center",
                render: (text, record, index) => {
                    var ColumnWidth = record.ColumnWidth
                    if (ColumnWidth === "") {
                        //ColumnWidth=50
                    }
                    return (
                        <Input value={ColumnWidth} onChange={this.ColumnWidthChange.bind(this, record, index)}></Input>
                    )
                }
            },
            /*{
                key: 7,
                title: '指向表',
                dataIndex: 'DirectTable',
                width: 30,
                align: "center",
            },
            {
              key: 8,
              title: '显示字段名',
              dataIndex: 'ShowField',
              width: 80,
              align: "center"
            }*/
        ]

    }

    componentDidMount() {
        var obj = ReactDOM.findDOMNode(this)
        if (obj) {
            this.clientWidth = obj.clientWidth
        }
        this.getClassData("", "")
        //this.getFieldData()
    }

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

    onClickRow = (record) => {
        //给右边的编辑form传值
        this.refs.TableData.resetFields()
        return {
            onClick: () => {
                //var itemData=res.result
                this.setState({ selectedRowKeys: [] })
                var ClassName = "", ClassTitle = "", selectRowid = ""
                if (this.state.ClassName === "") {
                    ClassName = record.Code
                    ClassTitle = record.Descripts
                    selectRowid = record.ID
                } else {
                    if (this.state.ClassName !== record.Code) {
                        ClassName = record.Code
                        ClassTitle = record.Descripts
                        selectRowid = record.ID
                    } else {
                        ClassName = ""
                        ClassTitle = ""
                        selectRowid = ""
                    }
                }
                this.setState({
                    ClassName: ClassName,
                    ClassTitle: ClassTitle,
                    selectRowid: selectRowid
                });
                if (ClassName !== "") {
                    this.getFieldData(ClassName)
                } else {
                    this.setState({
                        FieldData: []
                    })
                }
            },
        };
    }

    getClassData = (code, desc, selectFirstRow) => {
        const userData = sessionStorage.userData ? JSON.parse(sessionStorage.userData) : {}
        let { page, pageSize } = this.state;
        let data = {
            params: [
                {
                    Descripts: desc,
                    Code: code,
                    Group: userData.groupID,
                    Hospital: userData.hospID,
                    User: userData.userID
                }
            ],
            pagination: [{
                pageSize: pageSize,
                currentPage: page,
                sortColumn: "",
                sortOrder: ""
            }]
        }
        $http.post("urlS", this, {
            code: "4010",
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    this.setState({ ClassData: res.result.Data }, () => {
                        if (selectFirstRow) {
                            var data = res.result.Data[0]
                            this.setState({
                                ClassName: data.Code,
                                ClassTitle: data.Descripts,
                                selectRowid: data.ID
                            });
                            if (data.Code !== "") {
                                this.getFieldData(data.Code)
                            } else {
                                this.setState({
                                    FieldData: []
                                })
                            }
                        }
                    })
                    this.setState({ total: res.result.TotalCount })
                } else {
                    message.error('失败：' + res.errorMessage);
                }
            },
            error: function (error) {
                message.error('失败：' + error);
            }
        })
    }

    getFieldData = (className) => {
        //var className=this.props.className
        let data = {
            params: [{ ClassName: className }]
        }
        $http.post("urlS", this, {
            code: "4008",
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    var data = res.result
                    this.setState({ FieldData: data }, () => {

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

    handleUp = () => {
        var keys = this.state.selectedRowKeys
        var data = this.state.FieldData
        var newKeys = []
        keys = keys.sort(function (m, n) {
            if (m < n) return -1
            else if (m > n) return 1
            else return 0
        });
        for (var i = 0; i < keys.length; i++) {
            if (keys[i] === 0) {
                newKeys.push(keys[i])
                continue
            }
            var curRowData = data[keys[i]]
            var curRowKey = curRowData.key
            var upRowData = data[keys[i] - 1]
            var upRowKey = upRowData.key
            upRowData.key = curRowKey
            curRowData.key = upRowKey

            data[keys[i]] = upRowData
            data[keys[i] - 1] = curRowData
            newKeys.push(keys[i] - 1)
        }
        this.setState(
            {
                FieldData: data,
                selectedRowKeys: newKeys
            }
        )
    }

    handleDown = () => {
        var keys = this.state.selectedRowKeys
        var data = this.state.FieldData
        var newKeys = []
        keys = keys.sort(function (m, n) {
            if (m < n) return -1
            else if (m > n) return 1
            else return 0
        });
        for (var i = keys.length - 1; i >= 0; i--) {
            if (keys[i] === data.length - 1) {
                newKeys.push(keys[i])
                continue
            }
            var curRowData = data[keys[i]]
            var upRowData = data[keys[i] + 1]
            var curRowKey = curRowData.key
            var upRowKey = upRowData.key
            upRowData.key = curRowKey
            curRowData.key = upRowKey
            data[keys[i]] = upRowData
            data[keys[i] + 1] = curRowData
            newKeys.push(keys[i] + 1)
        }
        this.setState(
            {
                FieldData: data,
                selectedRowKeys: newKeys
            }
        )
    }

    saveRecordEdit = () => {
        var tableData = this.state.FieldData
        var idStr = ""
        var EditData = []
        for (var i = 0; i < tableData.length; i++) {
            var id = tableData[i].ID
            if (idStr === "") {
                idStr = id
            } else {
                idStr = idStr + "^" + id
            }
            if (tableData[i].Descripts === "") {
                message.error("字段" + tableData[i].Code + "的描述不能为空");
                return
            }
            var itemEditData = {}
            itemEditData.ID = id
            itemEditData.Descripts = tableData[i].Descripts
            itemEditData.FindFlag = tableData[i].FindFlag
            itemEditData.EditFlag = tableData[i].EditFlag
            itemEditData.ColumnFlag = tableData[i].ColumnFlag
            itemEditData.ColumnWidth = tableData[i].ColumnWidth
            itemEditData.ReadOnlyFlag = tableData[i].ReadOnlyFlag


            EditData.push(itemEditData)
        }
        var className = this.state.ClassName
        let data = {

            params: [
                {
                    ClassName: className,
                    FieldSort: idStr,
                    EditData: EditData
                }
            ]
        }
        $http.post("urlADS", this, {
            code: "4009",
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    message.success('保存成功');
                } else {
                    message.error('失败：' + res.errorMessage);
                }
            },
            error: function (error) {
                message.error('失败：' + error);
            }
        })
    }

    CheckOnChange = (record, index, field) => {
        if (record[field] === "Y") {
            record[field] = "N"
        } else {
            record[field] = "Y"
        }
        var data = this.state.FieldData
        data[index] = record
        this.setState({ FieldData: data })
    }

    Add = () => {
        let className = this.refs.ClassName.state.value
        if (className === "") {
            message.error("请输入表名");
            return
        }
        var desc = this.refs.Descripts.state.value
        if (desc === "") {
            message.error("请输入描述");
            return
        }
        let data = {

            params: [
                {
                    Code: className,
                    Descripts: desc
                }
            ]
        }
        $http.post("urlADS", this, {
            code: "4011",
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    message.success('保存成功');
                    this.getClassData("", "")
                } else {
                    message.error('失败：' + res.errorMessage);
                }
            }
        })

    }

    Find = () => {
        this.setState({
            page: 1
        }, () => {
            var code = this.refs.ClassName.state.value
            var desc = this.refs.Descripts.state.value
            if (typeof code === "undefined") {
                code = ""
            }
            if (typeof desc === "undefined") {
                desc = ""
            }
            this.getClassData(code, desc)
        })
    }

    handleKeyDown(e) {
        if (e.keyCode == '13') {
            this.Find()
        }
    }

    InputChange = (e) => {
        this.setState(
            { code: e.target.value }
        )
    }

    DescChange = (e) => {
        this.setState(
            { desc: e.target.value }
        )
    }

    handleData = () => {
        if (this.state.ClassName === "") {
            message.error("请选择要维护数据的表");
            return
        }
        let data = {
            params: [
                {
                    ClassName: this.state.ClassName
                }
            ]
        }
        $http.post("urlADS", this, {
            code: "4019",
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    this.refs.CBDataModel.setState({
                        visible: true
                    })
                } else {
                    message.error('失败：' + res.errorMessage);
                }
            }
        })
    }

    DescriptsChange = (record, index, e) => {
        record.Descripts = e.target.value
        var data = this.state.FieldData
        data[index] = record
        this.setState({ FieldData: data })
    }

    ColumnWidthChange = (record, index, e) => {
        record.ColumnWidth = e.target.value
        var data = this.state.FieldData
        data[index] = record
        this.setState({ FieldData: data })
    }

    // 页码改变的回调，参数是改变后的页码及每页条数
    PageChange = (page, pageSize) => {
        this.setState({ page: page, pageSize: pageSize }, () => {
            // 重新调用查询方法
            var code = this.refs.ClassName.state.value
            var desc = this.refs.Descripts.state.value
            if (typeof code === "undefined") {
                code = ""
            }
            if (typeof desc === "undefined") {
                desc = ""
            }
            this.getClassData(code, desc)
        });
    }

    // 条数改变的回调
    onShowSizeChange = (current, size) => {
        this.setState({ page: current, pageSize: size }, () => {
            // 重新调用查询方法
            var code = this.refs.ClassName.state.value
            var desc = this.refs.Descripts.state.value
            if (typeof code === "undefined") {
                code = ""
            }
            if (typeof desc === "undefined") {
                desc = ""
            }
            this.getClassData(code, desc)
        });
    }

    resetEditFieldData = () => {
        this.setState({
            ClassName: "",
            ClassTitle: "",
            selectRowid: "",
            FieldData: []
        });
    }

    onClose = () => {
        this.setState({
            editdata: 0,
        });
    };

    UpdateField = () => {
        var className = this.state.ClassName
        if (className === "") {
            return
        }
        let data = {
            params: [
                {
                    className: className
                }
            ]
        }
        $http.post("urlADS", this, {
            code: "4031",
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    message.success('字段更新成功');
                    this.getFieldData(this.state.ClassName)
                } else {
                    message.error('失败：' + res.errorMessage);
                }
            }
        })
    }

    render() {
        // const rowSelection = {
        //     onChange: (selectedRowKeys, selectedRows) => {
        //         this.setState({ selectedRowKeys: selectedRowKeys })
        //     },
        //     getCheckboxProps: record => ({
        //         disabled: record.name === 'Disabled User', // Column configuration not to be checked
        //         name: record.name,
        //     }),
        //     selectedRowKeys: this.state.selectedRowKeys
        // };
        return (
            <div>
                <Row type="flex" justify="space-between">
                    <Col span={7}>
                        <Card >
                            <div>
                                <Row type="flex" >
                                    <Col span={18}> 表名: <Input ref="ClassName" placeholder="请输入" style={{ width: '200px', marginRight: '10px' }} /> </Col>
                                    <Col span={6}>   <Button type="primary" onClick={this.Find}>查询</Button>   </Col>
                                </Row>
                                <br />
                                <Row type="flex" >
                                    <Col span={18}> 描述: <Input ref="Descripts" placeholder="请输入" style={{ width: '200px', marginRight: '10px' }}
                                        onKeyDown={this.handleKeyDown.bind(this)} /> </Col>
                                    <Col span={6}>   <Button type="primary" onClick={this.handleData}>数据维护</Button>  </Col>
                                </Row>
                                <br />
                                <Table
                                    dataSource={this.state.ClassData}
                                    columns={this.classColumns}
                                    rowClassName={this.setRowClassName}
                                    pagination={false}
                                    bordered
                                    rowKey="ID"
                                    onRow={this.onClickRow}
                                    style={{ height: store.getState().tableHeight.y + 45 + 'px' }}
                                    scroll={{ y: store.getState().tableHeight.y, x: 300 }}
                                //rowSelection={{onChange:this.tableOnChange,type:"radio"}}
                                />
                                <CommonPagination size="small" current={this.state.page} total={this.state.total} search='search'
                                    onShowSizeChange={this.onShowSizeChange} complete={false} dataSource={this.state.ClassData}
                                    onChange={this.PageChange} pageSize={20} />
                                {/* 分页: total--总条数  defaultCurrent--默认的当前页 hideOnSinglePage--只有一页时隐藏分页器 */}

                            </div>
                        </Card>
                    </Col>

                    <Col span={17} style={{ padding: 5 }}>
                        <Tabs type="card">
                            <TabPane tab="基本信息" key="1">
                                <TableDataForm selectRowid={this.state.selectRowid} handelThis={this} ref="TableData" />
                            </TabPane>
                            <TabPane tab="字段维护" key="2">
                                <TableDataEditField className={this.state.ClassName} handelThis={this} ref="TableDataEditField" />
                            </TabPane>
                            <TabPane tab="下拉框方法" key="3">
                                <TableDataSelectMethod className={this.state.ClassName} handelThis={this} ref="TableDataSelectMethod" />
                            </TabPane>
                            <TabPane tab="数据对象方法" key="4">
                                <TableDataGetDataMethod className={this.state.ClassName} handelThis={this} ref="TableDataGetDataMethod" />
                            </TabPane>
                        </Tabs>
                    </Col>
                </Row>

                <CBDataModel clientWidth={this.clientWidth} ClassName={this.state.ClassName} ClassTitle={this.state.ClassTitle} ref="CBDataModel" />
            </div>
        );
    }
}
export default TableDataConfig;