import React from 'react';
import ReactDOM from 'react-dom';
import {
    Table, Select, Button, Input, InputNumber, Form, message, DatePicker, Pagination
} from 'antd';
import { $http } from '../../containers/config/https';
import 'moment/locale/zh-cn';
import moment from 'moment';
moment.locale('zh-cn');

const Option = Select.Option;
const EditableContext = React.createContext();
const EditableRow = ({ form, index, ...props }) => (
    <EditableContext.Provider value={form}>
        <tr {...props} />
    </EditableContext.Provider>
);
const EditableFormRow = Form.create()(EditableRow);
const FormItem = Form.Item;
const getColumnsFromData = (result) => {
    let columns = [];
    if (result.length > 0) {
        let column = result[0];
        column = Object.keys(column);
        column.map(function (val, index) {
            let col = {};
            if (index == column.length - 1) {
                col = { title: val, dataIndex: val, key: val };
            } else {
                col = { title: val, dataIndex: val, key: val, width: 80 };
            }
            columns.push(col);
        });
    }
    else { }
    return columns;
}
class HisRefOrg extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            gridDataSource: [],
            columns: [],
            selNow: '',
            selKey: '',
            selTableName: '',
            selChild: [],
            orgColumn: [],
            orgDataSource: [],
            tableSelectedRowID: '',
            orgSelectedRowID: '',
            comparisonColumn: '',
            comparisonDataSource: [],
            TSelectedRowKeys: [],
            OSelectedRowKeys: [],
            editingKey: ''
        };
    }
    handleSelChange = (val, opt) => {
        this.getTableDataCol(val);
        this.setState({ selNow: val, selKey: opt.key, selTableName: opt.props.children }, this.getComparisonData);
        //console.log(opt);
        /*$http.post("", this, {
            code: '4028',
            data: { params: [{ className: val }] },
            success: function (res) {
                if (res.result.length > 0) {
                    let lastCol = res.result[res.result.length - 1];
                    delete lastCol.width;
                    res.result.splice(res.result.length - 1, 1, lastCol);
                    //let columns = getColumnsFromData(res.result);
                    this.setState({ columns: res.result });
                } else {
                    this.setState({ columns: [] });
                }
            },
            error: function () {
                this.setState({ errMsg: "数据加载失败，请重试!" });
            }
        });*/
    }
    getTableData=(val)=>{
        $http.post("", this, {
            code: 'ceshi002',
            data: { params: [{ className: val }] },
            success: function (res) {
                if (res.result.length > 0) {
                    if (this.state.columns.length == 0) {
                        let columns = getColumnsFromData(res.result);
                        this.setState({ columns: columns });
                    }
                    this.setState({ gridDataSource: res.result });
                } else {
                    this.setState({ gridDataSource: [] });
                }
            },
            error: function () {
                this.setState({ errMsg: "数据加载失败，请重试!" });
            }
        })
    }
    getTableDataCol=(val)=>{
        $http.post("", this, {
            code: '4028',
            data: { params: [{ className: val }] },
            success: function (res) {
                if (res.result.length > 0) {
                    let lastCol = res.result[res.result.length - 1];
                    delete lastCol.width;
                    res.result.splice(res.result.length - 1, 1, lastCol);
                    this.setState({ columns: res.result },this.getTableData(val));
                } else {
                    this.setState({ columns: [] },this.getTableData(val));
                }
            },
            error: function () {
                this.getTableData(val);
                this.setState({ errMsg: "数据加载失败，请重试!" });
            }
        });
    }
    tableSelect = (record, index, e) => {
        //console.log(record);
        this.setState({ tableSelectedRowID: record.ID, TSelectedRowKeys: [index] }, this.getComparisonData);
        //console.log(this.state.tableSelectedRowKeys);
    }
    getAllTableData = () => {
        $http.post("urlS", this, {
            code: 'ceshi001',
            data: { params: [] },
            success: function (res) {
                let children = [];
                res.result.map(function (value, key) {
                    //console.log(value.code+","+value.descripts)
                    children.push(<Option key={value.id} value={value.code}>{value.descripts}</Option>);
                });
                this.setState({ selChild: children });
            },
            error: function (err) {
                this.setState({ errMsg: "数据加载失败，请重试!" });
            }
        });
    }
    getOrgDataSource = () => {
        $http.post("urlS", this, {
            code: 'ceshi003',
            data: { params: [] },
            success: function (res) {
                if (res.result.length > 0) {
                    let columns = getColumnsFromData(res.result);
                    this.setState({ orgDataSource: res.result, orgColumn: columns });
                }
            },
            error: function (err) {
                this.setState({ errMsg: "数据加载失败，请重试!" });
            }
        });
    }
    getComparisonData = () => {
        let { selKey, tableSelectedRowID, orgSelectedRowID } = this.state;
        if (tableSelectedRowID == '' || selKey == '') return;
        let data = {
            params: [
                {
                    tableDataId: selKey,
                    orgDataId: orgSelectedRowID,
                    dataId: tableSelectedRowID
                }

            ]
        };
        $http.post("urlS", this, {
            code: 'ceshi004',
            data: data,
            success: function (res) {
                if (res.result.length > 0) {
                    this.setState({ comparisonDataSource: res.result });
                } else {
                    this.setState({ comparisonDataSource: [] });
                }
            },
            error: function (err) {
                this.setState({ errMsg: "数据加载失败，请重试!" });
            }
        });
    }
    onTableSelectChange = (selectedRowKeys, selectedRows) => {
        let { editingKey } = this.state;
        editingKey = editingKey != '' ? '' : '';
        this.setState({TSelectedRowKeys:selectedRowKeys, tableSelectedRowID: selectedRows[0].ID, editingKey: editingKey }, this.getComparisonData);
    }
    addComparise = (event) => {
        //console.log('selectedRowKeys changed: ', selectedRowKeys);
        //this.setState({ selectedRowKeys });
    }
    /*getDerivedStateFromProps(props, state) {
        this.getAllTableData();
        this.getOrgDataSource();
        console.log(props);
        console.log(state);
    }*/
    componentWillMount() {
        this.getAllTableData();
        this.getOrgDataSource();
    }
    componentDidMount() {
        message.config({ top: 150, duration: 1 });
    }
    render() {
        const comparisonColumn = [{
            title: '',
            dataIndex: '',
            key: 'Index',
            width: 15,
            align: 'center',
            //fixed:true
            //editable: true
            render: (text, record, index) => {
                return index + 1;
            }
        }, {
            title: '机构',
            dataIndex: 'CompOrgDr',
            key: 'CompOrgDr',
            width: 150,
            align: 'center',
            //fixed:true,
            editable: true,
            render: (text, record, index) => {
                //console.log(text);
                //console.log(this);
                //console.log(index);
                const { orgDataSource } = this.state;
                let val = text;
                orgDataSource.map((value, key) => {
                    if (value.ID == text) {
                        val = value.Descripts;
                    }
                });
                return val;
            }
        }, {
            title: '表名',
            dataIndex: 'TableName',
            key: 'TableName',
            width: 130,
            align: 'center',
            //fixed:true
        }, {
            title: '数据ID',
            dataIndex: 'DataID',
            key: 'DataID',
            width: 50,
            align: 'center',
            //fixed:true
        }, {
            title: '外部数据代码',
            dataIndex: 'ExtCode',
            key: 'ExtCode',
            width: 180,
            align: 'center',
            editable: true,
            //fixed:true
        }, {
            title: '外部数据描述',
            dataIndex: 'ExtDesc',
            key: 'ExtDesc',
            width: 180,
            editable: true,
            align: 'center',
            //fixed:true
        }, {
            title: '备注',
            dataIndex: 'Note',
            key: 'Note',
            width: 150,
            editable: true,
            align: 'center',
            //fixed:true
        }, {
            title: '生效日期',
            dataIndex: 'StartDate',
            key: 'StartDate',
            width: 120,
            editable: true,
            align: 'center',
            // fixed:true,
            render: (text, record, index) => {
                /*console.log(typeof record['StartDate']=='undefined');
                if (typeof record['StartDate']=='undefined'){
                    //console.log(record.StartDate);
                    return '';
                }else{
                    return (<span>{record.StartDate}</span>);
                }*/
                //console.log(text);
                let value = record.StartDate ? record.StartDate : '';
                if (Object.getPrototypeOf(value).constructor.name == 'Moment') {
                    console.log(value.format("YYYY-MM-DD"));
                    value = value.format("YYYY-MM-DD");
                }
                //console.log(value);
                return (<div dangerouslySetInnerHTML={{ __html: value }}></div>);
            }
        }, {
            title: '失效日期',
            dataIndex: 'StopDate',
            key: 'StopDate',
            width: 120,
            editable: true,
            align: 'center',
            render: (text, record, index) => {
                let value = record.StopDate ? record.StopDate : '';
                if (Object.getPrototypeOf(value).constructor.name == 'Moment') {
                    console.log(value.format("YYYY-MM-DD"));
                    value = value.format("YYYY-MM-DD");
                }
                //console.log(value);
                return (<div dangerouslySetInnerHTML={{ __html: value }}></div>);
            }
            //fixed:true
        }, {
            title: '创建日期',
            dataIndex: 'CreateDate',
            key: 'CreateDate',
            width: 120,
            align: 'center',
            //fixed:true
            //editable: true
        }, {
            title: '创建人',
            dataIndex: 'CreateUserDr',
            key: 'CreateUserDr'
            //width: 20,
            //editable: true
        }];
        const { gridDataSource, columns, selChild } = this.state;
        const { selKey, tableSelectedRowID, orgSelectedRowID, selNow, selTableName, editingKey } = this.state;
        const data = {
            tableDataDr: selKey,
            compOrgDr: orgSelectedRowID,
            dataID: tableSelectedRowID,
            tableName: selTableName
        }
        const title = (
            <div style={{ margin: '-10px 0px -10px 0px' }}>
                <Select
                    showSearch
                    style={{ width: '260px' }}
                    placeholder="请输入或选择对应表名"
                    optionFilterProp="children"
                    onChange={this.handleSelChange}
                >
                    {selChild}
                </Select>
            </div>
        );
        const { orgDataSource, orgColumn, comparisonDataSource, tableSelectedRowKeys, orgSelectedRowKeys } = this.state;

        const tableRowSelection = {
            selectedRowKeys: this.state.TSelectedRowKeys,
            type: 'radio',
            onChange: this.onTableSelectChange,
            columnWidth: 20,
            fixed:true
        };
        const pagination = (<Pagination
            total={gridDataSource.length}
            showTotal={(total, range) => `${range[0]}-${range[1]} of ${total} items`}
            pageSize={10}
            defaultCurrent={1} />);
        /*<div style={{ width: '48%', height: '45%', display: 'inline-block', float: 'right' }}>
                    <Table
                        bordered
                        title={() => 'title'}
                        scroll={{ x: 1000 }}
                        size='middle'
                        columns={orgColumn}
                        rowSelection={orgRowSelection}
                        dataSource={orgDataSource}
                        onRow={(record, index) => ({ onClick: (event) => { this.orgSelect(record, index, event); } })}
                    />
                </div>*/
        return (
            <div>
                <div style={{ width: '31%', display: 'inline-block', align: 'left' }}>
                    <Table
                        scroll={{ x: 2000, y: 300 }}
                        bordered
                        size='middle'
                        pagination={{
                            total: gridDataSource.length,
                            size: 'small',
                            showTotal: (total, range) => `${range[0]}-${range[1]} of ${total}`,
                            pageSize: 10,
                            defaultCurrent: 1,
                            style:{margin:'0px 0px 0px 0px'}
                        }}
                        title={() => title}
                        rowKey={(record) =>record.ID}
                        dataSource={gridDataSource}
                        columns={columns}
                        rowSelection={tableRowSelection}
                        onRow={(record, index) => ({ onClick: (event) => { this.tableSelect(record, index, event); } })}
                    />
                </div>

                <div style={{ width: '68%', height: '80%', display: 'inline-block', float: 'right' }}>
                    <EditableTable
                        bordered
                        data={data}
                        size='middle'
                        editingKey={editingKey}
                        columns={comparisonColumn}
                        dataSource={comparisonDataSource}
                        orgSelDataSource={orgDataSource}
                    />
                </div>
            </div>
        );
    }
}
class EditableCell extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            editing: false
        };
    }
    getInput = () => {
        if (this.props.inputType == 'number') {
            return <InputNumber onPressEnter={this.save} onBlur={this.save} />;
        } else if (this.props.inputType == 'date') {
            return <DatePicker onChange={this.onDateChange} format="YYYY-MM-DD" onPressEnter={this.save} onBlur={this.save} />;
        } else if (this.props.inputType == 'select') {
            let child = [];
            this.props.orgSelDataSource.map((value, key) => {
                child.push(<Option key={value.Code} value={value.ID}>{value.Descripts}</Option>);
            });
            //console.log(child);
            return (<Select
                showSearch
                style={{ width: 110 }}
                placeholder="请选择对应机构"
                optionFilterProp="children"
                onChange={this.onSelectChange}
                onBlur={this.save}
            >
                {child}
            </Select>);
        }
        return <Input onPressEnter={this.save} onBlur={this.save} onChange={this.onDataChange} />;
    }
    onDataChange = (e, ...rest) => {
        //console.log(e.target.value);
    }
    onDateChange = (dates, dateString) => {
        //console.log(dateString);
    }
    onSelectChange = (value, opt) => {
        //console.log(value);
    }
    toggleEdit = () => {
        const editing = !this.state.editing;
        this.setState({ editing: editing }, () => {
            if (editing) {
                this.input.focus();
            }
        })
    }
    save = () => {
        const { record: oldRecord, handleSave, saveEditRow } = this.props;
        this.form.validateFields((error, values) => {
            if (error) {
                return;
            }
            //this.toggleEdit();
            const newRecord = { ...oldRecord, ...values }
            if (JSON.stringify(newRecord) != JSON.stringify(oldRecord)) {
                saveEditRow(newRecord);
                handleSave(newRecord);
            }
        });
    }
    getRequired(record, dataIndex, inputType) {
        let ret = true;
        if (dataIndex == 'StopDate' || dataIndex == 'Note') {
            ret = false;
        }
        return ret;
    }
    getCellInitValue(record, dataIndex, inputType) {
        if (inputType == 'date') {
            if ((record[dataIndex] != '') && (typeof record[dataIndex] != 'undefined')) {
                record[dataIndex] = moment(record[dataIndex], 'YYYY-MM-DD');
            } else {
                if (dataIndex == 'StopDate') {
                    record[dataIndex] = '';
                } else if (dataIndex == 'StartDate') {
                    record[dataIndex] = moment(new Date(), "YYYY-MM-DD");
                }
            }
        } else if (inputType == 'select') {
            //console.log(record[dataIndex]);
        }
        return record[dataIndex];
    }
    render() {
        const {
            editing,
            dataIndex,
            title,
            inputType,
            record,
            index,
            handleSave,
            orgSelDataSource,
            saveEditRow,
            ...restProps
        } = this.props;
        return (
            <EditableContext.Consumer>
                {(form) => {
                    this.form = form;
                    const { getFieldDecorator } = form;
                    return (
                        <td {...restProps}>
                            {editing ? (
                                <FormItem style={{ margin: 0 }}>
                                    {getFieldDecorator(dataIndex, {
                                        rules: [{
                                            required: this.getRequired(record, dataIndex, inputType),
                                            message: `请输入   ${title}!`,
                                        }],
                                        initialValue: this.getCellInitValue(record, dataIndex, inputType),
                                    })(this.getInput())}
                                </FormItem>
                            ) : restProps.children}
                        </td>
                    );
                }}
            </EditableContext.Consumer>
        );
    }
}
class EditableTable extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            editingKey: props.editingKey,
            comparisonDataSource: props.dataSource,
            comparisonColumn: props.columns,
            parentData: props.data,
            orgSelDataSource: props.orgSelDataSource,
            editedRows: new Set(),
            editedRecord: {}
        };
    }
    componentWillReceiveProps(nextProps) {
        this.setState({
            comparisonDataSource: nextProps.dataSource,
            comparisonColumn: nextProps.columns,
            parentData: nextProps.data,
            editingKey: nextProps.editingKey,
            orgSelDataSource: nextProps.orgSelDataSource
        });
    }
    isEditing = index => index === this.state.editingKey;

    cancel = () => {
        this.setState({ editingKey: '' }, () => { console.log(); });
    };

    edit = (record, index, event) => {
        //console.log(record);
        //const {editedRows} = this.state;
        //console.log(editedRows);
        let child = event.target;
        console.log(child);
        this.setState({ editingKey: index }, () => { });
    }
    inputFocus = (e) => {
        const element = e.target;
        document.getElementById("ExtCode");
    }
    handleAdd = () => {
        const { comparisonDataSource, comparisonColumn, } = this.state;
        const { data } = this.props;
        const { dataID, tableDataDr, compOrgDr, tableName } = data;
        if (tableDataDr == "") {
            message.error('请先选择需要对照的数据表', 2);
            return;
        } else if (dataID == "") {
            message.error("请选择需要对照的具体数据", 2);
            return;
        }
        let oneData = {
            CompOrgDr: compOrgDr,
            TableDataDr: tableDataDr,
            DataID: dataID,
            TableName: tableName
        };
        /*comparisonColumn.map(function(value,key){
            let index =value.dataIndex;
            //console.log(index);
            oneData[index]='1';
        });
        console.log(oneData);*/
        const newData = [...comparisonDataSource, oneData];
        const index = newData.length - 1;
        this.setState({
            comparisonDataSource: [...comparisonDataSource, oneData],
            editingKey: index
        });
    }
    handleSave = (row) => {
        const newData = [...this.state.comparisonDataSource];
        const index = newData.findIndex((item, index) => index === this.state.editingKey);
        const item = newData[index];
        //const newItem = { ...item, ...row, }
        newData.splice(index, 1, {
            ...item,
            ...row,
        });
        this.setState({ comparisonDataSource: newData });
    }
    saveEditRow = (newItem) => {
        const { editedRows, editingKey, editedRecord } = this.state;
        const newEditedRows = [...new Set([...editedRows, editingKey])];
        editedRecord[editingKey] = newItem
        this.setState({ editedRows: newEditedRows, editedRecord: editedRecord }, () => { console.log(this.state.editedRecord) });
    }
    saveData = () => {
        /*this.props.form.validateFields((error, values) => {
            if (error) {
                return;
            }
            //this.toggleEdit();
            for (let el in values) {
                if (typeof values[el] != 'undefined' && Object.getPrototypeOf(values[el]).constructor.name === 'Moment') {
                    //console.log(Object.getPrototypeOf(values[el]));
                    values[el] = values[el].format('YYYY-MM-DD');
                }
            }
            handleSave({ ...record, ...values });
        });*/
        const { editedRecord: modifyData } = this.state;
        let data = [];
        for (let el in modifyData) {
            for (let key in modifyData[el]) {
                if (typeof modifyData[el][key] != 'undefined' && Object.getPrototypeOf(modifyData[el][key]).constructor.name === 'Moment') {
                    //console.log(Object.getPrototypeOf(values[el]));
                    modifyData[el][key] = modifyData[el][key].format('YYYY-MM-DD');
                }
            }
            data.push(modifyData[el]);
        }
        if (data.length <= 0) {
            message.warning("暂无数据需要保存");
            //console.log(JSON.parse(window.sessionStorage.userData).userId);
            this.setState({ editingKey: '' });
            return;
        }
        $http.post("", this, {
            code: 'ceshi005',
            data: { params: data, session: { userId: JSON.parse(window.sessionStorage.userData).userId } },
            success: function (res) {
                if (res.errorCode == 0) {
                    message.success(res.errorMessage);
                    if (res.result.length > 0) {
                        this.setState({ comparisonDataSource: res.result, editingKey: '', editedRecord: {} });
                    }
                } else {
                    //message.error(res.errorMessage);
                }
            },
            error: function () {
                this.setState({ errMsg: "数据加载失败，请重试!" });
            }
        });
    }
    getInputType = (dataIndex) => {
        let ret = 'text';
        if (dataIndex == 'StartDate' || dataIndex == 'StopDate') {
            ret = 'date';
        } else if (dataIndex == 'CompOrgDr') {
            ret = 'select';
        }
        return ret;
    }
    render() {
        const components = {
            body: {
                row: EditableFormRow,
                cell: EditableCell,
            },
        };
        //const {data}=this.props;
        //const {dataID,tableDataId,compOrgDr}=data;
        const addCompariseBtn = (
            <div style={{ margin: '-10px 0px -10px 0px' }}>
                <Button type="primary" onClick={this.handleAdd}>添加</Button>
                <EditableContext.Consumer>
                    {form => (
                        <Button style={{ margin: '0px 0px 0px 5px' }} type="primary" onClick={this.saveData}>保存</Button>
                    )}
                </EditableContext.Consumer>
            </div>
        );
        const columns = this.props.columns.map((col) => {
            if (!col.editable) {
                return col;
            }
            return {
                ...col,
                onCell: (record, index) => ({
                    record,
                    inputType: this.getInputType(col.dataIndex),
                    dataIndex: col.dataIndex,
                    title: col.title,
                    handleSave: this.handleSave,
                    saveEditRow: this.saveEditRow,
                    editing: this.isEditing(index),
                    orgSelDataSource: this.state.orgSelDataSource
                }),
            };
        });
        return (
            <Table
                components={components}
                bordered
                dataSource={this.state.comparisonDataSource}
                columns={columns}
                title={() => addCompariseBtn}
                scroll={{ x: 1360, y: 300 }}
                rowClassName="editable-row"
                size='middle'
                rowKey={(record) => record.ID}
                onRow={(record, index) => ({ onDoubleClick: (event) => this.edit(record, index, event) })}
                pagination={{
                    onChange: this.cancel,
                    style:{margin:'0px 0px 0px 0px'}
                }}
            />
        );
    }
}
export default HisRefOrg;