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

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

class AddDoctor extends React.Component {
    constructor(props) {
        super(props)
        var userData = JSON.parse(sessionStorage.getItem('userData'))
        this.state = {
            data: [],
            hospitalData: [],
            departmentData: [],
            doctorData: [],
            sumData: [],
            doctorRoom: [],
            userData: userData,
            newAmTimeData: [],
            newPmTimeData: [],
            bookMethodDetail: []
        }
    }

    componentDidMount() {
        var editData = JSON.parse(sessionStorage.getItem('editData'));
        this.loadHospitalMsg();
        this.getDepartment();//获取科室
        this.loadscheduType();
        this.getDoctor();//获取坐诊医生
        this.getDoctorRoom();//获取诊室
        // if (editData) {
        //     this.getModelDetail(editData.regTitleId);
        // }
    }

    //取地址栏传过来的数据
    getQueryString(name) {
        var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
        var r = this.props.location.search.substr(1).match(reg);
        if (r != null) {
            return decodeURIComponent(r[2]);
        }
        return null;
    }

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

    getDepartment() {
        $http.post('urlS', this, {
            code: "01040009",
            data: [],
            success: function (res) {
                if (res.errorCode === '0') {
                    this.setState({ departmentData: res.loc })
                }
            }
        })
    }

    //获取坐诊类型
    loadscheduType() {
        var params = {
            params: [
                { hospitalId: this.state.hospitalId }
            ],
            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,
                    })
                }
            }
        });
    }

    //获取坐诊医生
    getDoctor() {
        var params = {
            params: [{
                locId: this.state.departId,
            }]
        }
        $http.post('urlDeault', this, {
            code: "03010002",
            data: params,
            success: function (res) {
                if (res.errorCode === '0') {
                    this.setState({
                        doctorData: res.depDoctor
                    })
                }
            }
        });
    }

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

    changeDoctorList(name) {
        if (name == '3') {
            var params = {
                params: [{
                    regTitleId: '18',//暂时写死
                    "locId": ''
                }],
                "pagination": [{
                    "pageSize": 10,
                    "currentPage": 1
                }]
            }
            $http.post('urlDeault', this, {
                code: "03020026",
                data: params,
                success: function (res) {
                    if (res.errorCode === '0') {
                        this.setState({
                            ordinaryData: res.result.Data
                        })
                    }
                }
            });
        }
    }

    //获取模板详情信息
    getModelDetail(regTitleId) {
        var editData = JSON.parse(sessionStorage.getItem('editData'));
        var params = {
            params: [{
                regTitleId: regTitleId,
                deptDoctorId: this.state.deptDoctorId,
                hospId: this.state.hospitalId
            }]
        }
        $http.post('urlDeault', this, {
            code: "03020027",
            data: params,
            success: function (res) {
                if (res.errorCode === '0') {
                    var modelData = res.modelDetail;
                    if (modelData) {
                        for (var i = 0; i < modelData.length; i++) {
                            if (modelData[i].timeRangId == '1') {
                                this.setState({//获取上午开放号源
                                    amTimeRangData: modelData[i].timeRangDetail,
                                    amTimeId: modelData[i].timeRangId,
                                    amModelId: modelData[i].modelId
                                })
                            } else if (modelData[i].timeRangId == '2') {
                                this.setState({//获取下午开放号源
                                    pmTimeRangData: modelData[i].timeRangDetail,
                                    pmTimeId: modelData[i].timeRangId,
                                    pmModelId: modelData[i].modelId
                                })
                            }
                        }
                    }
                    this.setState({
                        modelDetail: res.modelDetail,
                        bookMethodDetail: res.bookMethodDetail
                    })
                }
            }
        });
    }

    //获取所有医生列表
    getDoctorList() {
        var doctorOption = []
        this.state.doctorData.map((item, index) => {
            doctorOption.push(<p className='borderStyle' key={index} value={item.ID + ''}>
                <span style={{ marginRight: '10%' }}>{item.Descripts}</span>
                <span style={{ marginRight: '45%' }}>{item.Title}</span>
            </p>)
        })
        return doctorOption;
    }

    //获取普通门诊医生
    getOrdinaryList() {
        var ordinaryList = []
        this.state.ordinaryData && this.state.ordinaryData.map((item, index) => {
            ordinaryList.push(<p className='borderStyle' key={index} value={item.id + ''}>
                <span style={{ marginRight: '10%' }}>{item.descripts}</span>
                <span style={{ marginRight: '45%' }}>{item.title}</span>
            </p>)
        })
        return ordinaryList;
    }

    //当切换坐诊类型后，当医院和坐诊类型ID不为空，调用取时间段接口
    handleSelectChange(e) {
        if (e && this.state.hospitalId) {
            this.setState({
                regTitleId: e
            })
            this.getModelDetail(e)
        }
    }

    changePmRegistNum(e, num, index) {
        var { pmTimeRangData, newPmTimeData } = this.state;
        for (var i = 0; i < pmTimeRangData.length; i++) {
            if (index == i && num == pmTimeRangData[i].indexId) {
                this.state.newPmTimeData.push({
                    methodFlag: "insert",
                    AppointNum: e,//新增号源
                    RegistNum: e,//限制号源
                    TimeDetailDr: pmTimeRangData[i].indexId,//时段详情id
                    CreateUserDr: this.state.userData.userId,
                    modelId: this.state.pmModelId,//时段id
                })
            }
        }
    }

    //获取上午输入的号源
    changeAmRegistNum(e, num, index) {
        var { amTimeRangData, newAmTimeData } = this.state;
        // this.setState({
        //     appointNum: e.target.value,
        //     registNum: e.target.value,
        // })
        for (var i = 0; i < amTimeRangData.length; i++) {
            if (index == i && num == amTimeRangData[i].indexId) {
                this.state.newAmTimeData.push({
                    methodFlag: "insert",
                    AppointNum: e,//新增号源
                    RegistNum: e,//限制号源
                    TimeDetailDr: amTimeRangData[i].indexId,//时段详情id
                    CreateUserDr: this.state.userData.userId,
                    modelId: this.state.amModelId,//时段id
                })
            }
        }
    }

    onSubmit(data, status) {


        var { doctorDta, resModel, newData } = this.state;
        var dataSource = []
        console.dir(this.state.newData)
        var test = []
        var a = {}
        for (var i = 0; i < resModel.length; i++) {
            if (this.state.newData[i]) {
                for (var j = 0; j < newData[i].length; j++) {
                    dataSource.push({
                        timeDetailDr: newData[i][j].indexId,
                        registNum: newData[i][j].registNum,
                        appointNum: newData[i][j].appointNum,
                        createUserDr: this.state.userData.userId,
                    })
                }
            }
            test.push({
                detpDoctorDr: doctorDta.detpDoctorDr,//医生ID
                sessionTypeDr: this.state.sessionTypeDr,//排班类型
                "timeRangeDr": resModel[i].timeRangId,//时段  上午/下午
                "registNum": 100,//总挂号限额
                "appointNum": 100,//预约限额
                "addNum": "",//空
                roomDr: this.state.roomDr,//诊室ID
                expertiseDr: "",//专长
                togetherSource: "",//空
                timeIntervalDr: "17",//间隔ID
                createUserDr: this.state.userData.userId,
                detail: this.state.dataSource
            })
        }
        console.dir(test)
        var params = {
            // params:[
            //     {
            //         detpDoctorDr: doctorDta.detpDoctorDr,//医生ID
            //         sessionTypeDr: this.state.sessionTypeDr,//排班类型
            //         "timeRangeDr": 1,//时段  上午/下午
            //         "registNum": 100,//总挂号限额
            //         "appointNum": 100,//预约限额
            //         "addNum": "",//空
            //         roomDr: this.state.roomDr,//诊室ID
            //         expertiseDr: "",//专长
            //         togetherSource: "",//空
            //         timeIntervalDr: "17",//间隔ID
            //         createUserDr: this.state.userData.userId,
            //     }
            // ]
            params: test
        }



        var amTimeData = [];
        var pmTimeData = [];
        var { modelDetail } = this.state;
        if (data) {//先判断获取子组件传过来的数据不会空，防止报错
            for (var i = 0; i < data.length; i++) {
                if (data[i].TimeRangName == '上午') {//业务特殊需求，根据名字判断
                    amTimeData.push(data[i])
                } else if (data[i].TimeRangName == '下午') {
                    pmTimeData.push(data[i])
                }
            }
        }
        //获取编辑排版医生模板数据
        var editData = JSON.parse(sessionStorage.getItem('editData'));
        var params = {
            params: [
                {
                    methodFlag: status == 'save' ? 'insert' : "insert",//保存 || 添加
                    DetpDoctorDr: this.state.deptDoctorId,//医生ID
                    SessionTypeDr: this.state.regTitleId,//坐诊类型
                    TimeRangeDr: this.state.amTimeId,//上午
                    RegistNum: '100',
                    AppointNum: '100',
                    AddNum: '1',//写死
                    TRFlag: 'Y',
                    RoomDr: this.state.RoomDr,
                    CreateUserDr: this.state.userData.userId,
                    UpdateUserDr: this.state.userData.userId,
                    detail: this.state.newAmTimeData,
                    method: amTimeData
                },
                {
                    methodFlag: status == 'save' ? 'insert' : "insert",//保存 || 添加
                    DetpDoctorDr: this.state.deptDoctorId,//医生ID
                    SessionTypeDr: this.state.regTitleId,//坐诊类型
                    TimeRangeDr: this.state.pmTimeId,//下午
                    RegistNum: '100',
                    AppointNum: '100',
                    AddNum: '1',//写死
                    TRFlag: 'Y',
                    RoomDr: this.state.RoomDr,
                    CreateUserDr: this.state.userData.userId,
                    UpdateUserDr: this.state.userData.userId,
                    detail: this.state.newPmTimeData ? this.state.newPmTimeData : [],
                    method: pmTimeData
                },
            ]
        }

        $http.post('urlDeault', this, {
            code: "03020014",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    message.success('保存成功！')
                }
            }
        });
    }

    render() {
        let { getFieldDecorator } = this.props.form;
        let formItemLayout = {
            labelCol: { span: 5 },
            wrapperCol: { span: 19 }
        };

        let formItemCol = {
            labelCol: { span: 6 },
            wrapperCol: { span: 23 }
        };

        let searchColConfig = {
            xs: { span: 24 },
            sm: { span: 12 },
            md: { span: 13 },
            lg: { span: 12 }
        }

        //所属医院参数
        let hospitalOption = [];
        this.state.hospitalData.map((item, index) => {
            hospitalOption.push(<Option key={index} value={item.id + ''}>{item.descripts}</Option>)
        })
        //获取科室Department
        let departmentOption = [];
        this.state.departmentData.map((item, index) => {
            departmentOption.push(<Option key={index} value={item.id + ''}>{item.descripts}</Option>)
        })

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

        //坐诊医生
        let doctorOption = []
        this.state.doctorData.map((item, index) => {
            doctorOption.push(<Option key={index} value={item.DeptDoctorId + ''}>{item.Descripts}</Option>)
        })

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

        var { modelDetail, amTimeRangData, pmTimeRangData, newAmTimeData, newPmTimeData } = this.state;
        var amTimeRangList = []//上午号源
        var pmTimeRangList = []//下午号源
        var modelDetailData = []//总开放号源

        var count = 0;
        for (var i = 0; i < newAmTimeData.length; i++) {
            count += parseInt(newAmTimeData[i].appointNum);
        }

        

        //时段间隔
        let resModelDetailOption = []
        this.state.resModelDetail && this.state.resModelDetail.map((item, index) => {
            resModelDetailOption.push(
                <span className='schedulingNo'>
                    <div>{item.timeRangDetail}</div>
                    <div>
                        <InputGroup compact style={{ width: '140px' }}>
                            <Input placeholder='号源数' style={{ width: '65px' }} value={item.registNum} />
                            <Input placeholder='可预约数' style={{ width: '65px' }} value={item.appointNum} />
                        </InputGroup>
                    </div>
                </span>
            )
        })

        //获取编辑排版医生模板数据
        var editData = JSON.parse(sessionStorage.getItem('editData'));

        //将获取的上午时间段，push到对应的位置
        amTimeRangData && amTimeRangData.map((item, index) => {
            amTimeRangList.push(
                <span className='schedulingNo'>
                    <div>{item.timeRangDetail}</div>
                    <div><Input onBlur={(e) => this.changeAmRegistNum(e.target.value, item.indexId, index)}
                        placeholder='号源' style={{ width: 80 }} key={index} /></div>
                </span>
            )
        })
        //将获取的下午时间段，push到对应的位置
        pmTimeRangData && pmTimeRangData.map((item, index) => {
            pmTimeRangList.push(
                <span className='schedulingNo'>
                    <div>{item.timeRangDetail}</div>
                    <div><Input onBlur={(e) => this.changePmRegistNum(e.target.value, item.indexId, index)}
                        placeholder='号源' style={{ width: 80 }} key={index + '_1'} /></div>
                </span>
            )
        })
        //获取总的号源时间段，push到对应的位置
        modelDetail && modelDetail.map((item, index) => {
            modelDetailData.push(
                <FormItem {...formItemCol} label={
                    <span>
                        <span key={index}>开放号源({item.timeRang})</span>
                        <span key={index + '-1'}>总计&nbsp;&nbsp;{count || '0'} </span>
                    </span>}>
                    {getFieldDecorator('5', {
                        initialValue: this.state.inputData,
                    })(
                        <Row>
                            <Col>
                                <span>
                                    {item.timeRangId == '1' ? <span key={index + '-2'}>{amTimeRangList}</span> : null}
                                    {item.timeRangId == '2' ? <span key={index + '-3'}>{pmTimeRangList}</span> : null}
                                </span>
                            </Col>
                        </Row>
                    )}
                </FormItem>
            )
        })

        return (
            <div className='addDoctorBody'>             
                <Card className='leftCard' gutter={0}>
                    <div className='leftCardHeader'>
                        <Tabs defaultActiveKey="1" size='small' onChange={this.changeDoctorList.bind(this)}>
                            <TabPane tab="医生列表" key="1">{this.getDoctorList()}</TabPane>
                            <TabPane tab="专家门诊" key="2"></TabPane>
                            <TabPane tab="普通门诊" key="3">{this.getOrdinaryList()}</TabPane>
                        </Tabs>
                    </div>
                </Card>
                <Card className='rightCard'>
                    <Form>
                        <Row gutter={10}>
                            <Col {...searchColConfig}>
                                <FormItem {...formItemLayout} label="所属医院">
                                    {getFieldDecorator('hospital', {
                                        initialValue: editData ? editData.hospDescripts : this.state.hospital,
                                        rules: [{ required: true, message: '所属平台不能为空' }],
                                    })(
                                        <Select placeholder="请选择所属医院" style={{ width: '150px' }}
                                            disabled={this.getQueryString('moduleId') == '1'}
                                            onChange={Util.handleSelectChange.bind(this, 'hospitalId')}
                                            getPopupContainer={triggerNode => triggerNode.parentNode}>
                                            {hospitalOption}
                                        </Select>
                                    )}
                                </FormItem>
                            </Col>

                            <Col {...searchColConfig}>
                                <FormItem {...formItemLayout} label="所属科室">
                                    {getFieldDecorator('1', {
                                        initialValue: editData ? editData.locDescripts : this.state.locDescripts,
                                        rules: [{ required: true, message: '所属科室不能为空' }],
                                    })(
                                        <Select placeholder="请选择所属科室" style={{ width: '150px' }}
                                            disabled={this.getQueryString('moduleId') == '1'}
                                            getPopupContainer={triggerNode => triggerNode.parentNode}>
                                            {departmentOption}
                                        </Select>
                                    )}
                                </FormItem>
                            </Col>
                            <Col {...searchColConfig}>
                                <FormItem {...formItemLayout} label="坐诊医生">
                                    {getFieldDecorator('2', {
                                        initialValue: editData ? editData.descripts : this.state.descripts,
                                        rules: [{ required: true, message: '坐诊医生不能为空' }],
                                    })(
                                        <Select placeholder="请选择坐诊医生" style={{ width: '150px' }}
                                            disabled={this.getQueryString('moduleId') == '1'}
                                            onChange={Util.handleSelectChange.bind(this, 'deptDoctorId')}
                                            getPopupContainer={triggerNode => triggerNode.parentNode}>
                                            {doctorOption}
                                        </Select>
                                    )}
                                </FormItem>
                            </Col>

                            <Col {...searchColConfig}>
                                <FormItem {...formItemLayout} label="坐诊类型">
                                    {getFieldDecorator('3', {
                                        initialValue: editData ? editData.sessionType : this.state.sessionType,
                                        rules: [{ required: true, message: '坐诊类型不能为空' }],
                                    })(
                                        <Select placeholder="请选择坐诊类型" style={{ width: '150px' }}
                                            disabled={this.getQueryString('moduleId') == '1'}
                                            onChange={this.handleSelectChange.bind(this)}
                                            getPopupContainer={triggerNode => triggerNode.parentNode}>
                                            {sumDataOption}
                                        </Select>
                                    )}
                                </FormItem>
                            </Col>
                            <Col {...searchColConfig}>
                                <FormItem {...formItemLayout} label="坐诊诊室">
                                    {getFieldDecorator('4', {
                                        initialValue: this.state.hospital,
                                        rules: [{ required: true, message: '坐诊诊室不能为空' }],
                                    })(
                                        <Select placeholder="请选择坐诊诊室" style={{ width: '150px' }}
                                            onChange={Util.handleSelectChange.bind(this, 'RoomDr')}
                                            getPopupContainer={triggerNode => triggerNode.parentNode}>
                                            {doctorRoomOption}
                                        </Select>
                                    )}
                                </FormItem>
                            </Col>
                        </Row>
                        {modelDetailData}
                        <Row>
                            <AddMechanism onSubmit={this.onSubmit.bind(this)}
                                bookMethodDetail={this.state.bookMethodDetail}
                                deptDoctorId={this.state.deptDoctorId}
                                regTitleId={this.state.regTitleId}
                                modelDetail={this.state.modelDetail}>
                            </AddMechanism>
                        </Row>
                    </Form>
                </Card>
            </div >
        )
    }
}

export default Form.create()(AddDoctor);