/**
 * 导入配置
 */

import React from 'react';
import {
    Card, Table, Input, Form, Select, Row, Col, Checkbox,
    DatePicker, Button, Popconfirm, Icon, Divider, message, Pagination, Switch
} from 'antd';
import { Util, dayFormat } from 'tools/index';
import { $http } from 'containers/config/https';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';
import RangeDatePicker from 'components/rangePicker/index';
import CommonPagination from 'components/pagination/index';
import * as XLSX from 'xlsx';
import { handleExcel } from 'tools/handleExcel.js';
import ShowSourceTypeModal from './component/ShowSourceTypeModal';
import { PAGE_NUM_MORE_STATUS } from 'tools/statusConstants';
import store from 'store';
import moment from 'moment';
import './style/index.less';

const { RangePicker } = DatePicker;
const InputGroup = Input.Group;
const Option = Select.Option;
const Search = Input.Search;
const FormItem = Form.Item;

class ImportConfigPage extends React.Component {
    constructor(props) {
        var userData = JSON.parse(sessionStorage.getItem('userData'));
        var date = new Date()
        super(props)
        this.state = {
            dataSource: [],
            startDate: moment(date).format(dayFormat),
            stopDate: moment(date).format(dayFormat),
            userData: userData,
            leftData: [],
            total: 0,
            page: 1,
            pageSize: 10,
            size: 'small',
            curPageDetail: PAGE_NUM_MORE_STATUS[0].code,
            type: 'String'
        }
    }

    componentDidMount() {
        this.initData()
        this.loadLeftData()
        this.loadRightData(1)
    }

    initData() {
        this.leftColumns = [
            {
                title: '代码',
                dataIndex: 'code',
                width: 80,
                align: 'center'
            },
            {
                title: '描述',
                dataIndex: 'descripts',
                width: 200,
                align: 'center'
            },
            {
                title: '方法名',
                dataIndex: 'methodName',
                width: 200,
                align: 'center'
            },
            {
                title: '类名',
                dataIndex: 'className',
                width: 250,
                align: 'center'
            },
            {
                title: '备注',
                dataIndex: 'note',
                width: 120,
                align: 'center'
            },
            {
                title: '操作',
                dataIndex: 'opertion',
                width: 120,
                align: 'center',
                fixed:'right',
                render: (text, data) => {
                    return <span>
                        <Icon type="edit" style={{ color: '#108EE9' }}></Icon>
                        <span className='span' onClick={this.editData.bind(this, data)}>编辑</span>
                        <Divider type="vertical" />
                        <Icon type="delete" style={{ color: 'rgba(240,65,52,1)' }}></Icon>
                        <Popconfirm title="删除不可恢复，你确定要删除吗?" onConfirm={this.handleDel.bind(this, data)} >
                            <span className='span' style={{ color: 'rgba(240,65,52,1)' }}>删除</span>
                        </Popconfirm>
                    </span >
                }
            },
        ],
            this.rightColumns = [
                {
                    title: '代码',
                    dataIndex: 'code',
                    width: 80,
                    align: 'center'
                },
                {
                    title: '描述',
                    dataIndex: 'descripts',
                    width: 150,
                    align: 'center'
                },
                {
                    title: '英文描述',
                    dataIndex: 'enDescripts',
                    width: 80,
                    align: 'center'
                },
                {
                    title: '类型',
                    dataIndex: 'type',
                    width: 80,
                    align: 'center'
                },
                {
                    title: '是否必选',
                    dataIndex: 'required',
                    width: 80,
                    align: 'center'
                },
                {
                    title: '操作',
                    dataIndex: 'opertion',
                    width: 80,
                    align: 'center',
                    render: (text, data) => {
                        return <span>
                            <Icon type="delete" style={{ color: 'rgba(240,65,52,1)' }}></Icon>
                            <Popconfirm title="删除不可恢复，你确定要删除吗?" onConfirm={this.handleDelRightData.bind(this, data)} >
                                <span className='span' style={{ color: 'rgba(240,65,52,1)' }}>删除</span>
                            </Popconfirm>
                        </span>
                    }
                },
            ]
    }

    handleDel(data) {
        var params = {
            params: [
                {
                    userID: this.state.userData.userID,
                    hospID: this.state.userData.hospID,
                    groupID: this.state.userData.groupID,
                    id: [data.id]
                }
            ]
        }
        $http.post('urlDeault', this, {
            code: "01040202",
            data: params,
            success: function (res) {
                if (res.errorCode === '0') {
                    this.loadLeftData(1);
                    message.success('删除成功！')
                }
            }
        });
    }

    handleDelRightData(data) {
        var params = {
            params: [
                {
                    userID: this.state.userData.userID,
                    hospID: this.state.userData.hospID,
                    groupID: this.state.userData.groupID,
                    id: [data.id]
                }
            ]
        }
        $http.post('urlDeault', this, {
            code: "01040205",
            data: params,
            success: function (res) {
                if (res.errorCode === '0') {
                    this.loadRightData(1);
                    message.success('删除成功！')
                }
            }
        });
    }

    editData(data) {
        this.setState({
            isShowSourceTypeModal: true,
            recordData: data
        })
    }

    loadLeftData() {
        var params = {
            params: [{
                userID: this.state.userData.userID,
                hospID: this.state.userData.hospID,
                groupID: this.state.userData.groupID,
            }]
        }
        $http.post('urlDeault', this, {
            code: "01040203",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    this.setState({
                        leftData: res.result.data
                    })
                }
            }
        });
    }

    loadRightData(page, pageSize, e) {
        var params = {
            params: [{
                userID: this.state.userData.userID,
                hospID: this.state.userData.hospID,
                groupID: this.state.userData.groupID,
                importRulesID: this.state.leftRowID
            }],
            pagination: [{
                pageSize: this.state.size == 'small' ? this.state.pageSize : PAGE_NUM_MORE_STATUS[0].code,
                currentPage: page
            }]
        }
        $http.post('urlDeault', this, {
            code: "01040206",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    this.setState({
                        dataSource: res.result.data,
                        total: res.result.totalCount,
                        page: page,
                        search: 'search'
                    })
                }
            }
        });
    }

    //点击行，渲染当前行样式
    onClickRow = (record) => {
        return {
            onClick: () => {
                this.setState({
                    leftRowID: record.id
                }, () => {
                    this.loadRightData(1)
                });
            },
        };
    }

    onClickRightRow = (record) => {
        var date = new Date()
        return {
            onClick: () => {
                if (this.state.rightRowID == record.id) {
                    this.setState({
                        rightRowID: '',
                        code: undefined,
                        descripts: undefined,
                        enDescripts: undefined,
                        note: undefined,
                        required: false,
                        type: 'String',
                        startDate: moment(date).format(dayFormat),
                        stopDate: ''
                    });
                } else {
                    this.setState({
                        rightRowID: record.id,
                        code: record.code,
                        descripts: record.descripts,
                        enDescripts: record.enDescripts,
                        note: record.note,
                        required: record.required == 'Y' ? true : false,
                        type: record.type,
                        startDate: record.startDate ? moment(record.startDate).format(dayFormat) : moment(date).format(dayFormat),
                        stopDate: record.stopDate ? moment(record.stopDate).format(dayFormat) : ''
                    });
                }
            },
        };
    }

    //点击行，渲染当前行样式
    setRowRightClassName = (record) => {
        return record.id === this.state.rightRowID ? 'clickRowStyle' : '';
    }

    //分页切换
    onChange(e) {
        this.setState({ page: e }, () => {
            this.loadRightData(e);
        });
    }

    //分页切换
    changePageSize(current, pageSize) {
        this.setState({ pageSize: pageSize, page: current }, () => {
            this.loadRightData(current, pageSize);
        });
    }


    //点击行，渲染当前行样式
    setRowClassName = (record) => {
        return record.id === this.state.leftRowID ? 'clickRowStyle' : '';
    }

    hideModal(name) {
        this.setState({
            [name]: false,
            recordData: {}
        })
    }

    //添加数据类型弹框
    showSourceType() {
        this.setState({
            isShowSourceTypeModal: true
        })
    }

    updateSourceType(data) {
        var params = {
            params: [{
                ...data,
                userID: this.state.userData.userID,
                hospID: this.state.userData.hospID,
                groupID: this.state.userData.groupID,
            }]
        }
        $http.post('urlDeault', this, {
            code: "01040201",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    message.success('操作成功！')
                    this.hideModal('isShowSourceTypeModal')
                    this.loadLeftData(1)
                }
            }
        });
    }

    //清空输入框
    cleanInput() {
        var date = new Date()
        this.props.form.resetFields();
        this.setState({
            code: undefined,
            descripts: undefined,
            enDescripts: undefined,
            required: false,
            type: 'String',
            startDate: moment(date).format(dayFormat),
            stopDate: '',
            rightRowID: ''
        })
    }

    changeDate(name, e) {
        this.setState({
            [name]: e ? moment(e).format(dayFormat) : ''
        })
    }

    onChangeSwitch(name, checked) {
        this.setState({
            [name]: checked
        })
    }

    handleSaveList() {
        let { validateFields } = this.props.form;
        validateFields({ force: true }, (err, params) => {
            if (err) {
                return;
            }
            var data = {
                params: [{
                    ...params,
                    importRulesID: this.state.leftRowID,
                    required: params.required == true ? 'Y' : 'N',
                    userID: this.state.userData.userID,
                    hospID: this.state.userData.hospID,
                    groupID: this.state.userData.groupID,
                    id: this.state.rightRowID,
                    startDate: params.startDate ? moment(params.startDate).format(dayFormat) : '',
                    stopDate: params.stopDate ? moment(params.stopDate).format(dayFormat) : '',
                }]
            }

            $http.post('urlDeault', this, {
                code: "01040204",
                data: data,
                success: function (res) {
                    if (res.errorCode == '0') {
                        this.cleanInput()
                        message.success('保存成功')
                        this.loadRightData(1)
                    }
                }
            });
        });
    }

    render() {
        let { getFieldDecorator, getFieldValue } = this.props.form;
        let formItemLayout = {
            labelCol: { span: 7 },
            wrapperCol: { span: 14 }
        };
        console.dir(this.state.dataSource)

        return (<div style={{ background: '#F1F1F1' }} className='import-config-body'>
            {/**添加数据类型 */}
            <ShowSourceTypeModal isShow={this.state.isShowSourceTypeModal}
                onSubmit={this.updateSourceType.bind(this)}
                recordData={this.state.recordData}
                onHide={this.hideModal.bind(this, 'isShowSourceTypeModal')}>
            </ShowSourceTypeModal>

            <Card style={{ height: '100%', width: '30%', float: 'left' }} title={'数据类型'} className='left-table-scroll-body'
                extra={<Button type='primary' onClick={this.showSourceType.bind(this)}><Icon type='plus' />添加数据类型</Button>}>
                <Table columns={this.leftColumns}
                    dataSource={this.state.leftData}
                    bordered
                    onRow={this.onClickRow}
                    scroll={{ x: 600, y: '79vh' }}
                    rowClassName={this.setRowClassName}
                    rowKey={(data) => {
                        return data.id
                    }}
                    pagination={false}>
                </Table>
            </Card>
            <Card style={{ height: '100%', width: '69.8%', float: 'right' }} title='列表维护'>
                <Form style={{ borderBottom: '5px solid #F1F1F1' }}>
                    <Row>
                        <Col span={7}>
                            <FormItem {...formItemLayout} label="代码">
                                {getFieldDecorator('code', {
                                    initialValue: this.state.code,
                                    rules: [{ required: true, message: '代码不能为空' }],
                                })(
                                    <Input placeholder='请输入代码' onChange={Util.commonInputChange.bind(this, 'code')} />
                                )}
                            </FormItem>
                        </Col>

                        <Col span={7}>
                            <FormItem {...formItemLayout} label="描述">
                                {getFieldDecorator('descripts', {
                                    initialValue: this.state.descripts,
                                    rules: [{ required: true, message: '描述不能为空' }],
                                })(
                                    <Input placeholder='请输入描述' onChange={Util.commonInputChange.bind(this, 'descripts')} />
                                )}
                            </FormItem>
                        </Col>

                        <Col span={7}>
                            <FormItem {...formItemLayout} label="英文描述">
                                {getFieldDecorator('enDescripts', {
                                    initialValue: this.state.enDescripts,
                                    // rules: [{ required: true, message: '英文描述不能为空' }],
                                })(
                                    <Input placeholder='请输入英文描述' onChange={Util.commonInputChange.bind(this, 'enDescripts')} />
                                )}
                            </FormItem>
                        </Col>

                        <Col span={7}>
                            <FormItem {...formItemLayout} label="类型">
                                {getFieldDecorator('type', {
                                    initialValue: this.state.type,
                                })(
                                    <Select placeholder='请选择类型' onChange={Util.handleSelectChange.bind(this, 'type')} >
                                        <Option key='1' value='String'>String</Option>
                                        <Option key='2' value='Date'>Date</Option>
                                    </Select>
                                )}
                            </FormItem>
                        </Col>

                        <Col span={7}>
                            <FormItem {...formItemLayout} label="生效日期">
                                {getFieldDecorator('startDate', {
                                    initialValue: moment(this.state.startDate, dayFormat),
                                    rules: [{ required: true, message: '生效日期不能为空' }],
                                })(
                                    <DatePicker format="YYYY-MM-DD" style={{ width: '100%' }} onChange={this.changeDate.bind(this, 'startDate')} />
                                )}
                            </FormItem>
                        </Col>

                        <Col span={7}>
                            <FormItem {...formItemLayout} label="失效日期">
                                {getFieldDecorator('stopDate', {
                                    initialValue: this.state.stopDate ? moment(this.state.stopDate, dayFormat) : ''
                                })(
                                    <DatePicker format="YYYY-MM-DD" style={{ width: '100%' }} onChange={this.changeDate.bind(this, 'stopDate')} />
                                )}
                            </FormItem>
                        </Col>

                        <Col span={7}>
                            <FormItem {...formItemLayout} label="必填">
                                {getFieldDecorator('required', {
                                    initialValue: this.state.required,
                                })(
                                    <Switch checkedChildren="是" unCheckedChildren="否" checked={this.state.required}
                                        onChange={this.onChangeSwitch.bind(this, 'required')} />
                                )}
                            </FormItem>
                        </Col>

                        <Col span={7}>
                            <Button onClick={this.cleanInput.bind(this)}>清空</Button>
                            <Button type='primary' style={{ marginLeft: 5 }} onClick={this.handleSaveList.bind(this)}>保存</Button>
                        </Col>
                    </Row>
                </Form>

                <Table columns={this.rightColumns} className='right-table-scroll-body'
                    dataSource={this.state.dataSource}
                    bordered
                    onRow={this.onClickRightRow}
                    rowClassName={this.setRowRightClassName}
                    scroll={{ y: '59vh' }}
                    rowKey={(data) => {
                        return data.id
                    }}
                    pagination={false}>
                </Table>
                <CommonPagination size={this.state.size} current={this.state.page} total={this.state.total}
                    search={this.state.search}
                    onShowSizeChange={this.changePageSize.bind(this)} complete={true} dataSource={this.state.dataSource}
                    onChange={this.onChange.bind(this)} />
            </Card>
        </div>)

    }
}

export default Form.create()(ImportConfigPage);