/**
 * 
 * 医嘱编辑权限设置
 */
import React from 'react';
import {
    Card, Table, Input, Form, Select, Row, Col, Checkbox, Tabs,
    DatePicker, Button, Pagination, Icon, Divider, message, Modal,
} from 'antd';
import { Util, dayFormat } from 'tools/index';
import { $http } from 'containers/config/https';
import CommonPagination from 'components/pagination/index';
import { PAGE_NUM_MORE_STATUS } from 'tools/statusConstants';
import store from 'store';
import moment from 'moment';
import '../style/index.less';

const { RangePicker } = DatePicker;
const Search = Input.Search;
const Option = Select.Option;
const TabPane = Tabs.TabPane;
const confirm = Modal.confirm;

class AdviceEditRoleTabPane extends React.Component {
    constructor(props) {
        super(props)
        var userData = JSON.parse(sessionStorage.getItem('userData'))
        this.state = {
            dataSource: [],
            total: 0,
            page: 1,
            pageSize: 10,
            userData: userData,
            ids: [],
            rightPageSize: 1,
            code: [],
            size: 'small',
        }
    }

    componentDidMount() {
        this.loadData(1)
        this.loadSelectData()
        this.initData()
    }

    initData() {
        this.columns = [
            // {
            //     title: '医嘱录入列名称',
            //     dataIndex: 'docOrderListDesc',
            //     width: 180,
            //     align: 'center',
            // },
            {
                title: '描述',
                dataIndex: 'descripts',
                width: 180,
                align: 'center',
            },
            {
                title: '就诊类型',
                dataIndex: 'admTypeDesc',
                width: 180,
                align: 'center',
            },
            {
                title: '医嘱优先级',
                dataIndex: 'priorityDesc',
                width: 180,
                align: 'center',
            },
            // {
            //     title: '医嘱优先级',
            //     dataIndex: 'editFlag',
            //     width: 180,
            //     align: 'center',
            //     render: (text, data) => {
            //         return <span>{data.editFlag == 'Y' ? '可编辑' : '不可编辑'}</span>
            //     }
            // },
        ],
            this.rightColumns = [
                {
                    title: '医嘱录入列名称',
                    dataIndex: 'descripts',
                    width: 180,
                    align: 'center',
                },
                {
                    title: '医嘱编辑权限',
                    dataIndex: 'editFlag',
                    width: 180,
                    align: 'center',
                    render: (text, data) => {
                        return <span>{data.editFlag == 'Y' ? '可编辑' : '不可编辑'}</span>
                    }
                },
                , {
                    title: '操作',
                    dataIndex: 'opertion',
                    width: 120,
                    align: 'center',
                    render: (text, data) => {
                        return (
                            <span>
                                <Icon type="edit" style={{ color: '#108EE9' }}></Icon>
                                <span className='span' onClick={this.editRightData.bind(this, data)}>编辑</span>
                                <Divider type="vertical" />
                            </span >
                        )
                    }
                }
            ]
        this.sunColumns = [
            {
                title: '子类名称',
                dataIndex: 'descripts',
                width: 180,
                align: 'center',
            }
        ]
    }

    handleDelete(data) {

    }

    loadData(page, pageSize, e) {
        this.setState({ loading: true })
        var params = {
            params: [{
                userID: this.state.userData.userID,
                hospID: this.state.userData.hospID,
                groupID: this.state.userData.groupID,
                admTypeID: this.state.admTypeId,
                orderTypeID: this.state.orderTypeId,
                priorityID: this.state.priorityId,
            }],
            pagination: [{
                pageSize: this.state.size == 'small' ? this.state.pageSize : PAGE_NUM_MORE_STATUS[0].code,
                currentPage: page
            }]
        }
        $http.post('urlDeault', this, {
            code: "03010043",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    this.setState({
                        dataSource: res.result.data,
                        total: res.result.totalCount,
                        ids: [],
                        docOrderListID: undefined,
                        admTypeID: undefined,
                        orderTypeID: undefined,
                        priorityID: undefined,
                        editFlag: 'N',
                        search: e,
                        loading: false
                    })
                }
            }
        });
    }

    loadSelectData() {
        var params = {
            params: [{
                admTypeFlag: 'Y',
                orderTypeFlag: 'Y',
                docOrdListFlag: 'Y',
                priorityFlag: 'Y',
                subCatFlag: 'Y'
            }]
        }
        $http.post('urlDeault', this, {
            code: "03010045",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    this.setState({
                        admType: res.result.admType,
                        orderType: res.result.orderType,
                        docOrdList: res.result.docOrdList,
                        priority: res.result.priority,
                        subCatData: res.result.subCat
                    })
                }
            }
        });
    }

    //保存
    saveEditRole(status) {
        var params = {
            params: [{
                userID: this.state.userData.userID,
                hospID: this.state.userData.hospID,
                groupID: this.state.userData.groupID,
                docOrderListID: this.state.docOrderListID,
                admTypeID: this.state.admTypeID,
                descripts: this.state.descripts,
                priorityID: this.state.priorityID,
                editFlag: this.state.editFlag,
                copyID: status == 'copy' ? this.state.ids[0] : ''
            }]
        }
        $http.post('urlDeault', this, {
            code: "03010041",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    message.success('保存成功', this.state.userData && this.state.userData.messageTime)
                    this.loadData(1)
                }
            }
        });
    }

    //分页切换
    onChange(e) {
        this.setState({ page: e }, () => {
            this.loadData(e);
        });
    }

    //分页切换
    changePageSize(current, pageSize) {
        this.setState({ pageSize: pageSize, page: current }, () => {
            this.loadData(current, pageSize, 'search');
        });
    }

    changeAdvicePage(current, pageSize) {
        this.setState({ newPage: pageSize, rightPageSize: current }, () => {
            this.loadRightData(current, pageSize, 'search');
        });
    }

    changeData(e) {
        this.setState({ rightPageSize: e }, () => {
            this.loadRightData(e);
        });
    }

    editRightData(data) {
        this.setState({
            editData: data
        })
    }

    handleDel() {
        var params = {
            params: [{
                userID: this.state.userData.userID,
                hospID: this.state.userData.hospID,
                groupID: this.state.userData.groupID,
                id: this.state.ids
            }]
        }
        $http.post('urlDeault', this, {
            code: "03010042",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    message.success('删除成功！', this.state.userData && this.state.userData.messageTime)
                    this.loadData(1)
                }
            }
        });
    }

    handleDelRight() {
        var params = {
            params: [{
                userID: this.state.userData.userID,
                hospID: this.state.userData.hospID,
                groupID: this.state.userData.groupID,
                id: this.state.code
            }]
        }
        $http.post('urlDeault', this, {
            code: "03010050",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    message.success('删除成功！', this.state.userData && this.state.userData.messageTime)
                    this.setState({
                        docOrderListID:undefined
                    },()=>{
                        this.loadRightData(1)
                        this.loadSelectData()
                    })
                }
            }
        });
    }

    handleDelSunData() {
        var params = {
            params: [{
                userID: this.state.userData.userID,
                hospID: this.state.userData.hospID,
                groupID: this.state.userData.groupID,
                id: this.state.newCode
            }]
        }
        $http.post('urlDeault', this, {
            code: "03010103",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    message.success('删除成功！', this.state.userData && this.state.userData.messageTime)
                    this.loadSunData(1)
                }
            }
        });
    }

    clearInput() {
        this.setState({
            subID: undefined
        })
    }

    onSelectChange(ids) {
        this.setState({
            ids
        })
    }

    onSelectRightChange(code) {
        this.setState({
            code
        })
    }

    onSelectSunData(newCode) {
        this.setState({
            newCode
        })
    }

    commonCheckbox(name, e) {
        this.setState({
            [name]: e.target.checked ? 'Y' : 'N',
        })
    }

    //点击行，渲染当前行样式
    onClickRow = (record) => {
        return {
            onClick: () => {
                this.setState({
                    rowId: record.id,
                }, () => {
                    this.loadRightData(1)
                    this.loadSunData()
                })
            }
        };
    }

    loadSunData() {
        var params = {
            params: [{
                userID: this.state.userData.userID,
                hospID: this.state.userData.hospID,
                groupID: this.state.userData.groupID,
                editID: this.state.rowId
            }],
        }
        $http.post('urlDeault', this, {
            code: "03010104",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    this.setState({
                        sunData: res.result.data,
                    })
                }
            }
        });
    }

    //获取明细
    loadRightData(page, pageSize, e) {
        this.setState({ loading: true })
        var params = {
            params: [{
                userID: this.state.userData.userID,
                hospID: this.state.userData.hospID,
                groupID: this.state.userData.groupID,
                editID: this.state.rowId
            }],
            pagination: [{
                pageSize: this.state.size == 'small' ? this.state.pageSize : PAGE_NUM_MORE_STATUS[0].code,
                currentPage: page
            }]
        }
        $http.post('urlDeault', this, {
            code: "03010051",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    this.setState({
                        rightData: res.result.data,
                        totalCount: res.result.totalCount,
                        orderTypeID: undefined,
                        rightPageSize: page,
                        editFlag: 'N',
                        editData: '',
                        searchs: 'search',
                        loading: false
                    })
                }
            }
        });
    }

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

    //保存明细
    addDetailList() {
        var params = {
            params: [{
                userID: this.state.userData.userID,
                hospID: this.state.userData.hospID,
                groupID: this.state.userData.groupID,
                docOrderListID: this.state.docOrderListID ? this.state.docOrderListID :
                    (this.state.editData ? this.state.editData.docOrderListID : ''),
                editID: this.state.rowId,
                editFlag: this.state.editFlag ? this.state.editFlag :
                    (this.state.editData ? this.state.editData.editFlag : 'N'),
                id: this.state.editData ? this.state.editData.id : ''
            }]
        }
        $http.post('urlDeault', this, {
            code: "03010049",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    message.success('保存成功！', this.state.userData && this.state.userData.messageTime)
                    this.setState({
                        docOrderListID:undefined
                    },()=>{
                        this.loadRightData(1)
                        this.loadSelectData()
                    })
                }
            }
        });
    }

    //保存子类医嘱
    saveSunData() {
        var params = {
            params: [{
                userID: this.state.userData.userID,
                hospID: this.state.userData.hospID,
                orderSubCatID: this.state.subID,
                editID: this.state.rowId
            }]
        }
        $http.post('urlDeault', this, {
            code: "03010102",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    message.success('保存成功！', this.state.userData && this.state.userData.messageTime)
                    this.clearInput()
                    this.loadSunData(1)
                }
            }
        });
    }

    handleSelectChange(name, e) {
        this.setState({
            [name]: e
        })
    }

    //过滤已选的下拉数据docOrderListID
    handleFilterOption() {
        var { rightData, docOrdList } = this.state;
        if (!Util.isEmpty(rightData) && !Util.isEmpty(docOrdList)) {
            for (var i = 0; i < docOrdList.length; i++) {
                for (var j = 0; j < rightData.length; j++) {
                    if(docOrdList[i].id == rightData[j].docOrderListID){
                        docOrdList.splice(i, 1);
                    }
                }
            }
            this.setState({})
        }
    }

    render() {
        var { admType, orderType, docOrdList, priority, ids, code, subCatData, newCode } = this.state;
        const rowSelection = {
            ids,
            onChange: this.onSelectChange.bind(this),
            selectedRowKeys: ids,
        }
        const rowRightSelection = {
            code,
            onChange: this.onSelectRightChange.bind(this),
            selectedRowKeys: code,
        }

        const sunSelection = {
            newCode,
            onChange: this.onSelectSunData.bind(this),
            selectedRowKeys: newCode,
        }
        //就诊类型
        var admTypeOption = []
        admType && admType.map((item, index) => {
            admTypeOption.push(<Option value={item.id} key={index} code={item.descriptsSPCode}>{item.descripts}</Option>)
        })
        //医嘱类型
        var orderTypeOption = []
        orderType && orderType.map((item, index) => {
            orderTypeOption.push(<Option value={item.id} key={index} code={item.descriptsSPCode}>{item.descripts}</Option>)
        })
        //医嘱录入列
        var docOrdListOption = []
        docOrdList && docOrdList.map((item, index) => {
            docOrdListOption.push(<Option value={item.id} key={index} code={item.descriptsSPCode}>{item.descripts}</Option>)
        })
        //医嘱优先级
        var priorityOption = []
        priority && priority.map((item, index) => {
            priorityOption.push(<Option value={item.id} key={index} code={item.descriptsSPCode}>{item.descripts}</Option>)
        })

        //医嘱子类
        var subCatDataOption = []
        subCatData && subCatData.map((item, index) => {
            subCatDataOption.push(<Option value={item.id} key={index} code={item.descriptsSPCode}>{item.descripts}</Option>)
        })

        return <div className='outpatient-station-body' style={{ height: '100%', background: '#f0f2f5' }}>
            <Card>
                <Row>
                    <Col span={5}>
                        就诊类型：<Select placeholder='请选择就诊类型' style={{ width: 180 }} showSearch allowClear
                            onChange={Util.handleSelectChange.bind(this, 'admTypeID')}
                            value={this.state.admTypeID}
                            filterOption={(input, option) =>
                                option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                || option.props.code.toLowerCase().indexOf(input.toLowerCase()) >= 0
                            }>{admTypeOption}</Select>
                    </Col>
                    <Col span={5}>
                        {/* 医嘱类型：<Select placeholder='请选择医嘱类型' style={{ width: 180 }} showSearch allowClear
                            onChange={Util.handleSelectChange.bind(this, 'orderTypeID')}
                            value={this.state.orderTypeID}
                            filterOption={(input, option) =>
                                option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                || option.props.code.toLowerCase().indexOf(input.toLowerCase()) >= 0
                            }>{orderTypeOption}</Select> */}
                        医嘱类型：<Input onChange={Util.commonInputChange.bind(this, 'descripts')} style={{ width: 180 }} />
                    </Col>
                    <Col span={5}>
                        医嘱优先级：<Select placeholder='请选择医嘱优先级' style={{ width: 180 }} showSearch allowClear
                            onChange={Util.handleSelectChange.bind(this, 'priorityID')}
                            value={this.state.priorityID}
                            filterOption={(input, option) =>
                                option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                || option.props.code.toLowerCase().indexOf(input.toLowerCase()) >= 0
                            }>{priorityOption}</Select>
                    </Col>
                    <Button type='primary' style={{ marginLeft: 10 }} onClick={this.saveEditRole.bind(this)}>保存</Button>
                    <Button type='primary' style={{ marginLeft: 10 }} disabled={!Util.isEmpty(this.state.ids) ? false : true}
                        onClick={this.saveEditRole.bind(this, 'copy')}>复制</Button>
                </Row>
            </Card>

            <div style={{ marginTop: 10, background: 'f0f2f5' }}>
                <div style={{ float: 'left', width: '61%', border: '1px solid #f0f2f5' }}>
                    <Table columns={this.columns} style={{ background: 'white', height: store.getState().tableHeight.y + 27 + 'px' }}
                        dataSource={this.state.dataSource}
                        loadData={this.loadData.bind(this)}
                        onRow={this.onClickRow}
                        rowClassName={this.setRowClassName}
                        rowSelection={rowSelection}
                        bordered
                        title={() => {
                            return <div style={{ display: 'flex', lineHeight: '35px' }}>
                                就诊类型：<Select placeholder='请选择就诊类型' style={{ width: 170 }} showSearch allowClear
                                    onChange={Util.handleSelectChange.bind(this, 'admTypeId')}
                                    value={this.state.admTypeId}
                                    filterOption={(input, option) =>
                                        option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                        || option.props.code.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                    }>{admTypeOption}</Select>
                                {/* <span style={{ marginLeft: 5 }}>医嘱类型：</span><Select placeholder='请选择医嘱类型' style={{ width: 170 }} showSearch allowClear
                                    onChange={Util.handleSelectChange.bind(this, 'orderTypeId')}
                                    value={this.state.orderTypeId}
                                    filterOption={(input, option) =>
                                        option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                        || option.props.code.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                    }>{orderTypeOption}</Select> */}
                                <span style={{ marginLeft: 5 }}>医嘱优先级：</span><Select placeholder='请选择医嘱优先级' style={{ width: 170 }} showSearch allowClear
                                    onChange={Util.handleSelectChange.bind(this, 'priorityId')}
                                    value={this.state.priorityId}
                                    filterOption={(input, option) =>
                                        option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                        || option.props.code.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                    }>{priorityOption}</Select>
                                <Button type='primary' style={{ marginLeft: 10 }} onClick={this.loadData.bind(this, '1', 'search')}>查询</Button>
                                <Button style={{ marginLeft: 10 }} type='danger' onClick={this.handleDel.bind(this)}>删除</Button>
                            </div>
                        }}
                        rowKey={(data) => {
                            return data.id
                        }}
                        scroll={{ y: store.getState().tableHeight.y + 'px' }}
                        pagination={false}>
                    </Table>
                    <CommonPagination size={this.state.size} current={this.state.page} total={this.state.total} search={this.state.search}
                        onShowSizeChange={this.changePageSize.bind(this)} complete={false} dataSource={this.state.dataSource}
                        loading={this.state.loading} onChange={this.onChange.bind(this)} />
                </div>

                <div style={{ float: 'right', width: '38%', background: 'f0f2f5', border: '1px solid #f0f2f5' }}>
                    <div>
                        <Table columns={this.sunColumns} style={{ background: 'white', height: 300 }}
                            dataSource={this.state.sunData}
                            loadData={this.loadSunData.bind(this, '1')}
                            rowSelection={sunSelection}
                            bordered
                            title={() => {
                                return <div style={{ display: 'flex', lineHeight: '35px' }}>
                                    <span style={{ marginLeft: 10 }}>医嘱子类：</span><Select placeholder='请选择医嘱子类' style={{ width: 350 }} showSearch allowClear
                                        onChange={this.handleSelectChange.bind(this, 'subID')}
                                        mode="multiple"
                                        // value={this.state.docOrderListID ? this.state.docOrderListID :
                                        //     (Util.isEmpty(this.state.editData) ? undefined : this.state.editData.docOrderListID)}
                                        filterOption={(input, option) =>
                                            option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                            || option.props.code.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                        }>{subCatDataOption}</Select>

                                    <Button type='primary' style={{ marginLeft: 10 }}
                                        onClick={this.saveSunData.bind(this)}>保存</Button>
                                    <Button style={{ marginLeft: 10 }} type='danger' onClick={this.handleDelSunData.bind(this)}>删除</Button>
                                </div>
                            }}
                            rowKey={(data) => {
                                return data.id
                            }}
                            scroll={{ y: 200 }}
                            pagination={false}>
                        </Table>
                        {/* <div style={{marginTop:15}} >
                        <CommonPagination size={this.state.size} current={this.state.page} total={this.state.totalCount} search={this.state.searchs}
                            onShowSizeChange={this.changeAdvicePage.bind(this)} complete={false} dataSource={this.state.rightData}
                            loading={this.state.loading} onChange={this.changeData.bind(this)} /></div> */}
                    </div>

                    <div style={{ marginTop: 20 }}>
                        <Table columns={this.rightColumns} style={{ background: 'white', height: 300 }}
                            dataSource={this.state.rightData}
                            loadData={this.loadRightData.bind(this, '1')}
                            rowSelection={rowRightSelection}
                            bordered
                            title={() => {
                                return <div style={{ display: 'flex', lineHeight: '35px' }}>
                                    <span style={{ marginLeft: 10 }}>医嘱录入列：</span><Select placeholder='请选择医嘱录入列' style={{ width: 170 }} showSearch allowClear
                                        onChange={Util.handleSelectChange.bind(this, 'docOrderListID')}
                                        disabled={!Util.isEmpty(this.state.editData) ? true : false}
                                        onFocus={this.handleFilterOption.bind(this)}
                                        value={this.state.docOrderListID ? this.state.docOrderListID :
                                            (Util.isEmpty(this.state.editData) ? undefined : this.state.editData.docOrderListID)}
                                        filterOption={(input, option) =>
                                            option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                            || option.props.code.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                        }>{docOrdListOption}</Select>
                                    <span style={{ marginLeft: 10 }}>是否编辑：</span><Checkbox
                                        checked={this.state.editFlag == 'N' ? false : (Util.isEmpty(this.state.editData) ? false :
                                            (this.state.editData.editFlag == 'Y' ? true : false))}
                                        onChange={this.commonCheckbox.bind(this, 'editFlag')} />
                                    <Button type='primary' style={{ marginLeft: 10 }} disabled={this.state.rowId ? false : true}
                                        onClick={this.addDetailList.bind(this)}>保存</Button>
                                    <Button style={{ marginLeft: 10 }} type='danger' onClick={this.handleDelRight.bind(this)}>删除</Button>
                                </div>
                            }}
                            rowKey={(data) => {
                                return data.id
                            }}
                            scroll={{ y: 200 }}
                            pagination={false}>
                        </Table>
                        <div style={{ marginTop: 15 }} >
                            <CommonPagination size={this.state.size} current={this.state.rightPageSize} total={this.state.totalCount} search={this.state.searchs}
                                onShowSizeChange={this.changeAdvicePage.bind(this)} complete={false} dataSource={this.state.rightData}
                                loading={this.state.loading} onChange={this.changeData.bind(this)} /></div>
                    </div>
                </div>
            </div>
        </div>
    }

}
export default AdviceEditRoleTabPane;