/**
 * 新建治疗申请
 */
import React from 'react';
import {
    Modal, Row, Col, Select, Card, Radio, Input, Button, Tree, Icon, Tag, Table,
    Divider, message, DatePicker
} from 'antd';
import { Util, dayFormat, timeFormat } from 'tools/index';
import { $http } from 'containers/config/https';
import ReadCard from 'components/readcard/ReadCard';
import '../style/index.less';
import moment from 'moment';

const Option = Select.Option;
const confirm = Modal.confirm;
const Search = Input.Search;
const RadioGroup = Radio.Group;
const { TextArea } = Input;

class ShowNewApplicationModal extends React.Component {

    constructor(props) {
        super(props);
        var userData = JSON.parse(sessionStorage.getItem('userData'));
        var date = new Date()
        this.state = {
            userData: userData,
            radioValue: '1',
            ids: [],
            dataSource: [],
            dateTime: moment(date).format(dayFormat),
            bookScheduleID: [],
            projectNum: 1
        }
    }
    componentWillReceiveProps(nextProp) {
        if (nextProp.isShow === true) {
            this.loadCardType()
            this.initData()
        } else if (this.props.isShow === false) {
            this.clearInput()
        }
    }

    initData() {
        let data = {
            params: [{
                type: "C",
                reactCode: ['ShowNewApplicationModal']
            }]
        }
        $http.post('urlDeault', this, {
            code: "01040073",
            data: data,
            success: (res) => {
                if (+res.errorCode === 0) {
                    this.setState({
                        localeProvider: this.state.userData.language == 'EN' ? res.result.language.EN : res.result.language.CN
                    })
                }
            }
        })
    }

    //国际化
    setMessage(name, message) {
        return this.state.localeProvider && this.state.localeProvider[name] ? this.state.localeProvider[name][message] : ''
    }

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

    clearInput() {
        this.setState({
            doctorList: [],
            appProgram: [],
            patientMsg: '',
            timeRangeId: undefined,
            doctorID: undefined,
            admID: undefined,
            bookScheduleID: [],
            projectNum: 1,
            treatmentPlan: undefined,
            treatmentGoals: undefined,
            number: undefined,
            medItemID: '',
            programPrice: undefined,
            admReasonID: undefined,
            ordFreqID: undefined,
            ordDurQty: undefined,
            ordDose: undefined,
            admReason: [],
            freList: []
        })
    }

    handleReadCard() {
        var cardType = this.state.carTypeDr ? this.state.carTypeDr : (this.state.cardStatus);
        this.readCard.ReadCard(cardType, "R", (json) => {
            this.setState({ readPatID: json && json.patInfo ? json.patInfo.patID : '', patCardNo: json.cardNo, readStatus: 'read' }, () => {
                this.loadData()
            })
        })
    }
    //切换卡类型
    changeCardType(name, e) {
        var { cardTypeData } = this.state;
        for (var i = 0; i < cardTypeData.length; i++) {
            if (e == cardTypeData[i].id) {
                this.setState({
                    cardLength: cardTypeData[i].cardLength,
                    replaceZero: cardTypeData[i].replenishZero,
                    cardTypeId: cardTypeData[i].id,
                    readMode: cardTypeData[i].readMode,
                    [name]: e,
                    inputStatus: true
                })
            }
        }
    }

    //获取卡类型
    loadCardType() {
        var params = {
            params: [{
                cardTypeFlag: '1',//卡类型
                patTypeFlag: '1',
            }]
        }
        $http.post('urlDeault', this, {
            code: "03030005",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    var cardStatus = ''
                    var replaceZero = ''
                    var cardLength = 0
                    var readMode = ''
                    if (res.cardType && res.cardType.length > 0) {
                        var cardType = res.cardType;
                        for (var i = 0; i < cardType.length; i++) {
                            if (cardType[i].defaultFlag == 'Y') {
                                cardStatus = cardType[i].id,
                                    replaceZero = cardType[i].replenishZero
                                cardLength = cardType[i].cardLength
                                readMode = cardType[i].readMode
                            }
                        }
                    }
                    this.setState({
                        cardTypeData: res.cardType,
                        credTypeData: res.credType,
                        patTypeData: res.patType,
                        sexData: res.sex,
                        socialStatusData: res.patSocialStatusDesc,
                        cardStatus: cardStatus,
                        readMode: readMode,
                        cardLength: cardLength,
                        replaceZero: replaceZero,
                    })
                }
            }
        });
    }

    loadEnterData(e) {
        if (e.keyCode == '13') {
            this.searchBuildCardMsg()
        }
    }

    //获取建卡后跳转过来信息
    searchBuildCardMsg() {
        var params = {
            params: [{
                number: this.state.number,
                cardTypeID: this.state.carTypeDr ? this.state.carTypeDr : (this.state.cardStatus),
                cardNo: this.state.cardNo
            }]
        }
        $http.post('urlDeault', this, {
            code: "03040004",
            data: params,
            success: function (res) {
                if (res.errorCode === '0') {
                    var data = []
                    var admReasonID = ''
                    if (!Util.isEmpty(res.data)) {
                        data = res.data.admReason
                        for (var i = 0; i < data.length; i++) {
                            if (data[i].defaultFlag == 'Y') {
                                admReasonID = data[i].id
                            }
                        }
                    }
                    this.setState({
                        patientMsg: res.data,
                        admReason: res.data.admReason,
                        admReasonID: !Util.isEmpty(admReasonID) ? admReasonID : ((res.data && res.data.admReason) ? res.data.admReason[0].id : '')
                    })
                }
            }
        });
    }

    changeScheduling(e) {
        var { appProgram } = this.state;
        var price = ''
        var freList = []
        if (!Util.isEmpty(appProgram)) {
            for (var i = 0; i < appProgram.length; i++) {
                if (e == appProgram[i].medItemID) {
                    price = appProgram[i].price
                    freList = appProgram[i].freList
                }
            }
        }
        this.setState({
            medItemID: e,
            programPrice: price,
            freList: freList
        })
    }

    //获取医生排班信息
    loadScheduling() {
        var params = {
            params: [{
                cureAppID: this.state.cureAppID,
                timeRangeID: this.state.timeRangeId,
                doctorID: this.state.doctorID,
                medicalNo: this.state.medicalNo,
                date: this.state.dateTime,
                locID: this.state.userData.locID,
                hospID: this.state.userData.hospID,
                medItemID: this.state.medItemID
            }]
        }
        $http.post('urlDeault', this, {
            code: "03050166",
            data: params,
            success: function (res) {
                if (res.errorCode === '0') {
                    this.setState({
                        doctorList: res.result.data
                    })
                }
            }
        });
    }

    handleSearch(value) {
        if (value.length >= 2) {
            this.loadApplicationProgram(value)
        }
    }

    loadApplicationProgram(value) {
        var params = {
            params: [{
                searchCode: value,
                admReasonID: this.state.admReasonID
            }]
        }
        $http.post('urlDeault', this, {
            code: "03050171",
            data: params,
            success: function (res) {
                if (res.errorCode === '0') {
                    this.setState({
                        appProgram: res.result.data
                    })
                }
            }
        });
    }

    onSubmit() {
        // if (Util.isEmpty(this.state.patientMsg)) {
        //     message.error('请先录入病人信息！')
        //     return
        // }
        var params = {
            params: [{
                admID: this.state.admID,
                resDetailID: this.state.resDetailID,
                medItemID: this.state.medItemID,
                patID: this.state.patientMsg ? this.state.patientMsg.patID : '',
                projectNum: this.state.projectNum,
                treatmentPlan: this.state.treatmentPlan,
                treatmentGoals: this.state.treatmentGoals,
                admReasonID: this.state.admReasonID,
                ordFreqID: this.state.ordFreqID,
                ordDurQty: this.state.ordDurQty,
                ordDose: this.state.ordDose,
            }]
        }
        var { onSubmit } = this.props;
        onSubmit && onSubmit(params)
    }

    //projectNum计算项目数量
    handleSelectChange(name, e, code) {
        var totalSum = 0;
        var intervalDays = code.props.intervalDays;
        var frequency = code.props.frequency;
        var cycleDays = code.props.cycleDays;
        if (Util.isEmpty(cycleDays) || cycleDays == 0) {
            totalSum = Math.ceil(frequency / intervalDays * (this.state.ordDurQty || 1)) * (this.state.ordDose || 1)
        } else if (!Util.isEmpty(cycleDays) && cycleDays !== 0) {
            totalSum = Math.ceil(frequency / cycleDays * (this.state.ordDurQty || 1)) * (this.state.ordDose || 1)
        }
        this.setState({
            [name]: e,
            projectNum: totalSum,
            intervalDays: intervalDays,
            frequency: frequency,
            cycleDays: cycleDays
        })
    }

    commonInputChange(name, e) {
        var value = e.target.value
        var reg = /[^0-9]/g
        if (reg.test(value)) {
            message.error(this.setMessage('ShowNewApplicationModalallowed', 'descripts'))
            return
        }
        if (name == 'ordDurQty') {
            var totalSum = 0;
            var intervalDays = this.state.intervalDays;
            var frequency = this.state.frequency;
            var cycleDays = this.state.cycleDays;
            if (Util.isEmpty(cycleDays) || cycleDays == 0) {
                totalSum = Math.ceil(frequency / intervalDays * (value || 1)) * (this.state.ordDose || 1)
            } else if (!Util.isEmpty(cycleDays) && cycleDays !== 0) {
                totalSum = Math.ceil(frequency / cycleDays * (value || 1)) * (this.state.ordDose || 1)
            }
            this.setState({
                [name]: value,
                projectNum: totalSum
            })
        } else if (name == 'ordDose') {
            var totalSum = 0;
            var intervalDays = this.state.intervalDays;
            var frequency = this.state.frequency;
            var cycleDays = this.state.cycleDays;
            if (Util.isEmpty(cycleDays) || cycleDays == 0) {
                totalSum = Math.ceil(frequency / intervalDays * (this.state.ordDurQty || 1)) * (value || 1)
            } else if (!Util.isEmpty(cycleDays) && cycleDays !== 0) {
                totalSum = Math.ceil(frequency / cycleDays * (this.state.ordDurQty || 1)) * (value || 1)
            }
            this.setState({
                [name]: value,
                projectNum: totalSum
            })
        } else {
            this.setState({
                [name]: value,
            })
        }
    }

    render() {
        var { doctorList, bookScheduleID } = this.state;
        //卡类型
        let cardTypeOption = []
        this.state.cardTypeData && this.state.cardTypeData.map((item, index) => {
            cardTypeOption.push(<Option key={index} value={item.id} code={item.descripts}>{item.descripts}</Option>)
        })

        //坐诊医生
        let doctorOption = []
        this.state.doctorData && this.state.doctorData.map((item, index) => {
            doctorOption.push(<Option key={index} value={item.id} code={item.descriptsSPCode} name={item.descripts}>
                {item.descripts}</Option>)
        })

        let timeRangeOption = []
        this.state.timeRange && this.state.timeRange.map((item, index) => {
            timeRangeOption.push(<Option key={index} value={item.id}>{item.descripts}</Option>)
        })
        //申请单项目
        let appProgramOption = []
        this.state.appProgram && this.state.appProgram.map((item, index) => {
            appProgramOption.push(<Option key={index} value={item.medItemID}>{item.medItemDesc}</Option>)
        })
        //结算类型admReason
        let admReasonOption = []
        this.state.admReason && this.state.admReason.map((item, index) => {
            admReasonOption.push(<Option key={index} value={item.id}>{item.descripts}</Option>)
        })

        //频次
        let freListOption = []
        this.state.freList && this.state.freList.map((item, index) => {
            freListOption.push(<Option key={index} value={item.id} code={item.code} name={item.descripts} cycleDays={item.cycleDays}
                disp={item.descriptsSPCode} intervalDays={item.intervalDays} frequency={item.frequency}>{item.descripts}</Option>)
        })

        return <div className='show-application-modal'>
            <ReadCard ref={ref => this.readCard = ref}></ReadCard>
            <Modal className='show-new-application-moadl'
                title={this.setMessage('ShowNewApplicationModalapplication', 'descripts')}
                maskClosable={false}
                visible={this.props.isShow}
                onOk={this.onSubmit.bind(this)}
                okText={this.state.userData.language == 'EN' ? 'Save' : '保存'}
                onCancel={this.closeModal.bind(this)}>
                <div style={{ width: '100%' }}>
                    <Card title={<span>{this.setMessage('ShowNewApplicationModalpatients', 'descripts')}</span>}>
                        <Row style={{ width: '50%', float: 'left' }}>
                            <Col style={{ marginLeft: 5, marginTop: 5 }}>
                                {this.setMessage('ShowNewApplicationModalCard', 'descripts')}<Select style={{ width: '100px' }} placeholder='请选择卡类型'
                                    allowClear showSearch
                                    value={this.state.carTypeDr ? this.state.carTypeDr : (this.state.cardStatus)}
                                    filterOption={(input, option) =>
                                        option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                        || option.props.code.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                    }
                                    getPopupContainer={triggerNode => triggerNode.parentNode}
                                    onChange={this.changeCardType.bind(this, 'carTypeDr')}>
                                    {cardTypeOption}
                                </Select>
                                <Search className={this.state.readMode == 'R' ? 'disable-input-title' : ''}
                                    placeholder={this.setMessage('ShowNewApplicationModalread', 'descripts')} style={{ width: '56%', marginLeft: 10 }}
                                    onChange={Util.commonInputChange.bind(this, 'cardNo')}
                                    value={this.state.cardNo}
                                    enterButton={this.setMessage('ShowNewApplicationModalCall', 'descripts')}
                                    readOnly={this.state.readMode == 'R' ? true : false}
                                    onPressEnter={(e) => console.dir(e)}
                                    onKeyDown={this.loadEnterData.bind(this)}
                                    onSearch={this.handleReadCard.bind(this)}
                                />
                            </Col>
                            <Col style={{ marginLeft: 5, marginTop: 5 }} span={14}>
                                {this.setMessage('ShowNewApplicationModalIdentity', 'descripts')}<Input onChange={Util.commonInputChange.bind(this, 'number')} allowClear={true}
                                    value={this.state.number}
                                    onKeyDown={this.loadEnterData.bind(this)}
                                    placeholder={this.setMessage('ShowNewApplicationModalnumber', 'descripts')} style={{ width: '70%' }} />
                            </Col>

                            <Col style={{ marginLeft: 5, marginTop: 5 }} span={9}>
                                {this.setMessage('ShowNewApplicationModalhospital', 'descripts')}
                                <Input placeholder={this.setMessage('ShowNewApplicationModalinput', 'descripts')} style={{ width: '65%' }} />
                            </Col>
                        </Row>

                        <Row style={{ width: '49.8%', float: 'right' }}>
                            <div style={{ height: 80, background: '#F6FCF9', textAlign: 'center', marginTop: 5 }}>
                                <div style={{ height: 79, display: 'flex', float: 'left' }}>
                                    <div className={this.state.patientMsg && this.state.patientMsg.patSexCode == '1' ?
                                        'splice-boy' : (this.state.patientMsg && this.state.patientMsg.patSexCode == '2' ? 'splice-girl' : 'splice-other')}></div>
                                    <div style={{ height: 79, borderRight: '1px solid #EEEEEE' }}></div>
                                    {!Util.isEmpty(this.state.patientMsg) ? <div style={{ fontSize: '16px' }}>
                                        <div style={{ padding: '10px 0 0 10px' }}>
                                            <span style={{ color: '#333333', fontWeight: 'bold' }}>{this.state.patientMsg ? this.state.patientMsg.patName || '--' : '--'}</span><Divider type="vertical" />
                                            <span>{this.state.patientMsg ? this.state.patientMsg.patSexDesc || '--' : '--'}</span><Divider type="vertical" />
                                            <span>{this.state.patientMsg ? this.state.patientMsg.patAge || '--' : '--'}</span><Divider type="vertical" />
                                            <span><Icon className='patNo-splice' />{this.state.patientMsg ? this.state.patientMsg.patNo || '--' : '--'}</span>
                                        </div>
                                        <div style={{ fontWeight: 400, color: '#666666', fontSize: '16px', padding: '10px 0 0 10px' }}>
                                            <span><Icon className='statusdesc-splice' />{this.state.patientMsg ? this.state.patientMsg.patSocialStatusDesc || '--' : '--'}</span><Divider type="vertical" />
                                            <span><Icon className='typeDesc-splice' />{this.state.patientMsg ? this.state.patientMsg.patTypeDesc || '--' : '--'}</span><Divider type="vertical" />
                                            <span>
                                                <span style={{ color: '#1999db' }}><Icon className='account-splice' />{this.state.patientMsg ? this.state.patientMsg.accountBalance || '--' : 0}</span> </span>
                                        </div>
                                    </div> : <span style={{ color: '#999999', lineHeight: '79px' }}>{this.setMessage('ShowNewApplicationModaldata', 'descripts')}</span>}
                                </div>
                            </div>
                        </Row>
                    </Card>

                    <Card title={this.setMessage('ShowNewApplicationModalentry', 'descripts')} style={{ marginTop: '5px' }}>
                        <Row>
                            <Col span={6}>
                                {this.setMessage('ShowNewApplicationModalSettlement', 'descripts')}
                                <Select placeholder={this.setMessage('ShowNewApplicationModalsettlements', 'descripts')} style={{ width: '65%' }}
                                    value={this.state.admReasonID} onChange={Util.handleSelectChange.bind(this, 'admReasonID')}>
                                    {admReasonOption}
                                </Select>
                            </Col>
                            <Col span={7}>
                                {this.setMessage('ShowNewApplicationModalApplications', 'descripts')}
                                <Select placeholder={this.setMessage('ShowNewApplicationModalitems', 'descripts')} style={{ width: '70%' }} showSearch
                                    onSearch={this.handleSearch.bind(this)}
                                    defaultActiveFirstOption={false}
                                    showArrow={false} value={this.state.medItemID}
                                    filterOption={false}
                                    onChange={this.changeScheduling.bind(this)}>{appProgramOption}</Select>
                            </Col>
                            <Col span={4}>
                                {this.setMessage('ShowNewApplicationModalnum', 'descripts')}
                                <Input placeholder={this.setMessage('ShowNewApplicationModalthe', 'descripts')} style={{ width: '50%' }} value={this.state.projectNum}
                                    onChange={this.commonInputChange.bind(this, 'projectNum')} />
                            </Col>
                            <Col span={5}>
                                {this.setMessage('ShowNewApplicationModalprice', 'descripts')}
                                <Input placeholder={this.setMessage('ShowNewApplicationModalprice', 'descripts')} style={{ width: '60%' }} disabled={true} value={this.state.programPrice} />
                            </Col>
                        </Row>

                        <Row style={{ marginTop: 5 }}>
                            <Col span={6}>
                                {this.setMessage('ShowNewApplicationModalFrequency', 'descripts')}
                                <Select placeholder={this.setMessage('ShowNewApplicationModalquency', 'descripts')} style={{ width: '77%' }} showSearch allowClear
                                    filterOption={(input, option) =>
                                        option.props.code.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                        || option.props.disp.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                        || option.props.name.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                    }
                                    value={this.state.ordFreqID} onChange={this.handleSelectChange.bind(this, 'ordFreqID')}>
                                    {freListOption}
                                </Select>
                            </Col>
                            <Col span={7}>
                                {this.setMessage('ShowNewApplicationModalCourse', 'descripts')}
                                <Input placeholder={this.setMessage('ShowNewApplicationModalCourse', 'descripts')} style={{ width: '70%' }} value={this.state.ordDurQty}
                                    disabled={!Util.isEmpty(this.state.ordFreqID) ? false : true}
                                    onChange={this.commonInputChange.bind(this, 'ordDurQty')} />
                            </Col>
                            <Col span={5}>
                                {this.setMessage('ShowNewApplicationModaldosage', 'descripts')}
                                <Input placeholder={this.setMessage('ShowNewApplicationModaldosage', 'descripts')} style={{ width: '60%' }} value={this.state.ordDose}
                                    disabled={!Util.isEmpty(this.state.ordFreqID) ? false : true}
                                    onChange={this.commonInputChange.bind(this, 'ordDose')} />
                            </Col>
                        </Row>
                        <Row>
                            {this.setMessage('ShowNewApplicationModalplan', 'descripts')}
                            <TextArea placeholder={this.setMessage('ShowNewApplicationModalan', 'descripts')} rows='4' value={this.state.treatmentPlan}
                                onChange={Util.commonInputChange.bind(this, 'treatmentPlan')} />
                            {this.setMessage('ShowNewApplicationModalobjectives', 'descripts')}
                            <TextArea placeholder={this.setMessage('ShowNewApplicationModaltarget', 'descripts')} rows='4' value={this.state.treatmentGoals}
                                onChange={Util.commonInputChange.bind(this, 'treatmentGoals')} />
                        </Row>
                    </Card>
                </div>
            </Modal>
        </div>
    }
}

export default ShowNewApplicationModal;