//打印医嘱子项类设置配置
import React from 'react';
import { Table, Popconfirm, Icon, message, DatePicker, Input, Modal, Form, Divider, Select, Row, Col, Button } from 'antd';
import { $http } from '../../containers/config/https';
import moment from 'moment';
import store from '../../store';
import CommonPagination from 'components/pagination/index';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';


const { Option } = Select;
const dateFormat = 'YYYY-MM-DD'; //定义全局日期格式
const formItemLayout = {    // label 和input宽度
    labelCol: { span: 8 },
    wrapperCol: { span: 14, offset: 2 },
};

class OPHBPrintOrdCatSub extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            loading: false, //加载状态标志
            visible: false, //弹窗显示状态标志
            total: 0,  // 表格数据总条数
            page: 1, //当前页数
            pageSize: 10, //每页显示条数
            updateID: '', //修改表单ID
            modalState: '', //弹窗点击提交时判断是否修改或增加标志
            motalTitle: '', //弹窗标题
            startValue: null, //日期选择器开始时间
            endValue: null, //日期选择器结束时间

            tableData: [], // 表格数据
            columns: [], //表格列表
            languageTable1: {}, // 国际化Table1
            languageTable2: {}, // 国际化Table2
            languageData: {}, // 国际化语言包
            language: {},   // 国际化语言
            languageCode: JSON.parse(window.sessionStorage.userData).language, // 国际化语言标识

            delPrintOrdCatSubID: '', //删除ID
            subArr: [], //医嘱子类下拉框数据
            hospData: [], //医院下拉框数据
            selectHosp: '', //查询条件 --- 医院
            selectOrdSub: '', //查询条件 --- 医嘱子类
            startDateSelect: null, //查询条件 --- 生效日期
            endDateSelect: null, //查询条件 --- 失效日期
        };
    }

    componentDidMount() {
        this.tableList();
        //初始化列表数据
        this.handleQuery();
        //医嘱类子项下拉框
        this.getOrderSubCatData();
        //获取医院下拉框数据
        this.getHospData();
    }
    //render 自定义项目名称
    listAdd = (i, j, languageCode) => {
        let { columns } = this.state
        columns.splice(i, j,
            {
                title: languageCode === 'CN' ? "操作" : 'Operation',
                key: 'op',
                align: "center",
                render: (text, record) => (
                    <span>
                        <span className='span' onClick={() => this.showModal(record)}><Icon type="edit" />{languageCode === 'CN' ? "修改" : 'Alter'}</span>
                        <Divider type="vertical" />
                        <Popconfirm
                            title={languageCode === 'CN' ? "确定要删除吗?" : 'You sure you want to delete it?'}
                            onConfirm={this.delConfirm}
                            okText={languageCode === 'CN' ? "是" : 'Yes'}
                            cancelText={languageCode === 'CN' ? "否" : 'No'}
                        >
                            <span style={{ color: '#f00' }} className='span' onClick={() => this.setState({ delPrintOrdCatSubID: record.ID })}><Icon type="delete" />删除</span>
                        </Popconfirm>
                    </span>
                ),
            },
        )
    }
    onColumnRef = (ref) => {
        console.log(ref)
        this.columnRef = ref;
    }
    // 获取主列表columns
    tableList = () => {
        var data = {
            params: [{
                "reactCode": ["HBPrintOrdCatSub"],
                "compontName": "HBPrintOrdCatSub",
                "type": "C"
            }]
        }
        console.log(1, data)
        $http.post('urlS', this, {
            code: '01040073',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    let resC = res.result.C
                    let { languageCode } = this.state
                    for (var i = 0; i < resC.length; i++) {
                        resC[i].key = i;
                    }
                    if (languageCode === "EN") {
                        resC.map((item, i) => {
                            item.title = item.enDescripts
                        })
                    }

                    if (languageCode === "CN") {
                        resC.map((item, i) => {
                            item.title = item.descripts
                        })
                    }
                    let arr = res.result && resC.length > 0 ? JSON.parse(JSON.stringify(resC)).map(item => {
                        return {
                            align: item.align,
                            widthNum: parseInt(item.width),
                            width: item.width,
                            dataIndex: item.dataIndex,
                            title: <div onDoubleClick={() => this.columnRef.onOpenModel()}>{item.title}</div>,
                            display: item.display,
                            key: item.seqNo
                        }
                    }) : '';
                    let filterArr = arr.filter(function (item) { return item.display === 'Y' });
                    this.setState({
                        columns: filterArr,
                        languageTable1: res.result.B || {},  // 国际化Table1
                        languageTable2: res.result.C || {},  // 国际化Table2
                        languageData: res.result.language || {},  // 国际化语言包
                    }, () => {
                        this.LanCNEN(this.state.languageCode)
                        this.listAdd(filterArr.length + 1, 0, languageCode);
                    })
                }
            }
        })
    }

    LanCNEN = (code) => {
        let { languageData } = this.state
        this.setState({
            language: languageData[code]
        })
    }

    //开始日期选择器选择限制
    disabledStartDate = startValue => {
        const { endValue } = this.state;
        if (!startValue || !endValue) {
            return false;
        }
        return startValue.valueOf() > endValue.valueOf();
    };

    //失效日期选择器选择限制
    disabledEndDate = endValue => {
        const { startValue } = this.state;
        if (!endValue || !startValue) {
            return false;
        }
        return endValue.valueOf() <= startValue.valueOf();
    };

    onChange = (field, value) => {
        this.setState({
            [field]: value,
        });
    };

    //开始日期变化
    onStartChange = value => {
        this.onChange('startValue', value);
    };

    //结束日期变化
    onEndChange = value => {
        this.onChange('endValue', value);
    };

    //初始化列表数据
    handleQuery = () => {
        let { page, pageSize, selectHosp, selectOrdSub, startDateSelect, endDateSelect } = this.state;
        let data = {}
        data = {
            params: [{
                hospID: selectHosp,
                startDate: startDateSelect,
                endDate: endDateSelect,
                ordCatSub: selectOrdSub
            }],
            pagination: [{
                pageSize: pageSize,
                currentPage: page,
                sortColumn: 'code',
                sortOrder: 'asc'
            }]
        }
        $http.post('urlS', this, {
            code: '05100286',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0 && res.result) {
                    for (var i = 0; i < res.result.length; i++) {
                        res.result[i].key = i;
                    }
                    this.setState({ tableData: res.result.Data, total: res.result.TotalCount, loading: false })
                } else {
                    this.setState({ tableData: [], total: 0, loading: false })
                }
            }
        })
    }

    //医嘱子类下拉框数据
    getOrderSubCatData = () => {
        let data = {
            params: [{

            }],
        }
        let subArr = []
        $http.post('urlS', this, {
            code: '05100173',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    for (var i = 0; i < res.data.length; i++) {
                        subArr.push(<Option value={String(res.data[i].id)} key={i + "S"} >{res.data[i].descripts}</Option>)
                    }
                    this.setState({subArr: subArr})
                }
            }
        })
    }

    //医院下拉框数据
    getHospData = () => {
        var data = {
            params: [{
                logonGroupID: JSON.parse(window.sessionStorage.userData).groupID,
                logonHospID: JSON.parse(window.sessionStorage.userData).hospID,
                dataType: "combo",
            }]
        }
        let hospital = []
        $http.post("urlS", this, {
            code: '05100046',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0 && res.Hosp) {
                    for (var i = 0; i < res.Hosp.length; i++) {
                        hospital.push(<Option value={String(res.Hosp[i].id)} key={i + "H"} >{res.Hosp[i].descripts}</Option>)
                    }
                    this.setState({ hospData: hospital })
                }
            },
            error: function (err) {
                this.setState({ errMsg: "数据加载失败，请重试！" })
            }
        })
    }

    //删除确认
    delConfirm = (e) => {
        this.handleDel();
    }

    //弹窗显示
    showModal = (params) => {
        if (params === 'add') {
            this.setState({
                modalState: 'add',
                visible: true,
                motalTitle: "新增",
                startValue: null,
                endValue: null,
                updateID: '',
            });
            this.props.form.setFieldsValue({
                'Hosp': JSON.parse(window.sessionStorage.userData).hospID,
                'OrdSubCat': '',
                'StartDate': undefined,
                'EndDate': undefined,
            });
        } else {
            this.setState({
                modalState: 'update',
                updateID: params.ID,
                visible: true,
                motalTitle: "修改",
                startValue: moment(params.StartDate, 'YYYY-MM-DD'),
                endValue: params.EndDate ? moment(params.EndDate, 'YYYY-MM-DD') : null,
            });
            this.props.form.setFieldsValue({
                'Hosp': params.hospID,
                'OrdSubCat': params.ordCatSubID,
                'StartDate': moment(params.startDate, 'YYYY-MM-DD'),
                'EndDate': params.endDate ? moment(params.endDate, 'YYYY-MM-DD') : undefined,
            });
        }
    };

    //弹窗点击确定
    handleOk = () => {
        this.props.form.validateFields((err, values) => {
            if (err) {
                return;
            }
            let data = {
                params: [{
                    ID: this.state.updateID,
                    userID: JSON.parse(window.sessionStorage.userData).userID,
                    hospID: values.Hosp,
                    ordCatSubID: values.OrdSubCat,
                    startDate: moment(values.StartDate).utcOffset(480).format('YYYY-MM-DD'),
                    endDate: values.EndDate ? moment(values.EndDate).utcOffset(480).format('YYYY-MM-DD') : '',
                }]
            }
            $http.post('urlS', this, {
                code: '05100287',
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        message.success(res.errorMessage);
                        this.handleQuery();
                        this.setState({ loading: false, visible: false });
                    }
                }
            })
        })
    };

    //弹窗点击取消
    handleCancel = () => {
        this.setState({ visible: false, });
    };

    //删除操作
    handleDel = () => {
        let data = {
            params: [{
                HBPrintOrdCatSubID: this.state.delPrintOrdCatSubID,
                userID: JSON.parse(window.sessionStorage.userData).userID,
            }]
        };
        $http.post('urlS', this, {
            code: "05100288",
            data: data,
            success: function (res) {
                let errorCode = res.errorCode;
                if (errorCode === '0') {
                    message.success(res.errorMessage);
                    this.handleQuery() // 查询
                }
            }
        });
    }

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

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

    //医院 --- 查询条件
    onChangeHospSelect = (e) => {
        this.setState({ selectHosp: e });
    }

    //医嘱子类 --- 查询条件
    onChangeOrdSubSelect = (e) => {
        this.setState({ selectOrdSub: e.target.value });
    }

    //生效日期 --- 查询条件
    onStartChangeSelect = time => {
        this.setState({ startDateSelect: time ? moment(time).utcOffset(480).format('YYYY-MM-DD') : '' })
    }

    //失效日期 --- 查询条件
    onEndChangeSelect = time => {
        this.setState({ endDateSelect: time ? moment(time).utcOffset(480).format('YYYY-MM-DD') : '' })
    }

    render() {
        let { hospData, startValue, endValue, subArr, language, languageCode } = this.state;
        // 医院
        const { getFieldDecorator } = this.props.form;
        return (
            <div>
                <div style={{ width: '100%', height: '100%' }}>
                    <Row style={{ minHeight: '80px', padding: '24px 24px 24px 24px' }}>
                        <Col span={4}>
                            <span>医院：</span>
                            <Select style={{ width: '150px' }} allowClear placeholder="请选择医院" onChange={this.onChangeHospSelect} >
                                {hospData}
                            </Select>
                        </Col>
                        <Col span={4}>
                            <span>医嘱子类：</span>
                            <Input
                                placeholder="请输入医嘱子类"
                                onChange={this.onChangeOrdSubSelect}
                                style={{ width: '150px' }}
                            />
                        </Col>
                        <Col span={4}>
                            <span>生效日期：</span>
                            <DatePicker onChange={this.onStartChangeSelect} format={dateFormat} />
                        </Col>
                        <Col span={4}>
                            <span>失效日期：</span>
                            <DatePicker onChange={this.onEndChangeSelect} format={dateFormat} />
                        </Col>
                        <Col span={3} style={{ textAlign: 'right' }}>
                            <Button type="primary" onClick={() => this.handleQuery()} icon="search" >查询</Button>
                        </Col>
                        <Col span={3} style={{ textAlign: 'center' }}>
                            <Button type="primary" onClick={() => this.showModal('add')} icon="plus" style={{ background: '#F7805D', color: '#FFFFFF', borderColor: '#F7805D' }} >
                                新增
                            </Button>
                            <Form layout="inline">
                                <Modal
                                    visible={this.state.visible}
                                    title={this.state.motalTitle}
                                    onOk={() => this.handleOk(this.state.modalState)}
                                    onCancel={this.handleCancel}
                                    width='600px'
                                    footer={[
                                        <Button key="back" onClick={this.handleCancel}>
                                            取消
                                        </Button>,
                                        <Button key="submit" type="primary" loading={this.state.loading} onClick={this.handleOk}>
                                            确定
                                        </Button>,
                                    ]}
                                >
                                    <Row>
                                        <Col span={24}>
                                            <Form.Item label="医院" {...formItemLayout} >
                                                {getFieldDecorator("Hosp", {
                                                    initialValue: '',
                                                    rules: [{ required: true, message: "医院不能为空" }]
                                                })(
                                                    <Select style={{ width: '150px' }} allowClear placeholder="请选择医院" >
                                                        {hospData}
                                                    </Select>
                                                )}
                                            </Form.Item>
                                        </Col>
                                        <Col span={24}>
                                            <Form.Item label="医嘱子类" {...formItemLayout}>
                                                {getFieldDecorator("OrdSubCat", {
                                                    initialValue: null,
                                                    rules: [{ required: true, message: "医嘱子类不能为空" }]
                                                })(
                                                    <Select style={{ width: '150px' }} allowClear placeholder="请选择医嘱子类" >
                                                        {subArr}
                                                    </Select>
                                                )}
                                            </Form.Item>
                                        </Col>
                                        <Col span={24}>
                                            <Form.Item label="生效日期" {...formItemLayout}>
                                                {getFieldDecorator("StartDate", {
                                                    initialValue: startValue,
                                                    rules: [{ required: true, message: "生效日期不能为空" }]
                                                })(
                                                    <DatePicker
                                                        format={dateFormat}
                                                        disabledDate={this.disabledStartDate}
                                                        // value={startValue}
                                                        onChange={this.onStartChange}
                                                    />
                                                )}
                                            </Form.Item>
                                        </Col>
                                        <Col span={24}>
                                            <Form.Item label="失效日期" {...formItemLayout}>
                                                {getFieldDecorator("EndDate", {
                                                    initialValue: endValue,
                                                })(
                                                    <DatePicker
                                                        format={dateFormat}
                                                        disabledDate={this.disabledEndDate}
                                                        //value={endValue}
                                                        onChange={this.onEndChange}
                                                    />
                                                )}
                                            </Form.Item>
                                        </Col>
                                    </Row>
                                </Modal>
                            </Form>
                        </Col>
                    </Row>
                </div>
                <div style={{ widht: '100%', height: '10px', background: '#f0f2f5' }}></div>
                <div style={{ padding: 24 }}>
                    <Table
                        style={{ height: store.getState().tableHeight.y + 65 + 'px' }}
                        dataSource={this.state.tableData}
                        columns={this.state.columns}
                        className='TableA'
                        //rowClassName="editable-row"
                        pagination={false}
                        scroll={{ x: 900, y: store.getState().tableHeight.y }}
                        bordered
                        loading={this.state.loading}
                    />
                    <CommonPagination size="small" current={this.state.page} total={this.state.total} search='search'
                        onShowSizeChange={this.apponShowSizeChange} complete={true} dataSource={this.state.tableData}
                        onChange={this.appPageChange} />
                    <ColumnAuthoritysModel
                        clientWidth='800px'
                        compontName='HBPrintOrdCatSub'
                        configType="C"
                        onRef={this.onColumnRef}
                        reloadData={this.tableList}
                    />
                </div>
            </div>
        )
    }
}


const OPHBPrintOrdCatSubForm = Form.create()(OPHBPrintOrdCatSub);
export default OPHBPrintOrdCatSubForm;
