/*
* 编辑排班
* */

import React, { Component } from 'react';
import { Input, Form, Select, Modal, Button, Row, Col, Table, Card, message, Checkbox } 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;

class ShowDepartModal extends Component {

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

    componentWillReceiveProps(nextProp) {
        if (nextProp.isShow === true) {
            this.setState({
                resourceType: nextProp.resourceType,
                resourceTypeID: nextProp.resourceTypeID,
            }, () => {
                this.loadLocResDetail(nextProp.locResDetailId, nextProp.locResModDetailId)
                this.initData()
            })
        } else if (this.props.isShow === false) {
            this.cleanInput();
        }
    }

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

    //获取诊室
    getDoctorRoom() {
        var params = {
            params: [{
                hospitalId: this.state.hospitalId,
                locID: 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, locResModDetailId) {
        var params = {
            params: [{
                locResDetailID: id || '',
                locResModDetailID: locResModDetailId || '',
                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
                    })
                }
            }
        });
    }

    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>{'(已使用' + data.registedNum + ')'}</span>
                    </span>
                }
            }, {
                title: '新号源',
                dataIndex: 'newNum',
                width: 120,
                align: 'center',
                render: (text, data, index) => {
                    return <Input placeholder='请输入新号源' 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>{'(已使用' + data.appointedNum + ')'}</span>
                    </span>
                }
            }, {
                title: '新预约挂号数',
                dataIndex: 'newRegNum',
                width: 120,
                align: 'center',
                render: (text, data, index) => {
                    return <Input placeholder='请输入新预约挂号数' onChange={this.changeRegNum.bind(this, text, data, index)}
                        style={{ width: '80' }} />
                }
            },
        ]
    }

    loadData() {

    }

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

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

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

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

    //提交
    onSubmit() {
        let { validateFields } = this.props.form;
        validateFields({ force: true }, (err, params) => {
            if (err) {
                return;
            }
            let { onSubmit } = this.props;
            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,
                resourceTypeID: this.state.resourceTypeID,
                params: this.state.dataSource,
                locResDetailID: this.props.locResDetailId || '',
                locResModDetailID: this.props.locResModDetailId || '',
                voluntServiceFlag: this.state.voluntServiceFlag ? 'Y' : 'N',
                roomID: this.state.roomDr ? this.state.roomDr : (this.props.modalData ? this.props.modalData.roomID : '')
            }

            onSubmit && onSubmit(params);
        });
    }

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

    render() {
        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>)
        })
        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.modalData ? this.props.modalData.userName : ''}{'/'}
                            {this.props.modalData ? this.props.modalData.regTitle : ''}{'/'}
                            {this.props.modalData ? this.props.modalData.dateDetail : ''}
                        </span>
                        {/* <span>医生：{this.props.modalData ? this.props.modalData.userName : ''}</span>
                        <span style={{ marginLeft: '10px' }}>排班类型：{this.props.modalData ? this.props.modalData.regTitle : ''}</span>
                        <span style={{ marginLeft: '10px' }}>坐诊时间：{this.props.modalData ? this.props.modalData.dateDetail : ''}</span> */}
                        <span style={{ marginLeft: '10px' }}>坐诊诊室：<Select placeholder="请选择坐诊诊室" style={{ width: '150px' }}
                            onChange={Util.handleSelectChange.bind(this, 'roomDr')}
                            defaultValue={this.props.modalData ? this.props.modalData.roomID : ''}
                            getPopupContainer={triggerNode => triggerNode.parentNode}>
                            {doctorRoomOption}
                        </Select></span>
                        <Checkbox style={{ marginLeft: 10 }} onChange={this.changeCheckBox.bind(this)} />义诊
                    </span>
                    <div>
                        <Table columns={this.columns} style={{ width: '100%', height: 200 }}
                            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>
                    </div>
                </div>
            </div>
        </Modal>
    }
}

export default Form.create()(ShowDepartModal);