/**
 * 医嘱录入列设置
 */

import React from 'react';
import {
    Card, Table, Input, Form, Select, Row, Col, Checkbox, Tabs,
    Radio, Button, Popconfirm, Icon, Divider, message, Modal,
} from 'antd';
import { Util, dayFormat } from 'tools/index';
import { $http } from 'containers/config/https';
import store from 'store';
import moment from 'moment';
import './style/index.less';

const Search = Input.Search;
const Option = Select.Option;
const confirm = Modal.confirm;

class AdviceColumnSettingPage 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,
            btnStatus: 'COMMON'
        }
    }

    componentDidMount() {
        this.loadData()
        this.initData()
        this.loadHospitalMsg()
        this.loadAdviceType()
        this.getDepartment(this.state.userData.hospID);
        document.querySelector('.ant-table-body').style.height = store.getState().tableHeight.y + 'px';
    }

    initData() {
        this.columns = [
            {
                title: '列名',
                dataIndex: 'descripts',
                width: 200,
                align: 'center',
                // render: (text, data, index) => {
                //     return <Input value={data.descripts} style={{ width: '90%' }}
                //         onChange={this.updateCommonInput.bind(this, 'descripts', data, index)} />
                // }
            },
            {
                title: '下标名',
                dataIndex: 'code',
                width: 180,
                align: 'center',
                // render: (text, data, index) => {
                //     return <Input value={data.code} style={{ width: '90%' }} onChange={this.updateCommonInput.bind(this, 'code', data, index)} />
                // }
            },
            {
                title: '属性名',
                dataIndex: 'attribute',
                width: 180,
                align: 'center',
                // render: (text, data, index) => {
                //     return <Input value={data.attribute} style={{ width: '90%' }}
                //         onChange={this.updateCommonInput.bind(this, 'attribute', data, index)} />
                // }
            },
            {
                title: '其他样式',
                dataIndex: 'style',
                width: 180,
                align: 'center',
                render: (text, data, index) => {
                    return <Input value={data.style} style={{ width: '90%' }}
                        onChange={this.updateCommonInput.bind(this, 'style', data, index)} />
                }
            },
            {
                title: '列宽',
                dataIndex: 'width',
                width: 180,
                align: 'center',
                render: (text, data, index) => {
                    return <Input value={data.width} style={{ width: '90%' }} onChange={this.updateCommonInput.bind(this, 'width', data, index)} />
                }
            },
            {
                title: '隐藏',
                dataIndex: 'hide',
                width: 180,
                align: 'center',
                render: (text, data, index) => {
                    return <Checkbox value={data.hide == 'Y' ? true : false} checked={data.hide == 'Y' ? true : false}
                        onChange={this.changeCheckBox.bind(this, 'hide', index)} />
                }
            },
        ]
    }

    changeCheckBox(name, index, e) {
        this.state.dataSource[index][name] = e.target.checked ? 'Y' : 'N'
        this.setState({})
    }

    updateCommonInput(name, data, index, e) {
        this.state.dataSource[index][name] = e.target.value
        this.setState({})
    }

    loadAdviceType() {
        var params = {
            params: [{
            }]
        }
        $http.post('urlDeault', this, {
            code: "03050088",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    this.setState({
                        adviceType: res.result.Data
                    })
                }
            }
        });
    }

    loadData() {
        var params = {
            params: [{
                userID: this.state.depDoctorId,
                hospID: this.state.btnStatus == 'COMMON' ? '' : (this.state.hospitalId ? this.state.hospitalId : this.state.userData.hospID),
                locID: this.state.departId,
                saveType: this.state.btnStatus,
                admTypeID: this.state.admID
            }]
        }
        $http.post('urlDeault', this, {
            code: "03010022",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    this.setState({
                        dataSource: res.data,
                        deleteID: res.id
                    })
                }
            }
        });
    }

    showDefaultElement(e) {
        this.setState({
            btnStatus: e.target.value,
        }, () => {
            this.loadData()
        })
    }

    //鼠标移动添加样式
    addMouseOverStyle(name, e) {
        this.setState({
            addMouseStyle: true,
            indexStyle: name
        })
    }
    addMouseLeaveStyle() {
        this.setState({
            addMouseStyle: false,
            indexStyle: ''
        })
    }

    getDepartment(e) {
        var params = {
            params: [{
                hospID: e,
            }]
        }
        $http.post('urlS', this, {
            code: "03020046",
            data: params,
            success: function (res) {
                if (res.errorCode === '0') {
                    this.setState({ departmentData: res.result.Data })
                }
            }
        })
    }

    //获取医院信息
    loadHospitalMsg() {
        var params = {
            params: [{
                // hospitalId:this.state.userData.hospDr,
                logonHospID: this.state.userData.hospID,
                logonGroupID: this.state.userData.groupID,
                hospRequired: '1'
            }]
        }
        $http.post('urlDeault', this, {
            code: "01040001",
            data: params,
            success: function (res) {
                if (res.errorCode === '0') {
                    this.setState({
                        hospitalData: res.depDoctor
                    })
                }
            }
        });
    }


    //获取坐诊医生
    getDoctor(departId, depDoctorId) {
        var params = {
            params: [{
                locID: departId ? departId : (this.state.departId ? this.state.departId : this.state.userData.locID),
                groupID: '',
                depDoctorID: depDoctorId || '',
                hospID: this.state.hospitalId ? this.state.hospitalId : this.state.userData.hospID
            }]
        }
        $http.post('urlDeault', this, {
            code: "03020049",
            data: params,
            success: function (res) {
                if (res.errorCode === '0') {
                    this.setState({
                        doctorData: res.depDoctor
                    })
                }
            }
        });
    }

    //获取科室ID
    changeDepartment(e) {
        var id = '';
        var departName = '';
        if (e) {
            id = e.substring(e.indexOf('^') + 1)
            departName = e.substring(0, e.indexOf('-'))
        }
        this.setState({
            departId: id,
            departName: departName,
            depDoctorId: ''
        })
        this.getDoctor(id, '')
    }

    handleSelectChangeHos(e) {
        var id = '';
        if (e) {
            id = e.substring(e.indexOf('^') + 1)
        }
        this.setState({
            hospitalId: id,
            departId: '',
            depDoctorId: ''

        }, () => {
            this.getDepartment(id);//获取医院信息后调查看科室接口
        })
    }

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

    //获取坐诊医生ID
    changeDoctorId(e) {
        var id = '';
        var docName = ''
        if (e) {
            id = e.substring(e.indexOf('#') + 1);
            docName = e.substring(0, e.indexOf('-'))
        }
        this.setState({
            depDoctorId: id,
            docName: docName
        })
        // this.getDoctor('', id)
    }

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

    handleSaveBtn() {
        var params = {
            params: [{
                userID: this.state.depDoctorId,
                hospID: this.state.hospitalId ? this.state.hospitalId : this.state.userData.hospID,
                logonUserID: this.state.userData.userID,
                locID: this.state.departId,
                saveType: this.state.btnStatus,
                datas: this.state.dataSource,
                admTypeID: this.state.admID
            }]
        }
        $http.post('urlDeault', this, {
            code: "03010021",
            data: params,
            success: function (res) {
                if (res.errorCode === '0') {
                    message.success('保存成功！', this.state.userData && this.state.userData.messageTime)
                    this.loadData()
                }
            }
        });
    }

    delMechansim() {
        var params = {
            params: [{
                userID: this.state.userData.userID,
                hospID: this.state.userData.hospID,
                groupID: this.state.userData.groupID,
                id: [this.state.deleteID]
            }]
        }
        $http.post('urlDeault', this, {
            code: "03010108",
            data: params,
            success: function (res) {
                if (res.errorCode === '0') {
                    message.success('清除设置成功！', this.state.userData && this.state.userData.messageTime)
                    this.loadData()
                }
            }
        });
    }

    handleUp = () => {
        var keys = this.state.ids
        var data = this.state.dataSource
        var newKeys = []
        keys = keys.sort(function (m, n) {
            if (m < n) return -1
            else if (m > n) return 1
            else return 0
        });
        for (var i = 0; i < keys.length; i++) {
            if (keys[i] - 1 === 0) {
                newKeys.push(keys[i])
                // continue
                message.warn('已经到顶了，无法再移动！', this.state.userData && this.state.userData.messageTime)
                return
            }
            var curRowData = data[keys[i] - 1]
            var curRowKey = curRowData.count
            var upRowData = data[keys[i] - 2]
            var upRowKey = upRowData.count
            upRowData.count = curRowKey
            curRowData.count = upRowKey
            data[keys[i] - 1] = upRowData
            data[keys[i] - 2] = curRowData
            newKeys.push(keys[i] - 1)
        }
        this.setState(
            {
                dataSource: data,
                ids: newKeys
            }
        )
    }
    handleDown = () => {
        var keys = this.state.ids
        var data = this.state.dataSource
        var newKeys = []
        keys = keys.sort(function (m, n) {
            if (m < n) return -1
            else if (m > n) return 1
            else return 0
        });
        for (var i = keys.length - 1; i >= 0; i--) {
            if (keys[i] === data.length) {
                newKeys.push(keys[i])
                // continue
                message.warn('已到最底部，无法移动！', this.state.userData && this.state.userData.messageTime)
                return
            }
            var curRowData = data[keys[i] - 1]
            var upRowData = data[keys[i]]
            var curRowKey = curRowData.count
            var upRowKey = upRowData.count
            upRowData.count = curRowKey
            curRowData.count = upRowKey
            data[keys[i] - 1] = upRowData
            data[keys[i]] = curRowData
            newKeys.push(keys[i] + 1)
        }
        this.setState(
            {
                dataSource: data,
                ids: newKeys
            }
        )
    }

    render() {
        const { ids } = this.state;
        const rowSelection = {
            ids,
            onChange: this.onSelectChange.bind(this),
            selectedRowKeys: ids,
        }
        //所属医院参数
        let hospitalOption = [];
        this.state.hospitalData && this.state.hospitalData.map((item, index) => {
            hospitalOption.push(<Option key={index} value={item.descripts + '^' + item.id} code={item.code}
                name={item.descripts}>{item.descripts}</Option>)
        })
        //获取科室Department
        let departmentOption = [];
        this.state.departmentData && this.state.departmentData.map((item, index) => {
            departmentOption.push(<Option key={index} value={item.descripts + '-' + item.descriptsSPCode +
                '^' + item.id} code={item.descriptsSPCode} name={item.descripts}>{item.descripts}</Option>)
        })
        //坐诊医生
        let doctorOption = []
        this.state.doctorData && this.state.doctorData.map((item, index) => {
            doctorOption.push(<Option key={index}
                value={item.descripts + '-' + item.code + item.descriptsSPCode + '#' + item.id + ''}
                code={item.descriptsSPCode} name={item.descripts}>
                {item.descripts}</Option>)
        })

        //就诊类型
        let adviceTypeOption = []
        this.state.adviceType && this.state.adviceType.map((item, index) => {
            adviceTypeOption.push(<Option key={index} value={item.admTypeID} code={item.code}>{item.admDesc}</Option>)
        })

        return <div className='columns-station-body' style={{ height: '100%' }}>
            <Row style={{ margin: '0 20px' }}>
                <Table columns={this.columns} dataSource={this.state.dataSource}
                    pagination={false} bordered
                    rowSelection={rowSelection}
                    scroll={{ y: store.getState().tableHeight.y + 'px' }}
                    rowKey={(data) => {
                        return data.count
                    }}
                    title={() => {
                        return <div>
                            <Radio.Group defaultValue='COMMON' buttonStyle="solid" onChange={this.showDefaultElement.bind(this)}>
                                <Radio.Button value='COMMON'>就诊类型</Radio.Button>
                                <Radio.Button value='HOSP'>医院</Radio.Button>
                                <Radio.Button value='LOC'>科室</Radio.Button>
                                <Radio.Button value='USER'>医生</Radio.Button>
                            </Radio.Group>
                            <div style={{ marginTop: 10, display: 'flex' }}>
                                <Select style={{ width: 180 }} placeholder='请选择就诊类型' allowClear
                                    showSearch
                                    filterOption={(input, option) =>
                                        option.props.code.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                    }
                                    onChange={this.handleSelectChangeType.bind(this, 'admID')}>
                                    {adviceTypeOption}
                                </Select>

                                {this.state.btnStatus == 'HOSP' || this.state.btnStatus == 'LOC' || this.state.btnStatus == 'USER' ?
                                    <Select style={{ width: 180 }} placeholder='请选择医院' allowClear
                                        defaultValue={this.state.userData.hospDesc}
                                        showSearch
                                        filterOption={(input, option) =>
                                            option.props.code.toLowerCase().indexOf(input.toLowerCase()) >= 0 ||
                                            option.props.name.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                        }
                                        onChange={this.handleSelectChangeHos.bind(this)}>
                                        {hospitalOption}
                                    </Select> : null}
                                {this.state.btnStatus == 'LOC' || this.state.btnStatus == 'USER' ?
                                    <Select
                                        style={{ width: 180, marginLeft: 10 }}
                                        placeholder='请选择科室'
                                        allowClear
                                        showSearch
                                        filterOption={(input, option) =>
                                            option.props.code.toLowerCase().indexOf(input.toLowerCase()) >= 0 ||
                                            option.props.name.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                        }
                                        value={this.state.departId ? this.state.departName : undefined}
                                        onChange={this.changeDepartment.bind(this)}>
                                        {departmentOption}
                                    </Select> : null}
                                {this.state.btnStatus == 'USER' ?
                                    <Select style={{ width: 180, marginLeft: 10 }} placeholder='请选择医生' allowClear
                                        showSearch
                                        filterOption={(input, option) =>
                                            option.props.code.toLowerCase().indexOf(input.toLowerCase()) >= 0 ||
                                            option.props.name.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                        }
                                        value={this.state.depDoctorId ? this.state.docName : undefined}
                                        onChange={this.changeDoctorId.bind(this)}>
                                        {doctorOption}
                                    </Select> : null}
                                <Button style={{ marginLeft: 10 }} type='primary' onClick={this.loadData.bind(this)}>查询</Button>
                            </div>

                            <div style={{ marginTop: 10 }}>
                                <span style={{ cursor: 'pointer' }} className={this.state.indexStyle == '3' ? 'mouse-add-Style' : ''}
                                    onMouseLeave={this.addMouseLeaveStyle.bind(this)}
                                    onClick={this.handleUp}
                                    onMouseOver={this.addMouseOverStyle.bind(this, '3')}>
                                    <Icon className='doctor-up-splice' />
                                    <span>上移</span>
                                </span><Divider type="vertical" />
                                <span style={{ cursor: 'pointer' }} className={this.state.indexStyle == '4' ? 'mouse-add-Style' : ''}
                                    onMouseLeave={this.addMouseLeaveStyle.bind(this)}
                                    onClick={this.handleDown}
                                    onMouseOver={this.addMouseOverStyle.bind(this, '4')}>
                                    <Icon className='doctor-down-splice' />
                                    <span>下移</span>
                                </span><Divider type="vertical" />
                                {/* <span style={{ cursor: 'pointer' }} className={this.state.indexStyle == '5' ? 'mouse-add-Style' : ''}
                                    onClick={this.delMechansim.bind(this)}
                                    onMouseLeave={this.addMouseLeaveStyle.bind(this)}
                                    onMouseOver={this.addMouseOverStyle.bind(this, '5')}>
                                    <Icon className='doctor-delete-splice' />
                                    <span>清除设置</span>
                                </span> */}
                                <span style={{ cursor: 'pointer' }} className={this.state.indexStyle == '12' ? 'mouse-add-Style' : ''}
                                    onMouseLeave={this.addMouseLeaveStyle.bind(this)}
                                    onClick={this.handleSaveBtn.bind(this)}
                                    onMouseOver={this.addMouseOverStyle.bind(this, '12')}>
                                    <Icon className='doctor-save-splice' />
                                    <span>保存</span><Divider type="vertical" />
                                </span>
                                <Button type='primary' size='small' onClick={this.delMechansim.bind(this)}
                                    disabled={Util.isEmpty(this.state.deleteID) ? true : false}>清除设置</Button>
                            </div>
                        </div>
                    }}></Table>
            </Row>
        </div>
    }

}
export default AdviceColumnSettingPage;