/*
* 编辑排班
* */

import React, { Component } from 'react';
import { Input, Form, Select, Modal, Button, Row, Col, Table, Card, Tabs, Checkbox, message } from 'antd';
import AddMechanism from 'components/addMechanism';
import { $http } from 'containers/config/https';
import { Util } from 'tools/index';
import '../style/index.less';

const Option = Select.Option;
const FormItem = Form.Item;
const TabPane = Tabs.TabPane;

class ShowStopMedicalModal extends Component {

    constructor(props) {
        var userData = JSON.parse(sessionStorage.getItem('userData'));
        super(props);
        this.state = {
            dataSource: [],
            data: [{}],
            saveData: [],
            userData: userData,
            showKey: '1',
            newData: [],
            voluntServiceFlag: false
        }
    }

    componentWillReceiveProps(nextProp) {
        if (nextProp.isShow === true) {
            this.setState({
                resourceType: nextProp.resourceType,
                resourceTypeID: nextProp.resourceTypeID,
                regTitleID: nextProp.medicalData ? nextProp.medicalData.regTitleID : undefined,
            }, () => {
                this.loadLocResDetail(nextProp.medcialId)
                this.getDoctorRoom(nextProp.medicalData ? nextProp.medicalData.locID : '')
            })
        } else if (this.props.isShow === false) {
            this.cleanInput();
        }
    }

    componentDidMount() {
        this.initData()
        this.getDoctorRoom()
        this.loadscheduType()
    }

    //获取坐诊类型
    loadscheduType() {
        var params = {
            params: [
                {
                    hospID: this.state.userData.hospID,
                    resourceTypeID: this.state.resourceTypeID
                }
            ],
            pagination: [{
                pageSize: 1000,
                currentPage: 1
            }]
        }
        $http.post('urlDeault', this, {
            code: "03020004",
            data: params,
            success: function (res) {
                if (res.errorCode === '0') {
                    this.setState({
                        sumData: res.result.Data,
                    })
                }
            }
        });
    }

    //获取诊室
    getDoctorRoom(id) {
        var params = {
            params: [{
                hospID: this.state.hospitalId,
                locID: this.state.roomDr ? this.state.roomDr : (id ? id : this.state.userData.locID),
                resourceTypeID: this.state.resourceTypeID
            }]
        }
        // var params = []
        $http.post('urlDeault', this, {
            code: "01040023",
            data: params,
            success: function (res) {
                if (res.errorCode === '0') {
                    this.setState({
                        doctorRoom: res.room
                    })
                }
            }
        });
    }

    loadLocResDetail(id) {
        var params = {
            params: [{
                locResDetailID: id,
                flag: this.state.showKey == '2' ? 'R' : (this.state.showKey == '3' ? 'S' : ''),
                resourceTypeID: this.state.resourceTypeID
            }]
        }
        // var params = []
        $http.post('urlDeault', this, {
            code: "03020041",
            data: params,
            success: function (res) {
                if (res.errorCode === '0') {
                    this.setState({
                        dataSource: res.data,
                        newData: res.data,
                        resultData: res.data
                    })
                }
            }
        });
    }

    initData() {
        this.columns = [
            {
                title: '时间段',
                dataIndex: 'timeDetailStr',
                width: 120,
                align: 'center'
            }, {
                title: '号源数',
                dataIndex: 'registNum',
                width: 120,
                align: 'center',
                render: (text, data) => {
                    return <span>
                        <span>{data.registNum}</span>
                        <span style={{ color: 'red' }}>{'(已使用' + data.registedNum + ')'}</span>
                    </span>
                }
            }, {
                title: '新号源',
                dataIndex: 'newNum',
                width: 120,
                align: 'center',
                render: (text, data, index) => {
                    return <Input placeholder='请输入新号源' disabled={data.editFlag == 'Y' ? false : true} onChange={this.changeNewNum.bind(this, text, data, index)}
                        style={{ width: '80' }} />
                }
            }, {
                title: '原可预约数',
                dataIndex: 'appointNum',
                width: 120,
                align: 'center',
                render: (text, data) => {
                    return <span>
                        <span>{data.appointNum}</span>
                        <span style={{ color: 'red' }}>{'(已使用' + data.appointedNum + ')'}</span>
                    </span>
                }
            }, {
                title: '新可预约数',
                dataIndex: 'newRegNum',
                width: 120,
                align: 'center',
                render: (text, data, index) => {
                    return <Input placeholder='请输入新科预约数' disabled={data.editFlag == 'Y' ? false : true} onChange={this.changeRegNum.bind(this, text, data, index)}
                        style={{ width: '80' }} />
                }
            },
        ]
        this.stopMedical = [
            {
                title: '时间段',
                dataIndex: 'timeDetailStr',
                width: 120,
                align: 'center'
            }, {
                title: '号源数',
                dataIndex: 'registNum',
                width: 120,
                align: 'center',
                render: (text, data) => {
                    return <span>{data.registedNum + '/' + data.registNum}</span>
                }
            }, {
                title: '选择',
                dataIndex: 'opertion',
                width: 120,
                align: 'center',
                render: (text, data) => {
                    return <Checkbox disabled={(data.editFlag == 'Y' ? false : true) || data.workStatusID == '1'}
                        // checked={data.checked ? data.checked : (data.retWorkStatusDr == '1' ? true : false)}
                        onChange={this.changeCheck.bind(this, data)}>
                    </Checkbox>
                }
            }
        ]
        this.contrColumns = [
            {
                title: '时间段',
                dataIndex: 'timeDetailStr',
                width: 120,
                align: 'center'
            }, {
                title: '号源数',
                dataIndex: 'registNum',
                width: 120,
                align: 'center',
                render: (text, data) => {
                    return <span>{data.registedNum + '/' + data.registNum}</span>
                }
            }, {
                title: '选择',
                dataIndex: 'opertion',
                width: 120,
                align: 'center',
                render: (text, data) => {
                    return (data.registedNum || data.appointedNum > 0 ? '有预约就诊病人不能停诊' : <Checkbox disabled={(data.editFlag == 'Y' ? false : true) || (data.workStatusID == '2')}
                        // checked={data.checkedData ? data.checkedData : (data.retWorkStatusDr == '2' ? true : false)}
                        onChange={this.changeContrCheck.bind(this, data)}>
                    </Checkbox>)
                }
            }
        ]
    }

    loadData() {

    }

    //恢复停诊
    changeCheck(data, e) {
        data.checked = e.target.checked
        if (e.target.checked) {
            data.retWorkStatusID = '1'
        } else {
            data.retWorkStatusID = '2'
        }
        this.setState({})
    }

    //停诊
    changeContrCheck(data, e) {
        data.checkedData = e.target.checked
        if (e.target.checked) {
            data.retWorkStatusID = '2'
        } else {
            data.retWorkStatusID = '1'
        }
        this.setState({})
    }

    //获取新号源参数
    changeNewNum(text, data, index, e) {
        var { dataSource } = this.state;
        var datas = e.target.value;
        if (!(/(^[1-9]\d*$)/.test(datas)) && datas.length > 0) {
            message.error('请输入整数')
            return
        }
        for (var i = 0; i < dataSource.length; i++) {
            if (data.locResTimeID == dataSource[i].locResTimeID) {
                // this.state.dataSource[i].registNum = e.target.value
                this.state.dataSource[i]['regNum'] = e.target.value
            }
        }
        // this.setState({})
    }

    //获取新预约挂号数
    changeRegNum(text, data, index, e) {
        var { dataSource, resultData } = this.state;
        var datas = e.target.value;
        if (!(/(^[0-9]\d*$)/.test(datas)) && datas.length > 0) {
            message.error('请输入整数')
            return
        }

        for (var i = 0; i < dataSource.length; i++) {
            if (data.locResTimeID == dataSource[i].locResTimeID) {
                // this.state.dataSource[i].appointNum = e.target.value
                this.state.dataSource[i]['aptNum'] = e.target.value
            }
        }
        // this.setState({})
    }

    closeModal() {
        let { onHide } = this.props;
        onHide && onHide();
        this.cleanInput();
    }

    //清空输入框
    cleanInput() {
        this.props.form.resetFields();
        this.setState({
            dataSource: [],
            newData: [],
            roomDr: '',
            voluntServiceFlag: false
        })
    }

    //提交
    onSubmit() {
        let { validateFields } = this.props.form;
        validateFields({ force: true }, (err, value) => {
            if (err) {
                return;
            }
            if (Util.isEmpty(this.state.roomDr) && Util.isEmpty((this.props.medicalData ? this.props.medicalData.roomID : ''))) {
                message.error('坐诊诊室不能为空，请选择诊室！')
                return
            }
            let { onSubmit } = this.props;
            if (this.state.showKey == '1') {
                var { dataSource } = this.state;
                var temp = []
                for (var i = 0; i < dataSource.length; i++) {
                    if (!Util.isEmpty(dataSource[i].regNum) || !Util.isEmpty(dataSource[i].aptNum)) {
                        temp.push(dataSource[i])
                    } else {
                        if (Util.isEmpty(dataSource[i].regNum)) {
                            dataSource[i].regNum = dataSource[i].registNum
                        }
                        if (Util.isEmpty(dataSource[i].aptNum)) {
                            dataSource[i].aptNum = dataSource[i].appointNum
                        }
                        temp.push(dataSource[i])
                    }
                    if ((parseInt(dataSource[i].regNum) < parseInt(dataSource[i].registedNum)) &&
                        (parseInt(dataSource[i].regNum) < parseInt(dataSource[i].appointedNum))
                        && (parseInt(dataSource[i].regNum) < Util.isEmpty(dataSource[i].aptNum) ? (dataSource[i].appointNum) :
                            (parseInt(dataSource[i].aptNum ? dataSource[i].aptNum : 0))
                        )) {
                        message.error('新号源必须大于已使用号源并且大于已使用预约数和新可预约数')
                        return
                    }
                }
                var params = {
                    userID: this.state.userData.userID,
                    params: this.state.dataSource,
                    resourceTypeID: this.state.resourceTypeID,
                    regTitleID: this.state.regTitleID,
                    locResDetailID: this.props.medcialId,
                    voluntServiceFlag: this.state.voluntServiceFlag ? 'Y' : 'N',
                    roomID: this.state.roomDr ? this.state.roomDr : (this.props.medicalData ? this.props.medicalData.roomID : '')
                }
                onSubmit && onSubmit(params, this.state.showKey);
            } else {
                var params = {
                    userID: this.state.userData.userID,
                    params: this.state.newData,
                    resourceTypeID: this.state.resourceTypeID,
                    regTitleID: this.state.regTitleID,
                    locResDetailID: this.props.medcialId,
                    voluntServiceFlag: this.state.voluntServiceFlag ? 'Y' : 'N',
                    roomID: this.state.roomDr ? this.state.roomDr : (this.props.medicalData ? this.props.medicalData.roomID : '')
                }
                onSubmit && onSubmit(params, this.state.showKey);
            }

        });
    }

    changeKey(e) {
        this.setState({
            showKey: e
        }, () => {
            this.loadLocResDetail(this.props.medcialId)
        })
    }

    changeCheckBox(e) {
        this.setState({
            voluntServiceFlag: e.target.checked
        })
    }

    render() {
        console.dir(this.props.medicalData)
        let { getFieldDecorator, getFieldValue } = this.props.form;
        let formItemLayout = {
            labelCol: { span: 10 },
            wrapperCol: { span: 19 }
        };

        let merchantOption = [];
        //坐诊诊室
        let doctorRoomOption = []
        this.state.doctorRoom && this.state.doctorRoom.map((item, index) => {
            doctorRoomOption.push(<Option key={index} value={item.id + ''}>{item.descripts}</Option>)
        })

        //坐诊类型sumData
        let sumDataOption = []
        this.state.sumData && this.state.sumData.map((item, index) => {
            sumDataOption.push(<Option key={index} value={item.id}>{item.descripts}</Option>)
        })

        return <Modal className='departModalStyle'
            title={'设置医生排班'}
            maskClosable={false}
            visible={this.props.isShow}
            onCancel={this.closeModal.bind(this)}
            onOk={this.onSubmit.bind(this)}>
            <div>
                <div className="modal-body">
                    <span>
                        <span>
                            {this.props.medicalData ? this.props.medicalData.userName : ''}{'/'}
                            {/* {this.props.medicalData ? this.props.medicalData.regTitle : ''}{'/'} */}
                            {this.props.medicalData ? this.props.medicalData.dateDetail : ''}
                        </span>
                        <span style={{ marginLeft: 10 }}>排班类型：<Select style={{ width: '150px' }}
                         placeholder='请选择排班类型' value={this.state.regTitleID}
                            onChange={Util.handleSelectChange.bind(this, 'regTitleID')}>{sumDataOption}</Select></span>
                        <span style={{ marginLeft: '10px' }}><span style={{ color: '#f5222d', fontFamily: 'SimSun' }}>*</span>坐诊诊室：
                        <Select placeholder="请选择坐诊诊室" style={{ width: '150px' }}
                                onChange={Util.handleSelectChange.bind(this, 'roomDr')} disabled={this.state.showKey == '1' ? false : true}
                                value={this.state.roomDr ? this.state.roomDr : (this.props.medicalData ? this.props.medicalData.roomID : '')}
                                getPopupContainer={triggerNode => triggerNode.parentNode}>
                                {doctorRoomOption}
                            </Select></span>
                        <Checkbox style={{ marginLeft: 10 }} onChange={this.changeCheckBox.bind(this)} checked={this.state.voluntServiceFlag} />义诊
                    </span>
                    <div>
                        <Tabs defaultActiveKey={this.state.showKey} onChange={this.changeKey.bind(this)}>
                            <TabPane tab="设置号源" key="1">
                                <Table columns={this.columns} style={{ width: '100%' }}
                                    dataSource={this.state.dataSource}
                                    loadData={this.loadData.bind(this)}
                                    bordered
                                    rowKey={(data) => {
                                        return data.id
                                    }}
                                    pagination={false}></Table>
                                <div style={{ marginTop: '20px' }}>
                                    {/* <AddMechanism showBtn={true} data={this.state.data}></AddMechanism> */}
                                </div>
                            </TabPane>
                            <TabPane tab='恢复坐诊' key='2'>
                                <Table columns={this.stopMedical} style={{ width: '100%' }}
                                    dataSource={this.state.newData}
                                    loadData={this.loadData.bind(this)}
                                    bordered
                                    rowKey={(data) => {
                                        return data.id
                                    }}
                                    pagination={false}></Table>
                            </TabPane>
                            <TabPane tab='停诊' key='3'>
                                <Table columns={this.contrColumns} style={{ width: '100%' }}
                                    dataSource={this.state.newData}
                                    loadData={this.loadData.bind(this)}
                                    bordered
                                    rowKey={(data) => {
                                        return data.id
                                    }}
                                    rowClassName={(data) => {
                                        return (data.appointedNum || data.registedNum) > 0 ? 'row-class' : ''
                                    }}
                                    pagination={false}></Table>
                            </TabPane>
                        </Tabs>
                    </div>
                </div>
            </div>
        </Modal>
    }
}

export default Form.create()(ShowStopMedicalModal);