import React from 'react';
import { Card, Row, Col, Icon, Table, Button, Select, Input, message, Pagination, Radio } from 'antd';
import { $http } from 'containers/config/https';
import './index.less';
import ColumnAuthoritysModel from '../../columnAuthority/ColumnAuthoritysModel'
import store from 'store';
import CommonPagination from 'components/pagination/index';
const { Option } = Select;
const RadioGroup = Radio.Group;
let user;
const Search = Input.Search;
export default class NeedAtentiontable extends React.Component {
    constructor(props) {
        super(props);
        user = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
        this.state = {
            show: false,
            size: 'small',
            search: 'search',
            value: '0',
            tableType: 'C',
            locDesc: "0",	// 科室
            loc: '',//需处理
            scloc:"",//需处理类型
            loading: false,//表格loading
            DepartmentInformation: [], // 科室下拉框
            data: [],//需关注医嘱列表数据
            dataSource: [],//执行记录列表数据
            process: "",//进程号
            selectedRowKeys: [],//左边需关注医嘱勾选
            selectedRowKeys_right: [],//右边执行记录勾选
            Type: "0",// 类型
            total: 0,// 需关注医嘱分页数据
            page: 1,
            pageSize: 10,
            detailTotal: 0, // 执行记录分页数据
            page2: 1,
            pageSize2: 10,
            clickRow: {},
            admID: '',
            cardTypeList: [],
            columns: [],
            modalColumns: [],
        };

        //     this.columns = [
        //         {
        //             key: 1,
        //             title: '开始日期',
        //             dataIndex: 'ordStartDateTime',
        //             align: "center",
        //             width: '12%'
        //         },
        //         {
        //             key: 2,
        //             title: '医嘱',
        //             dataIndex: 'medDesc',
        //             align: "center",
        //             width: '12%',
        //             render: (text, record, index) => {
        //                 let arr = []
        //                 record.ordTipsAry.forEach(item =>
        //                     arr.push(<span style={{ color: item.control === 'Y' ? '#f5222d' : '#1890ff' }}> {item.descripts} </span>)
        //                 )

        //                 return (
        //                     <span>{arr}<span>{`----${text}`}</span></span>
        //                 )

        //             }
        //         },
        //         {
        //             key: 3,
        //             title: '开单科室',
        //             dataIndex: 'ordLocDesc',
        //             align: "center",
        //             width: '12%'
        //         },
        //         {
        //             key: 4,
        //             title: '接受科室',
        //             dataIndex: 'ordRecLocDesc',
        //             align: "center",
        //             width: '12%'
        //         },
        //         {
        //             key: 5,
        //             title: '开医嘱人',
        //             dataIndex: 'ordDocName',
        //             align: "center",
        //             width: '12%'
        //         }, {
        //             key: 6,
        //             title: '优先级',
        //             dataIndex: 'ordPriorityDesc',
        //             align: "center",
        //             width: '12%'
        //         },
        //         {
        //             key: 7,
        //             title: '医嘱状态',
        //             dataIndex: 'ordStatusDesc',
        //             align: "center",
        //             width: '12%'
        //         },
        //         {
        //             key: 8,
        //             title: '标本号',
        //             dataIndex: 'ordLabNo',
        //             align: "center",
        //             width: '12%'
        //         }
        //     ];
        //     this.modalColumns = [
        //         {
        //             key: 1,
        //             title: '要求执行时间',
        //             dataIndex: 'execReqDateTime',
        //             align: "center",
        //             width: '130px'
        //         },
        //         {
        //             key: 2,
        //             title: '需处理情况',
        //             dataIndex: 'execTipsAry',
        //             align: "center",
        //             width: '130px',
        //             render: (text, record, index) => {
        //                 let arr = []
        //                 record.execTipsAry.forEach(item =>
        //                     arr.push(<span style={{ color: item.control === 'Y' ? '#f5222d' : '#1890ff' }}> {item.descripts} </span>)
        //                 )

        //                 return (
        //                     <span>{arr}<span></span></span>
        //                 )

        //             }
        //         },
        //         {
        //             key: 3,
        //             title: '计费数量',
        //             dataIndex: 'execQty',
        //             align: "center",
        //             width: '130px'
        //         }, {
        //             key: 4,
        //             title: '执行时间',
        //             dataIndex: 'execDateTime',
        //             align: "center",
        //             width: '130px'
        //         },
        //         {
        //             key: 5,
        //             title: '执行状态',
        //             dataIndex: 'execStatusDesc',
        //             align: "center",
        //             width: '130px'
        //         },
        //         {
        //             key: 6,
        //             title: '执行人',
        //             dataIndex: 'execUserName',
        //             align: "center",
        //             width: '130px'
        //         },
        //         {
        //             key: 7,
        //             title: '检查部位',
        //             dataIndex: 'execPart',
        //             align: "center",
        //             width: '130px'
        //         }
        //     ];
    }
    componentDidMount() {

        this.loadColumn("Needattention")
        this.loadColumnExecution("Executionrecord")

        // 初始化设置table的高度以及表体的高度
        document.querySelector('.ant-table-body').style.height = store.getState().tableHeight.y + 'px';
        this.getDepartmentInformation('0');
        if (this.props.admID != "") {
            this.setState({ admID: this.props.admID }, () => {
                this.handleQuery(this.props.admID);
            })
        }
    }
    componentWillReceiveProps(nextProps) {
        if ((nextProps.admID != "") && (this.props.admID != nextProps.admID)) {
            this.handleQuery(nextProps.admID);
        }
    }

    //查询列头数据
    loadColumn = (compontName) => {
        let data = {
            params: [{
                compontName: compontName ? compontName : this.state.compontName,
                type: "C",
                reactCode: [compontName ? compontName : this.state.compontName]
            }]
        }
        $http.post('urlDeault', this, {
            code: "01040073",
            data: data,
            success: (res) => {
                if (res.errorCode == 0) {
                    let column = res.result.C;
                    if (user.language == 'EN') {
                        for (let i = 0; i < column.length; i++) {
                            column[i].title = column[i].enDescripts
                        }
                    }
                    for (let i = 0; i < column.length; i++) {
                        column[i].key = column[i].id
                        if (column[i].code == 'medDesc'){
                            column[i].render = (text, record, index) => {
                                let data = []
                                record.ordTipsAry.forEach(item =>
                                    data.push(<span style={{ color: item.control === 'Y' ? '#f5222d' : '#1890ff' }}> {item.descripts} </span>)
                                )        
                                return (
                                    <span>{data}<span>{`----${text}`}</span></span>
                                )        
                            }
                        }
                    }
                    let arr = Object.keys(res.result.language.EN);
                    if (arr.length > 0) {
                        this.setState({
                            [(compontName ? compontName : this.state.compontName) + "Column"]: res.result.C,
                            ENObj: res.result.language.EN,
                            CNObj: res.result.language.CN
                        })
                    } else {
                        this.setState({
                            [(compontName ? compontName : this.state.compontName) + "Column"]: res.result.C,
                        })
                    } 
                    if (+res.errorCode === 0) {
                        let resData = res.result[this.state.tableType];
                        this.setState({
                            columns: resData,
                            tableWidth: res.totalWidth
                        })
                    }

                }
            }
        })
    }

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

    //查询列头数据
    loadColumnExecution = (compontName) => {
        let data = {
            params: [{
                compontName: compontName ? compontName : this.state.compontName,
                type: "C",
                reactCode: [compontName ? compontName : this.state.compontName]
            }]
        }
        $http.post('urlDeault', this, {
            code: "01040073",
            data: data,
            success: (res) => {
                if (res.errorCode == 0) {
                    let column = res.result.C;
                    if (user.language == 'EN') {
                        for (let i = 0; i < column.length; i++) {
                            column[i].title = column[i].enDescripts
                        }
                    }
                    for (let i = 0; i < column.length; i++) {
                        column[i].key = column[i].id
                        if (column[i].code == 'execTipsAry'){
                            column[i].render = (text, record, index) => {
                                let arr = []
                                record.execTipsAry.forEach(item =>
                                    arr.push(<span style={{ color: item.control === 'Y' ? '#f5222d' : '#1890ff' }}> {item.descripts} </span>)
                                )        
                                return (
                                    <span>{arr}<span></span></span>
                                )        
                            }
                        }
                    }
                    var arr = Object.keys(res.result.language.EN);
                    if (arr.length > 0) {
                        this.setState({
                            [(compontName ? compontName : this.state.compontName) + "Column"]: res.result.C,
                            ENObj: res.result.language.EN,
                            CNObj: res.result.language.CN
                        })
                    } else {
                        this.setState({
                            [(compontName ? compontName : this.state.compontName) + "Column"]: res.result.C,
                        })
                    } if (+res.errorCode === 0) {
                        let resData = res.result[this.state.tableType];
                        this.setState({
                            modalColumns: resData,
                            tableWidth: res.totalWidth
                        }
                            , () => {
                                //  this.handleQuery(); 
                            })
                    }

                }
            }
        })
    }

    // 查询条件 --- 科室
    onChangeLocDesc = (e) => {
        this.setState({ locDesc: e });
    }
    // 查询条件 --- 需处理
    onChangeLoc = (e) => {
        this.setState({ loc: e });
    }

    changeLoc= (e) => {
        this.setState({ scloc: e });
    }



    // 查询条件 ---  类型
    onChangeType = (e) => {
        this.setState({ Type: e }, () => {
            this.getDepartmentInformation(e);
        });
    }
    // 获取需处理下拉框信息
    getDepartmentInformation(type) {
        let data = {
            params: [
                {
                    hospID: user.hospID,
                    deptType: "N",
                    concernType: type,
                    power: "select"
                }
            ]
        }
        $http.post('urlS', this, {
            code: "04050006",
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    this.setState({ DepartmentInformation: res.result.Data })
                } else {
                    this.setState({ DepartmentInformation: [] })
                }
            }
        })
    }


    //查询需关注医嘱列表
    handleQuery = (admID, e) => {
        let locDesc = this.state.locDesc;//0:全部，1：本科室，2：其他科室
        let { page, pageSize,loc, value, Type } = this.state;
        if (e == null || e != "pageChange") {
            page = 1
            this.setState({
                page: 1,
            })
        }
        let data = {
            params: [{
                locDesc: locDesc,
                userID: user.userID,
                hospID: user.hospID, //医院主键
                admID: admID ? admID : this.props.admID,//患者就诊号
                locID: user.locID,//科室主键
                deptType: "N",//医护人员类型
                concernType: Type,//需关注类型
                concernID:loc,//需关注详细项目主键
                ordPriorityID: value,//医嘱优先级
            }],
            pagination: [{
                pageSize: pageSize,
                currentPage: page,
                sortColumn: 'code',
                sortOrder: 'asc'
            }]
        }
        $http.post('urlS', this, {
            code: "04050005",
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    this.setState({ data: res.result.needCareAry, total: parseInt(res.result.TotalCount), loading: false })
                }
            }
        })
    }
    handlEexecutionQuery = () => {
        let { page2, pageSize2 } = this.state;
        let data = {
            params: [{
                process: this.state.clickRow.process,//进程号
                ordID: this.state.clickRow.ordID,//医嘱ID
                concernID: this.state.scloc,//需关注详细项目主键
            }],
            pagination: [{
                pageSize: pageSize2,
                currentPage: page2,
                sortColumn: 'code',
                sortOrder: 'asc'
            }]
        }
        $http.post('urlS', this, {
            code: "04050007",
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    this.setState({
                        dataSource: res.result.Data,
                        detailTotal: parseInt(res.result.TotalCount),
                        loading: false
                    })
                } else {
                    message.error('查询失败：' + res.errorMessage);
                }
            }
        })

    }


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

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



    onChange1 = e => {
        this.setState({
            value: e.target.value,
        }, () => {
            this.handleQuery("");
        });
    };

    onChange(e, pageSize) {
        this.setState({ page: e, pageSize: pageSize }, () => {
            this.handleQuery("", "pageChange");
        });
    }

    //分页切换
    changePageSize(page, pageSize) {
        this.setState({ page: 1, pageSize: pageSize }, () => {
            this.handleQuery("", "pageChange");
        });
    }
    // // 页码改变的回调，参数是改变后的页码及每页条数 需关注医嘱
    // onChange = (page, pageSize) => {
    //     this.setState({ page: page, pageSize: pageSize }, () => {
    //         // 重新调用查询方法
    //         this.handleQuery("", "pageChange");
    //     });
    // };

    // onShowSizeChange = (current, size) => {
    //     this.setState({ page: 1, pageSize: size }, () => {
    //         // 重新调用查询方法
    //         this.handleQuery("", "pageChange");
    //     })
    // };

    // 页码改变的回调，参数是改变后的页码及每页条数 执行记录
    onChange2 = (page, pageSize) => {
        this.setState({ page2: page, pageSize2: pageSize }, () => {
            // 重新调用查询方法
            this.handlEexecutionQuery();
        });
    };

    onShowSizeChange2 = (current, size) => {
        this.setState({ page2: 1, pageSize2: size }, () => {
            // 重新调用查询方法
            this.handlEexecutionQuery();
        })
    };
    // 显示分页总条数
    showTotal(total) {
        return `共 ${total} 条`;
    }
    packUpHandle = () => {
        this.setState({ show: !this.state.show, span: 24 })
    };
    render() {

        const cardType = [];
        this.state.cardTypeList.map((item) => {
            cardType.push(
                <Option key={item.id} value={item.id} cardlength={item.cardLength}>
                    {user.language == 'CN' ? item.descripts : item.enDescripts}
                </Option>
            )
        })

        var language = user.language;
        var languageObj = {}
        if (language == "EN") {
            languageObj = this.state.ENObj
        } else {
            languageObj = this.state.CNObj
        }


        return (
                <div className='detail1'>
                    <Row>
                        <Col span={17} style={{height:'100%'}} >
                            <Card
                                size="small"
                                title="需关注医嘱"
                                headStyle={{ background: 'rgb(66, 185, 131)' }}
                            >
                                <div style={{ height: store.getState().tableHeight.y - 56 + 'px', overflow: 'auto' }} className="detail-left" style={{ height: '95%' }}>
                                    <Row>

                                        <Col span={24} style={{ paddingRight: '10px' }}>
                                            <RadioGroup onChange={this.onChange1} value={this.state.value}>
                                                <Radio value="0">{languageObj && languageObj.NeedattentionAll != null ? languageObj.NeedattentionAll.descripts : ""}</Radio>
                                                <Radio value="1">{languageObj && languageObj.NeedattentionLong != null ? languageObj.NeedattentionLong.descripts : ""}</Radio>
                                                <Radio value="2">{languageObj && languageObj.Needattentiontemporary != null ? languageObj.Needattentiontemporary.descripts : ""}</Radio>
                                            </RadioGroup>
                                            
                                            {languageObj && languageObj.NeedattentionType != null ? languageObj.NeedattentionType.descripts : ""}：<Select showSearch optionFilterProp="title" allowClear value={this.state.Type} onChange={this.onChangeType} style={{ width: '150px', margin: '23px 15px 0 0' }} placeholder="请选择">
                                                <Option value="0">全部</Option>
                                                <Option value="T">转科</Option>
                                                <Option value="D">出院</Option>
                                            </Select>
                                            {languageObj && languageObj.NeedattentionTobeprocessed != null ? languageObj.NeedattentionTobeprocessed.descripts : ""}：<Select showSearch optionFilterProp="title" allowClear value={this.state.loc} onChange={this.onChangeLoc} style={{ width: '150px', margin: '23px 15px 0 0' }} placeholder="请选择">
                                                {this.state.DepartmentInformation && this.state.DepartmentInformation.map(item => {
                                                    return <Option key={item.id} value={item.id} title={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>
                                                })}
                                            </Select>
                                            {languageObj && languageObj.NeedattentionDepartment != null ? languageObj.NeedattentionDepartment.descripts : ""}：<Select showSearch optionFilterProp="title" allowClear value={this.state.locDesc} onChange={this.onChangeLocDesc.bind(this)} style={{ width: '150px', margin: '23px 15px 0 0' }} placeholder="请选择科室">
                                                <Option value="0">全部</Option>
                                                <Option value="1">本科室</Option>
                                                <Option value="2">其他科室</Option>
                                            </Select>
                                            <Button onClick={this.handleQuery.bind(this, "")} style={{ margin: '23px 15px 20px 0', background: 'rgba(255,255,255,1)' }}>{languageObj && languageObj.NeedattentionQuery != null ? languageObj.NeedattentionQuery.descripts : ""}</Button>

                                        </Col>
                                        <Col span={24} style={{height: 'calc(100% - 45px)'}}>
                                            <div style={{ paddingLeft: '24px' }}>
                                                {/* <Button type="primary">处理</Button>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                                <Button type="primary">执行</Button>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                                <Button type="primary">领药审核</Button> */}
                                                <span style={{ float: 'right', fontSize: '14px', paddingTop: '8px', color: '#1890ff' }}>蓝色为提示项目，<span style={{ color: '#f5222d' }}>红色为控制项目</span></span>
                                            </div>
                                            <br />

                                            <ColumnAuthoritysModel
                                                clientWidth='800px'
                                                compontName={this.state.compontName}
                                                configType="C"
                                                visible={this.state.visible}
                                                onRef={this.onColumnRef}
                                                reloadData={this.loadColumn}
                                            />
                                        <div style={{ width: '100%', height: '100%', overflow: 'hidden' }}>
                                            <div style={{ width: '100%', height: 'calc(100% - 60px)', overflow: 'hidden' }} className='coursetable'>
                                            <Table
                                                style={{ width: '100%',"padding": "5px",height: '100%' }}
                                                dataSource={this.state.data}
                                                columns={this.state.columns}
                                                pagination={false}
                                                rowKey={(row) => {
                                                    return row.ordID
                                                }}
                                                //单击事件 
                                                onHeaderRow={column => {
                                                    return {
                                                        onDoubleClick: () => {
                                                            this.setState({
                                                                compontName: "Needattention",
                                                            }, () => {
                                                                this.columnRef.onOpenModel();
                                                            })

                                                        }
                                                    };
                                                }
                                                }
                                                onRow={this.onClickRow}
                                                rowClassName={this.setRowClassName}
                                                loading={this.state.loading}
                                                // rowSelection={rowSelection} 
                                                scroll={{ y: 'calc(100% - 46px)', x: this.state.tableWidth }}
                                                bordered

                                            />
                                            </div>
                                                <div style={{ width: '100%', height: '45px', overflow: 'hidden' }}>
                                                    {/* 分页: total--总条数  defaultCurrent--默认的当前页 hideOnSinglePage--只有一页时隐藏分页器 */}
                                                    <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.data}
                                                        loading={this.state.loading} onChange={this.onChange.bind(this)} />
                                                </div>
                                            </div>
                                        </Col>
                                    </Row>
                                </div>
                            </Card>
                        </Col>
                        <Col span={this.state.show ? 24 : 7} style={{height:'100%'}}>
                            <Card
                                size="small"
                                title={<span><Icon onClick={this.packUpHandle} type={this.state.show ? 'double-right' : 'double-left'} />执行记录</span>}
                                headStyle={{ background: 'rgb(66, 185, 131)' }}

                            >
                                <div style={{height: '100%',overflow: 'hidden'}} className="needExecute" >
                                    <Row style={{height:'75px'}}>
                                        <Col span={24} style={{ paddingRight: '10px' }}>
                                        {languageObj && languageObj.NeedattentionTypetobeprocessed != null ? languageObj.NeedattentionTypetobeprocessed.descripts : ""}：<Select showSearch optionFilterProp="title" allowClear value={this.state.scloc} onChange={this.changeLoc} style={{ width: '150px', margin: '23px 15px 0 0' }} placeholder="请选择">
                                                {this.state.DepartmentInformation && this.state.DepartmentInformation.map(item => {
                                                    return <Option key={item.id} value={item.id} title={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>
                                                })}
                                            </Select>

                                            <Button onClick={this.handlEexecutionQuery} style={{ margin: '23px 15px 20px 0', background: 'rgba(255,255,255,1)' }}>{languageObj && languageObj.NeedattentionQuery != null ? languageObj.NeedattentionQuery.descripts : ""}</Button>

                                        </Col>
                                        <Col span={24}>
                                            <div>
                                                {/* <Button type="primary">执行</Button>&nbsp;&nbsp;&nbsp;&nbsp;
                                                    <Button type="primary">领药审核</Button>&nbsp;&nbsp;&nbsp;&nbsp;
                                                    <Button type="primary">停止执行</Button>&nbsp;&nbsp;&nbsp;&nbsp;
                                                    <Button type="primary">撤销执行</Button> */}
                                            </div>
                                            <br />
                                        </Col>
                                    </Row>
                                    <ColumnAuthoritysModel
                                        clientWidth='800px'
                                        compontName={this.state.compontName}
                                        configType="C"
                                        visible={this.state.visible}
                                        onRef={this.onColumnRef}
                                        reloadData={this.loadColumnExecution}
                                    />
                                    <Table
                                        style={{ 
                                            height: 'calc(100% - 144px)',
                                            marginBottom: '28px',
                                         }}
                                         
                                        dataSource={this.state.dataSource}
                                        columns={this.state.modalColumns}
                                        pagination={false}
                                        rowKey={(row) => {
                                            return row.execID
                                        }}
                                        //单击事件 
                                        onHeaderRow={column => {
                                            return {
                                                onDoubleClick: () => {
                                                    this.setState({
                                                        //Needattention\Executionrecord
                                                        compontName: "Executionrecord",
                                                    }, () => {
                                                        this.columnRef.onOpenModel();
                                                    })

                                                }
                                            };
                                        }
                                        }
                                        // rowSelection={rowSelection_right} 
                                        scroll={{ y: 'calc(100% - 50px)', x: this.state.tableWidth }}
                                        bordered
                                    />
                                    {/* 分页: total--总条数  defaultCurrent--默认的当前页 hideOnSinglePage--只有一页时隐藏分页器 */}
                                    <CommonPagination size={this.state.size} current={this.state.page2} total={this.state.detailTotal} search={this.state.search}
                                        onShowSizeChange={this.onShowSizeChange2.bind(this)} complete={false} dataSource={this.state.dataSource}
                                        loading={this.state.loading} onChange={this.onChange2.bind(this)} style={{marginTop: '23px',}}/>
                                    {/* <CommonPagination size={this.state.size}  current={this.state.page2} total={this.state.detailTotal} search='search'
                                        onShowSizeChange={this.onShowSizeChange2.bind(this)} complete={true} dataSource={this.state.dataSource}
                                        onChange={this.onChange2.bind(this)} /> */}
                                </div>
                            </Card>
                        </Col>
                    </Row>
                </div>
        )

    }
}