import React from 'react';
import { Table, Select, Pagination, Button, Input, message, Modal, Form, Switch, Row, Col, Divider, Card } from 'antd';
import { $http } from '../../../containers/config/https';
import './style/LocPropSetting.less';
import moment from 'moment';
moment.locale('zh-cn');
import store from 'store';

class FormModal extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            locPropTypeOptID: '', //参数类型默认id
        }
    }
    saveData = () => {
        this.props.form.validateFields((error, values) => {
            if (error) {

            }
            this.props.saveData(values);
        });
        this.props.cancel();
    }

    getInitialValue = (type, id) => {
        let ret = '';
        for (let key in this.props.data) {
            if (key == id) {
                ret = this.props.data[key];
            }
        }
        if (ret) {
            if (type == 'Checkbox') {
                ret = ret == 1 ? true : false;
            }
        } else {
            if (type == 'Checkbox') {
                ret = false;
            }
        }
        return ret;
    }
    render() {
        const { getFieldDecorator } = this.props.form;
        const { formList } = this.props;
        const formStype = {
            labelCol: {
                xs: { span: 9 },
                sm: { span: 10 },
                md: { span: 9 }
            },
            wrapperCol: {
                xs: { span: 15 },
                sm: { span: 14 },
                md: { span: 15 }
            },
        };
        formList.sort((a, b) => a.seqNo > b.seqNo);
        return (
            <Form layout={'horizontal'}>
                <Modal
                    visible={this.props.visible}
                    onCancel={this.props.cancel}
                    okText={'保存'}
                    onOk={this.saveData}
                    width={1000}
                >
                    <Divider />
                    <Row>
                        {formList.map((value, index) => {
                            return <Col key={value.ID} span={8}>
                                <Form.Item label={value.Descripts} {...formStype}>
                                    {value.FieldType == 'Checkbox' ? (getFieldDecorator(String(value.ID), {

                                        valuePropName: 'checked',
                                        initialValue: this.getInitialValue(value.FieldType, value.ID)
                                    })(<Switch />))
                                        :
                                        (getFieldDecorator(String(value.ID), {
                                            initialValue: this.getInitialValue(value.FieldType, value.ID)
                                        })(<Input />))
                                    }
                                </Form.Item>
                            </Col>
                        })}
                    </Row>
                </Modal>
            </Form>
        );
    }
}
const ModalForm = Form.create()(FormModal)
///科室参数设置
class LocPropSetting extends React.Component {
    constructor(props) {
        super(props);
        this.values = {};
        this.state = {
            dataSource: [],
            hbLocOpt: [],
            locPropTypeOpt: [],
            locTypeOpt: [],
            formList: [],
            key: '',
            pagination: {
                current: 1,
                pageSize: 10
            },
            columns: []
        }

    }
    addOneData = () => {
        const { dataSource, key, modifyData } = this.state;
        let { loc, propType } = this.values;
        if (key === '' && (!loc || !propType)) {
            message.error("请选择维护的行或者要添加的科室");
            return;
        }
        if (dataSource[key]) {
            loc = { id: dataSource[key].locId, desc: dataSource[key].loc }
        }
        $http.post("", this, {
            code: '02020058',
            data: { params: [{ propType: this.values.propType, loc: loc }] },
            success: function (res) {
                if (res.errorCode == 0) {
                    if (res.result.length > 0) {
                        //message.success(res.errorMessag
                        if (this.modalForm) {
                            this.modalForm.resetFields();
                        }
                        this.setState({ modalVisible: true, formList: res.result });
                    } else {
                    }
                } else {
                    message.error(res.errorMessage);
                }
            },
            error: function () {
                this.setState({ errMsg: "数据加载失败，请重试!" });
            }
        });
        // const data = { SeqNo: '', Value: '', Code: '', Descripts: '', PropType: this.values.propType, Remark: '' };
        // if (modifyData[editKey]){
        //     dataSource[editKey]=modifyData[editKey];
        // }
        // const length = dataSource.push(data);
    }
    saveData = (modifyData) => {
        let loc = {}
        if (this.state.dataSource[this.state.key]) {
            const data = this.state.dataSource[this.state.key];
            loc = { id: data.locId, desc: data.loc }
        } else {
            loc = this.values.loc;
        }
        $http.post("", this, {
            code: '02020056',
            data: { params: [{ values: { propType: this.values.propType, loc: loc }, modifyData: modifyData }] },
            success: function (res) {
                if (res.errorCode == 0) {
                    message.success(res.errorMessage)
                    if (res.result) {
                        this.setState({ dataSource: res.result });
                    }
                } else {
                }
                this.setState({ key: '' });
            },
            error: function () {
                this.setState({ errMsg: "数据加载失败，请重试!" });
            }
        });
    }
    getInitData() {
        $http.post("", this, {
            code: '02020055',
            data: { params: [] },
            success: function (res) {
                if (res.errorCode == 0) {
                    let hbLocOpt = [], locPropTypeOpt = [], locTypeOpt = []
                    if ('hbLoc' in res) {
                        this.loc = res.hbLoc;
                        res.hbLoc.map((value, key) => {
                            hbLocOpt.push(<Select.Option key={value.id} chinesesp={value.descriptsSPCode} value={value.id}>{value.descripts}</Select.Option>);
                        })
                    }
                    if ('locPropType' in res) {
                        res.locPropType.map((value, key) => {
                            locPropTypeOpt.push(<Select.Option key={value.code} chinesesp={value.chineseSP} value={value.id}>{value.descripts}</Select.Option>);
                        });
                    }
                    if ('locType' in res) {
                        res.locType.map((value, key) => {
                            locTypeOpt.push(<Select.Option key={value.code} chinesesp={value.descriptsSPCode} value={value.id}>{value.descripts}</Select.Option>);
                        });
                    }
                    this.setState({ hbLocOpt: hbLocOpt, locPropTypeOpt: locPropTypeOpt, locTypeOpt: locTypeOpt, locPropTypeOptID: res.defaultLocTypeID },()=>{
                        if(res.defaultLocTypeID){
                            this.values.propType = { id: res.defaultLocTypeID };
                            this.getPropSetting();
                        }
                    });
                }
            },
            error: function () {
                this.setState({ errMsg: "数据加载失败，请重试!" });
            }
        });
    }
    onLocChange = (value, option) => {
        if (option) {
            this.values.loc = { id: value, desc: option.props.children };
        } else {
            delete this.values.loc;
        }
        if (this.values.propType) {
            this.getPropSetting();
        }
    }
    onLocTypeChange = (value, option) => {
        let locOpt = [];
        console.log(option);
        if (this.loc && value) {
            this.loc.map((val, index) => {
                if (value == val.locTypeID) {
                    locOpt.push(<Select.Option key={val.id} chinesesp={val.descriptsSPCode} val={val.id}>{val.descripts}</Select.Option>)
                }
            });
        } else {
            this.loc.map((val, index) => {
                locOpt.push(<Select.Option key={val.id} chinesesp={val.descriptsSPCode} val={val.id}>{val.descripts}</Select.Option>)
            });
        }
        this.setState({ hbLocOpt: locOpt });
    }
    onPropTypeChange = (value, option) => {
        this.values.propType = { id: value, desc: option.props.children };
        this.getPropSetting();
    }
    locFilter = (inputValue, opt) => {
        if (opt.props.chinesesp.indexOf(inputValue.toUpperCase()) > -1) {
            return true;
        }
        if (opt.props.children.indexOf(inputValue.toUpperCase()) > -1) {
            return true;
        }
        return false;
    }
    onSearch = () => {
        this.getPropSetting();
    }
    getPropSetting() {
        $http.post("", this, {
            code: '02020057',
            data: { params: [this.values] },
            success: function (res) {
                if (res.errorCode == 0) {
                    if (res.columns.length > 0) {
                        let columns = [{
                            title: "科室",
                            key: 'loc',
                            dataIndex: 'loc',
                            width: '100px',
                            align: 'center'
                        }];
                        res.columns.sort((a, b) => a.seqNo > b.seqNo);
                        res.columns.map((value, index) => {
                            let obj = {}
                            if (value.fieldType == 'Checkbox') {
                                obj = {
                                    title: value.desc,
                                    key: value.id,
                                    dataIndex: value.id,
                                    width: '100px',
                                    align: 'center',
                                    render: (text, record) => {
                                        return <Switch disabled checked={text == 1 ? true : false} />
                                    }
                                }
                            } else {
                                obj = {
                                    title: value.desc,
                                    key: value.id,
                                    dataIndex: value.id,
                                    width: '100px',
                                    align: 'center'
                                }
                            }
                            columns.push(obj);
                        });
                        this.setState({ columns: columns });
                    }
                    if (res.result.length > 0) {
                        this.setState({ dataSource: res.result });
                    } else {
                        this.setState({ dataSource: [] });
                        message.warning("未查询到数据");
                    }
                    this.setState({ key: '' });
                }
            },
            error: function () {
                this.setState({ errMsg: "数据加载失败，请重试!" });
            }
        });
    }
    componentWillMount() {
        this.getInitData();
    }
    render() {
        const { getFieldDecorator } = this.props.form;
        const formStype = {
            labelCol: {
                xs: { span: 9 },
                sm: { span: 10 },
                md: { span: 6 }
            },
            wrapperCol: {
                xs: { span: 15 },
                sm: { span: 14 },
                md: { span: 18 }
            },
        };
        return (
            <div className={'LocPropSetting'}>
                <Card size={'small'} title='科室参数维护'>
                    <Row style={{ marginTop: '18px', marginLeft: '10px' }}>
                        <Col span={18}>
                            <Form>
                                <Row>
                                    <Col span={5}>
                                        <Form.Item label={'科室类型'} {...formStype}>
                                            {getFieldDecorator('startDate', {
                                                rules: [{
                                                    required: false,
                                                    message: '不能为空'
                                                }]
                                            })(<Select allowClear onChange={this.onLocTypeChange} style={{ width: '100%' }}>{this.state.locTypeOpt}</Select>)}
                                        </Form.Item>
                                    </Col>
                                    <Col span={6}>
                                        <Form.Item label={'科室'} {...formStype}>
                                            {getFieldDecorator('endDate', {
                                                rules: [{
                                                    required: false,
                                                    message: '不能为空'
                                                }]
                                            })(<Select allowClear onChange={this.onLocChange} showSearch filterOption={this.locFilter} style={{ width: '100%' }}>{this.state.hbLocOpt}</Select>)}
                                        </Form.Item>
                                    </Col>
                                    <Col span={7}>
                                        <Form.Item label={'参数类型'} {...formStype}>
                                            {getFieldDecorator("stockItem", {
                                                initialValue: this.state.locPropTypeOptID ? this.state.locPropTypeOptID : '',
                                                rules: [{required: true, message: '不能为空'}]
                                            })(<Select onChange={this.onPropTypeChange} style={{ width: '100%' }}>{this.state.locPropTypeOpt}</Select>)}
                                        </Form.Item>
                                    </Col>
                                </Row>
                            </Form>
                        </Col>
                        <Col span={6}>
                            <Row>
                                <Button style={{ margin: '0px 16px 16px 0px' }} onClick={this.onSearch}>查询</Button>
                                <Button type={'primary'} onClick={this.addOneData}>{this.state.key !== "" ? '修改' : '添加'}</Button>
                            </Row>
                        </Col>
                    </Row>
                </Card>
                <Card title='参数明细' size={'small'}>

                    {/** @ByYQL: 科室参数设置：单机与双击取值用的是下标index，因此不可设置分页*/}
                    {/** Create 2022-2-25*/}
                    <Table
                        bordered
                        columns={this.state.columns}
                        dataSource={this.state.dataSource}
                        style={{ height: store.getState().tableHeight.y - 18 }}
                        pagination={false}  //不分页
                        rowKey={(record, index) => index + (this.state.pagination.current - 1) * this.state.pagination.pageSize}
                        rowClassName={(record, index) => {
                            return index === this.state.key ? 'selectColor' : '';
                        }}
                        onRow={(record, index) => ({ onClick: (event) => { this.state.key !== index ? this.setState({ key: index }) : this.setState({ key: '' }) }, onDoubleClick: (event) => { this.setState({ key: index }, this.addOneData); } })}
                    />
                    <ModalForm ref={(el) => this.modalForm = el} saveData={this.saveData} data={this.state.dataSource[this.state.key] ? this.state.dataSource[this.state.key] : {}} formList={this.state.formList} visible={this.state.modalVisible} cancel={() => { this.setState({ modalVisible: false }) }} />
                </Card>
            </div>
        );
    }
}
const LocPropSettingForm = Form.create()(LocPropSetting);
export default LocPropSettingForm;
