//会诊查询
import React from 'react';
import { Card, Row, Col, Form, DatePicker, Select, Button, Tooltip, message, Pagination } from 'antd';
import { $http } from 'containers/config/https';
import PubilcTablePagination from '../../common/PubilcTablePagination.jsx'; // 公共table组件
import ColumnAuthoritysModel from '../../columnAuthority/ColumnAuthoritysModel';
import Moment from 'moment';
import { Util, dayFormat } from 'tools/index';
import RangeDatePicker from 'components/rangePicker/index';
import store from 'store';
import './index.less';

let userData ;

const { Option } = Select;
const FormItem = Form.Item;
const formItemLayout = {    // label 和input宽度
    labelCol: { span: 7 },
    wrapperCol: { span: 17 },
};
const ConsultationQuery = Form.create()(
    class extends React.Component {
        constructor(props) {
            userData = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
            super(props);
            var date = new Date()
            this.state = {
                admDateFrom: Moment(date).format(dayFormat),
                admDateTo: Moment(date).format(dayFormat),
                hospID: '',
                tableData: [], //入库单数据
                pageSize: 10,
                page: 1,
                pageSize2: 10,
                columns: [],
                total: 0,
                tableWidth: 0,
                locData: [],
                locType: "I^W",
                conStatusAry: [],
                tableType: 'C',
                locID: '',
                conApplyLocID: '',
                conStatusCode: '',
                sortColumn:'applyDate',
            }            
        }
        componentDidMount() {
            this.initDefaultValue();
        }
        //查询默认数据
        initDefaultValue = () => {
            let data = {
                params: [{
                    type:'consultQuery'
                }]
            }
            $http.post('urlDeault', this, {
                code: "04090020",
                data: data,
                success: (res) => {
                    if (+res.errorCode === 0) {
                        this.setState({
                            startDate: res.result.ConQueryStartDate,
                            stopDate: res.result.ConQueryStopDate,
                            conStatusAry: res.result.conStatusAry
                        }
                            , () => {
                                this.loadColumn();
                                this.getLocData();
                            });
                    }
                }
            })
        }

        //查询列头数据
        loadColumn = () => {
            let data = {
                params: [{
                    compontName: "ConsultationQuery",
                    type: this.state.tableType,
                }]
            }
            $http.post('urlDeault', this, {
                code: "01040073",
                data: data,
                success: (res) => {
                    if (+res.errorCode === 0) {
                        // let widthNumber = 0
                       // let resData = res.result[this.state.tableType];
                       let resData = res.result && res.result[this.state.tableType].length > 0 ? JSON.parse(JSON.stringify(res.result[this.state.tableType])).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
                        }
                    }) : '';
                        for (let index = 0; index < resData.length; index++) {
                            // widthNumber += parseInt(res.result[index].width);
                            let columnCode = resData[index].dataIndex;
                            if ((columnCode == 'conPatCondition') || (columnCode == 'admDiag') || (columnCode == 'conAims') || (columnCode == 'conItemIdea')) {
                                resData[index].onCell = () => {
                                    return {
                                        style: {
                                            maxWidth: 150,
                                            overflow: 'hidden',
                                            whiteSpace: 'nowrap',
                                            textOverflow: 'ellipsis',
                                            cursor: 'pointer'
                                        }
                                    }
                                }
                                resData[index].render = (text) => <Tooltip placement="topLeft" title={text}>{text}</Tooltip>
                            }

                        }
                        this.setState({
                            columns: resData,
                            tableWidth: res.totalWidth
                        }
                            , () => {
                                this.handleQuery();
                            })
                    }
                }
            })
        }

        // 获取科室信息
        getLocData = () => {
            let data = {
                "params": [{
                    hospID: this.state.hospID ? this.state.hospID : userData.hospID,          // 会诊医院id
                    type: 'O^OI^I^W'
                }]
            };
            $http.post('urlDeault', this, {
                code: "04020008",
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        this.setState({
                            locData: res.result.Data
                        })
                    }
                },
                error: function (error) {
                    message.error('失败：' + error);
                }
            });
        }

        handleQuery = () => {
            const formData = this.props.form.getFieldsValue();
            let data = {
                params: [{
                    hospID: userData.hospID,
                    startDate: this.state.admDateFrom ? Moment(this.state.admDateFrom).utcOffset(480).format('YYYY-MM-DD') : '',
                    stopDate: this.state.admDateTo ? Moment(this.state.admDateTo).utcOffset(480).format('YYYY-MM-DD') : '',
                    // auditStatus: this.state.conApplyLocID != "" ? this.state.auditStatus : formData.auditStatus,
                    conStatusCode: this.state.conStatusCode != "" ? this.state.conStatusCode : formData.conStatusCode,
                    locID: this.state.locID != "" ? this.state.locID : formData.locID,
                    conApplyLocID: this.state.conApplyLocID != "" ? this.state.conApplyLocID : formData.conApplyLocID,
                    // patNo: formData.patNo,
                }],
                pagination: [{
                    pageSize: this.state.pageSize,
                    currentPage: this.state.page,
                    sortColumn: this.state.sortColumn,
                    sortOrder: 'desc'
                }]
            };
            $http.post('urlS', this, {
                code: '04090018',
                data: data,
                success: (res) => {
                    // console.dir(res);
                    if (res.errorCode === "0") {
                        for (let index = 0; index < res.result.Data.length; index++) {
                            res.result.Data[index].key = index + 1;
                        }
                        this.setState({
                            total: res.result.TotalCount,
                            tableData: res.result.Data,
                        });
                    } else {
                        this.setState({
                            total: 0,
                            tableData: []
                        });
                    }
                }
            });
            this.commonChild.handleLoading();
        }

        // 提供修改page和pageSize的回调函数
        compilePage(page, pageSize) {
            // 修改page，或者pageSize
            this.setState({ page: page, pageSize: pageSize }, () => {
                // 重新调用查询方法
                this.handleQuery();
            })
        }

        // 调用公共组件的连接事件
        onRef = (ref) => {
            this.child = ref
        }
        handleOnRef = (ref) => {
            this.commonChild = ref
        }
        // 会诊状态
        handleConStatus = (code) => {
            this.setState({
                conStatusCode: code
            }, () => {
                this.handleQuery();
            })

        }
        handleConApplyLocID = (id) => {
            this.setState({ conApplyLocID: id },
                () => { this.handleQuery() });
        }

        handleLocID = (id) => {
            this.setState({ handleLocID: id },
                () => { this.handleQuery() });
        }

        startChange(date) {
            this.setState({
                admDateFrom: date,
            })
        }
    
        endChange(date) {
            this.setState({
                admDateTo: date,
            })
        }
    
        // 获取主列表columns
        getMainTableColumns = () => {
            let data = {
                params: [{
                    compontName: 'ConsultationQuery', // 接口服务
                    type: 'C',
                }]
            }
        }

        onColumnRef = (ref) => {
            this.columnRef = ref;
        }


        render() {
            var date = new Date()
            // 组件所需参数
            const param = {
                // 表头配置
                columns: this.state.columns,
                // 表格数据
                data: this.state.tableData,
                // 数据总条数
                total: this.state.total,
                // 数据页数
                page: this.state.page,
                // 表格的宽度
                x: this.state.tableWidth
            }

            const { getFieldDecorator } = this.props.form;
            return (
                <div className="WarehouseEntryCheck1">
                    <div>
                        <Row>
                            <Card
                                size="small"
                                title="会诊查询"
                                headStyle={{ background: 'rgb(66, 185, 131)' }}
                            >
                                <Col span={18}>
                                    <Form>
                                        <Row >
                                            <Col span={8}>
                                                <FormItem {...formItemLayout} label="会诊时间">
                                                    <RangeDatePicker  format='YYYY-MM-DD' style={{ width: "100%", textAlign: "center" }}
                                                        startDate={Moment(date).format(dayFormat)} endDate={Moment(date).format(dayFormat)}
                                                        startChange={this.startChange.bind(this)} endChange={this.endChange.bind(this)} 
                                                        locale={userData.language}
                                                    /> 
                                                </FormItem>
                                            </Col>
                                            <Col span={8}>
                                                <FormItem {...formItemLayout} label="申请科室">
                                                    {getFieldDecorator('conApplyLocID', {
                                                        initialValue: undefined,
                                                        rules: [{ required: false, message: '申请科室' }]
                                                    })(
                                                        <Select
                                                            allowClear
                                                            style={{ width: "100%", textAlign: "center" }}
                                                            showSearch
                                                            onChange={this.handleConApplyLocID}
                                                            optionFilterProp='role'
                                                        >
                                                            {this.state.locData.map(data => (
                                                                <Select.Option
                                                                    role={data.code + '^' + data.descripts + '^' + data.descriptsSPCode}
                                                                    key={data.id}
                                                                >{data.descripts}
                                                                </Select.Option>
                                                            )
                                                            )}
                                                        </Select>
                                                    )}
                                                </FormItem>
                                            </Col>
                                            <Col span={8}>
                                                <FormItem {...formItemLayout} label="会诊状态">
                                                    {getFieldDecorator('conStatusCode', {
                                                        initialValue: "",
                                                        rules: [{ required: false, message: '患者ID' }]
                                                    })(
                                                        <Select
                                                            allowClear
                                                            style={{ width: "100%", textAlign: "center" }}
                                                            showSearch
                                                            onChange={this.handleConStatus}
                                                            optionFilterProp='role'
                                                        >
                                                            {this.state.conStatusAry.map(data => (
                                                                <Select.Option
                                                                    role={data.code + '^' + data.descripts + '^' + data.descriptsSPCode}
                                                                    key={data.code}
                                                                >{data.descripts}
                                                                </Select.Option>
                                                            )
                                                            )}
                                                        </Select>
                                                    )}
                                                </FormItem>
                                            </Col>
                                        </Row>
                                        <Row>
                                            <Col span={8}>
                                                <FormItem {...formItemLayout} label="会诊科室">
                                                    {getFieldDecorator('locID', {
                                                        initialValue: "",
                                                        rules: [{ required: false }]
                                                    })(
                                                        <Select
                                                            allowClear
                                                            style={{ width: "100%", textAlign: "center" }}
                                                            showSearch
                                                            onChange={this.handleLocID}
                                                            optionFilterProp='role'
                                                        >
                                                            {this.state.locData.map(data => (
                                                                <Select.Option
                                                                    role={data.code + '^' + data.descripts + '^' + data.descriptsSPCode}
                                                                    key={data.id}
                                                                >{data.descripts}
                                                                </Select.Option>
                                                            )
                                                            )}
                                                        </Select>
                                                    )}
                                                </FormItem>
                                            </Col>
                                        </Row>
                                    </Form>
                                </Col>
                                <Col span={6} style={{ marginTop: '4px' }}>
                                    <Row style={{ marginBottom: '18px' }} className="button">
                                        &nbsp;&nbsp;&nbsp;&nbsp;<Button type="primary" style={{ marginRight: '30px' }}
                                            onClick={this.handleQuery}
                                        >查询</Button>
                                        <Button type="primary" style={{ marginRight: '30px' }} >导出</Button>
                                    </Row>
                                </Col>

                            </Card>
                        </Row>
                    </div>
                    <div>
                        {/* handelThis将夫组件的属性与方法给子组件访问 */}
                        <PubilcTablePagination param={param} handelThis={this} onRef={this.handleOnRef} />
                        <ColumnAuthoritysModel
                            clientWidth='800px'
                            compontName='ConsultationQuery'
                            configType="C"
                            onRef={this.onColumnRef}
                            reloadData={this.getMainTableColumns}
                        />

                    </div>
                </div>
            )
        }

    }
);
export default ConsultationQuery;