/*
 * Creator:     ML
 * CreatDate:   2019-09-18
 * descripts：  查看检验报告
 * */
import React from 'react';
import {
    Form,
    Row,
    Col,
    Input,
    Select,
    Button,
    DatePicker,
    Modal,
    Table,
    Icon,
    Pagination,
    message,
    TimePicker,
    Tooltip,
    Popover
} from 'antd';
import moment from 'moment';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';
import { $http } from '../../../containers/config/https';
import store from '../../../store';
const FormItem = Form.Item;
const Option = Select.Option;
const confirm = Modal.confirm;
const userData = sessionStorage.userData ? JSON.parse(sessionStorage.userData) : {}

const formItemLayout = { // label 和input宽度
    labelCol: { span: 6},
    wrapperCol: { span: 18 },
}
const formItemLayoutNo = { // label 和input宽度
    labelCol: { span: 6},
    wrapperCol: { span: 18 },
}

const ViewTextReport = Form.create()(
    class ViewTextReport extends React.Component {
        constructor(props) {
            super(props)
            this.state = {
                loading: false,
                visible: false,
                total: 0,//表格总数据
                consuilationData: [],//查询出来的检查报告数据
                values: {},//查询条件数据
                searchLoading:false,//查询请求
                rowIds:'',//表格行选中 页面数据
                columns:[],//检查报告表头
                widthTotal:0,//宽
                columnsVisible:false,//配置表头显隐
                page:1,
                pageSize:10,
                starNoVisible:false,
                startNoMessage:"",
            }

        }
        componentDidMount() {
            let self = this
            // 初始化设置table的高度以及表体的高度
            document.querySelector('.ant-table-body').style.height = store.getState().tableHeight.y　+ 51 + 'px';
            this.getMainTableColumns()
        }
        onColumnRef = (ref) => {
            this.columnRef = ref;
        }
        // 获取主列表columns
        getMainTableColumns = () => {
            let data = {
                params: [{
                    compontName: "ViewTextReport", // 检查报告
                    type: 'C', // 卡类型id
                }]
            }
            $http.post('urlS', this, {
                code: '01040073',
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        let arr = res.result&&res.result.C.length > 0 ? JSON.parse(JSON.stringify(res.result.C)).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,
                                render: (text, record) => {
                                    // console.log("record",record)
                                    /**
                                     * @ByYQL：住院Lis报告
                                     * Create 2021-11-23
                                     */
                                    if (item.code === "lisRptURL"){
                                        return (
                                            record.lisRptURL && record.lisRptURL != "undefined" ?
                                                <span style={{ cursor: "pointer" }}><span style={{ color: "#ffffff", background: (record.statusNormal == "Y" ? "#096dd9" : "#F6A724"), padding: "2px", borderRadius: "2px", marginRight: "2px" }}>{record.statusNormal == "Y" ? "正" : "异"}</span>
                                                <a href={record.lisRptURL} style={{color:(record.statusNormal == "Y" ? "#096dd9" : "#F6A724") }} target="_blank" rel="noopener noreferrer">{record.lisRptURL && record.lisRptURL != "undefined" ? "Lis报告查看" : ""}</a>
                                            </span> : "无报告"
                                        )
                                    }
                                    if(item.code === 'orderDescFormat'){
                                        const content = (
                                            <div>
                                                {record?.orderList && record?.orderList.length > 0 ?
                                                    record?.orderList.map((item,index) => {
                                                        return (<p>{item.ordDesc}</p>)
                                                    }) : ''  }
                                            </div>
                                        );
                                        return (
                                            <Popover content={content} title="医嘱详情：">
                                                <span style={{overflow:"hidden",whiteSpace:"nowrap",width:"100%",display:"inline-block",textOverflow:"ellipsis"}}>{record?.orderDescFormat}</span>
                                            </Popover>
                                        )
                                    }
                                    if(item.code === 'statusNormal'){
                                        return (
                                            record.lisRptURL && record.lisRptURL != "undefined" ?
                                            <span style={{color:(record.statusNormal == "Y" ? "#096dd9" : "#F6A724") }}>{record.statusNormal == "Y" ? "正常" : "异常"}</span> : ''
                                        )
                                    }
                                    return text
                                }
                            }
                        }) : '';
                        let filterArr = arr.filter(function(item){ return item.display === 'Y'});
                        this.setState({columns: filterArr, widthTotal:parseInt(res.totalWidth)+50})
                    }
                }
            })
        }
        // 修改page和pageSize 跳转至---
        onChange = (page, pageSize) => {
            this.setState({ page: page, pageSize: pageSize }, () => {
                // 重新调用查询方法
                let { values } = this.state;
                this.getFindDate(values);
            })
        }
        //下拉选择页数
        onShowSizeChange = (page, pageSize) => {
            this.setState({ page: 1, pageSize: pageSize }, () => {
                // 重新调用查询方法
                let { values } = this.state;
                if(this.state.consuilationData&&this.state.consuilationData.length>0){
                    this.getFindDate(values);
                }
            })
        }
        // 显示分页总条数
        showTotal(total) {
            return `共 ${total} 条`;
        }
        //获取查询数据
        getFindDate = (values) => {
            if(this.state.total==0){
                this.setState({
                    searchLoading:true
                })
            }
            let { page, pageSize, } = this.state;
            let data = {}
            data = {
                params: [{
                    // admID: 26351,
                    admID:sessionStorage.patientData ? JSON.parse(sessionStorage.patientData).admID:"",
                    dateFrom: values.dateFrom&&values.dateFrom ? moment(values.dateFrom).format('YYYY-MM-DD') : undefined,//开始日期
                    dateTo: values.dateTo&&values.dateTo  ? moment(values.dateTo).format('YYYY-MM-DD') : undefined,//截止日期
                }],
                pagination: [{
                    pageSize: pageSize,
                    currentPage: page,
                }]
            }
            $http.post('urlS', this, {
                code: '03060018',
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        this.setState({
                            searchLoading:false,
                            rowId:"",
                        })
                        //setLisReportUrl为拼装url函数，去除该函数时直接将res.result.data赋值即可
                        let resultData = this.setLisReportUrl(res.result.data)
                        this.setState({ consuilationData: resultData , total: res.result.totalCount&&res.result.totalCount!=undefined?res.result.totalCount:0, }, () => {
                        },)
                    } else {
                        this.setState({
                            searchLoading:false
                        })
                    }
                },
                error:function(){
                    this.setState({
                        searchLoading:false
                    })
                }
            })
        }


        /**
         * @ByYQL：Lis报告url拼装函数
         * Create 2021-11-23
         */
        setLisReportUrl = (data) => {
            let windowHost = window.location && window.location.origin ? window.location.origin : (window.location && window.location.protocol ? (window.location.protocol + '//' + window.location.hostname) : "");
            for(let i=0;i<data.length;i++){
                if(data[i].lisRptURL && data[i].lisRptURL != "undefined"){
                    data[i].lisRptURL = windowHost+"/pryklisrpt/TechReportWeb/ReportHtml/LisResult.aspx"+ data[i].lisRptURL
                }
            }
            return data
        }


        //--检查报告列表
        findData = () => {
            this.props.form.validateFields((err, values) => {
                if((values.dateFrom&&values.dateFrom)&&(values.dateTo&&values.dateTo)){
                    if(moment(values.dateFrom).format('YYYYMMDD') > moment(values.dateTo).format('YYYYMMDD')){
                        this.setState({
                            starNoVisible: true,
                            startNoMessage: "开始日期大于结束日期",
                        },()=>{
                            setTimeout(()=>{
                                this.visibleTip()
                            },1500)
                        })
                        return
                    }
                }
                if (!err) {
                    this.setState({
                        values: values,
                        rowIds:""
                    })
                    this.setState({ page: 1, pageSize: this.state.pageSize }, () => {
                        let { values } = this.state;
                        this.getFindDate(values)
                    })
                }
            })
        }
        handleCancel = () => {
            this.handleRest()
            this.setState({
                visible: false,
                bindMoreInfo:false,
                bindVail:true
            });
        }

        //点击查询后 表格行
        setRowClassNames=(record)=>{
            return record.admID === this.state.rowIds ? 'clickRowStyle' : '';
        }
        //点击Row
        onClickRow = (record) => {
            return {
                onClick: () => {
                    this.setState({
                        parms: record,
                    })
                    if (this.state.rowId === "") {
                        this.setState({
                            rowIds: record.admID,
                        });
                    } else {
                        if (this.state.rowId !== record.admID) {
                            this.setState({
                                rowIds: record.admID,
                            });
                        } else {
                            this.setState({
                                rowIds: "",
                                detailInfo: {},
                            });
                        }
                    }
                },
            };
        }
        //隐藏提示信息
        visibleTip=()=>{
            this.setState({
                starNoVisible:false,
            })
        }
        render() {
            const { getFieldDecorator } = this.props.form;
            const { baseParms,searchLoading,localArr,doctorArr,exportLoading,widthTotal,columns} = this.state;
            const mesIcon = <Icon type="exclamation-circle" />
            return (
                <div style={{ padding: '4px 2px' }} className="reportDom">
                    <Form>
                        <Row gutter={60} style={{ margin: '0' }}>
                            <Col span={7} className="starDataDom">
                                <Tooltip getPopupContainer={() => document.querySelector('.starDataDom')} overlayStyle={{ zIndex: 999, }} overlayClassName="toolTipDom starData" title={<div className="titleIcon">{mesIcon}<span >{this.state.startNoMessage}</span></div>} visible={this.state.starNoVisible}>
                                    <FormItem label='开始日期' {...formItemLayout}>
                                        {getFieldDecorator('dateFrom', {
                                            initialValue: moment(),
                                            rules: [{ required: false, message: '' }],
                                        })(
                                            <DatePicker onFocus={this.visibleTip} onChange={this.visibleTip} style={{ width: '100%' }} placeholder={'起始日期'} disabledDate={(curDate) => {
                                                return curDate && curDate > moment().endOf('day');
                                            }} />
                                        )}
                                    </FormItem>
                                </Tooltip>
                            </Col>
                            <Col span={7}>
                                <FormItem label='截止日期' {...formItemLayout}>
                                    {getFieldDecorator('dateTo', {
                                        initialValue: moment(),
                                        rules: [{ required: false, message: '' }],
                                    })(
                                        <DatePicker style={{ width: '100%' }} placeholder={'建卡日期'} disabledDate={(curDate) => {
                                            return curDate && curDate > moment().endOf('day');
                                        }} />
                                    )}
                                </FormItem>
                            </Col >
                            <Col span={2} style={{ paddingLeft: "0 !important" }}>
                                <FormItem  {...formItemLayout}>
                                    {getFieldDecorator('export', {
                                        initialValue: undefined,
                                        rules: [{ required: false, message: '' }],
                                    })(
                                        <Button onClick={this.findData} loading={searchLoading} style={{ background: 'rgba(66,185,131,1)', color: '#fff' }}>查询</Button>
                                    )}
                                </FormItem>
                            </Col>
                        </Row>

                    </Form>
                    <Table
                        scroll={{ x: (columns&&columns.length>0?widthTotal:4000), y: store.getState().tableHeight.y +　51　 }}
                        columns={columns&&columns.length>0?columns:[]}
                        dataSource={this.state.consuilationData}
                        pagination={false}
                        rowKey={record => record.key}
                        onRow={this.onClickRow}
                        rowClassName={this.setRowClassNames}
                        bordered
                        style={{ height: store.getState().tableHeight.y -180 + 'px', marginTop: '12px', }}
                    />
                    <Pagination
                        showTotal={() => this.showTotal(this.state.total)}
                        size="small"
                        showQuickJumper
                        showSizeChanger
                        defaultCurrent={1}
                        current={this.state.page ? this.state.page : 1}
                        total={this.state.total ? this.state.total : 0}
                        onChange={this.onChange}
                        onShowSizeChange={this.onShowSizeChange}
                        style={{ textAlign: "right", }}
                    />
                    <ColumnAuthoritysModel
                        clientWidth='800px'
                        compontName= 'ViewTextReport'
                        configType="C"
                        onRef={this.onColumnRef}
                        reloadData={this.getMainTableColumns}
                    />
                </div>
            )
        }
    })
export default ViewTextReport
