/**
 * 安排座位
 */
import React from "react";
import { Modal, message, Row, Col, Input, Select, Button, Icon } from 'antd';
import { $http } from '../../containers/config/https';
import ReadCard from '../../components/readcard/ReadCard';
import { Util } from 'tools/index';
import { $loadTemplate } from '../lodop/Common/Print.js';

let user;
const Option = Select.Option;
class ArrangePat extends React.Component {
    constructor(props) {
        super(props);
        user = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
        this.state = {
            patInfo: "",
            admList: [],
            admID: "",
            cardTypeID: "",     //卡类型
            changeSeatID: "",
            patNo: "",          //患者ID
            arrangeDis: false,
            cardNo: '',          //卡号
            cardTypeList: [],
           
            // replenishZero:this.props.cardType[0].replenishZero,
            // cardLength:this.props.cardType[0].cardLength,
        }
    }
    componentDidMount() {
        this.props.onRef(this);
        this.handleBaseData();
        message.config({ top: 320, duration: 3 });
     
    }
    componentWillUnmount() {
        // 组件销毁前将静止让setState修改state的状态
        this.setState = (state, callback) => { return; }
    }

    componentWillReceiveProps(nextProps) {
        if (nextProps.seatInfo.patInfo) {
            if (nextProps.seatInfo.patInfo.patBaseInfo) {
                if (this.handleInit()) {
                    this.handleGetPatInfo(nextProps.seatInfo.patInfo.patBaseInfo.patNo, "", nextProps.seatInfo.patInfo.admID, "N");
                }
            } else {
                this.handleInit();
            }
        }
    }
    //加载基础数据
    handleBaseData = () => {
        let data = {
            params: [{
                hospID: user.hospID,
            }]
        }
        $http.post('urlDeault', this, {
            code: "04080005",
            data: data,
            success: (res) => {
                if (+res.errorCode === 0) {
                    let defaultCardTypeID = "";
                    res.result.cardTypeList.map((item) => {
                        if (item.defaultFlag === "Y") {
                            defaultCardTypeID = item.id;
                        }
                    })
                    this.setState({
                        cardTypeList: res.result.cardTypeList,
                        defaultCardTypeID: defaultCardTypeID,
                        replenishZero: res.result.cardTypeList[0].replenishZero,
                        cardLength: res.result.cardTypeList[0].cardLength,
                    })
                } else {
                    message.error('获取信息失败：' + res.errorMessage);
                }
            }
        })
    }
    //确认
    handleOk = () => {

    }
    handleCancel = () => {

    }
    //选择就诊记录
    onAdmChange = (value) => {
        this.setState({ admID: value })
    }
    //初始化数据
    handleInit = () => {
        this.setState({
            patInfo: "",
            admList: [],
            admID: "",
            cardTypeID: "",
            changeSeatID: "",
            patNo: "",
            arrangeDis: false,
        });
        return true;
    }

    //获取患者就诊信息
    handleGetPatInfo = (patNo, cardNo, admID, flag) => {
        let data = {
            params: [{
                hospID: user.hospID,
                locID: user.locID,
                cardTypeID: this.state.cardTypeID === "" ? this.props.defaultCardTypeID : this.state.cardTypeID,
                patNo: patNo,
                cardNo: cardNo,
                admID: admID,
            }]
        }
        $http.post('urlDeault', this, {
            code: "04080006",
            data: data,
            success: (res) => {
                if (+res.errorCode === 0) {
                    let arrangeDis = this.state.arrangeDis;
                    if (flag === "Y") {
                        if (res.result.arrangeInfo.seatID) {
                            arrangeDis = true;
                            message.warn("该患者已安排了座位:" + res.result.arrangeInfo.seatAreaDesc + " " + res.result.arrangeInfo.seatDesc);
                        }
                    }
                    let admID = "";
                    if (res.result.admList.length === 1) {
                        admID = res.result.admList[0].admID;
                    }
                    this.setState({
                        patInfo: res.result.baseInfo,
                        admList: res.result.admList,
                        admID: admID,
                        arrangeDis: arrangeDis,
                    })
                } else {
                    this.setState({
                        patInfo: "",
                        admList: [],
                        admID: "",
                    })
                }
            },
            error: () => {
                this.setState({
                    patInfo: "",
                    admList: [],
                    admID: "",
                })
            }
        })
    }
    //登记号回车事件
    onPatNoEnter = (e) => {
        e.stopPropagation();
        this.handleGetPatInfo(e.target.value, "", "", "Y");
    }
    //卡号回车事件
    onCardNoEnter = (e) => {
        // this.handleZero();
        // this.handleGetPatInfo("", e.target.value, "", "Y");
        e.stopPropagation();
        this.setState({
            cardNo: e.target.value
        }, () => {
            this.handleGetPatInfo("", this.handleZero(), "", "Y");
        })
    }

    //进行卡号检测补0操作
    handleZero = () => {
        //补0 Y 长度不为0
        let cardNoNum = ''
        if (this.state.replenishZero == "Y" && parseInt(this.state.cardLength) && parseInt(this.state.cardLength) > 0 && this.state.cardNo && this.state.cardNo.length > 0) {
            let No = this.state.cardNo ? this.state.cardNo : ''
            // console.log("长度handleLength",this.state.cardLength,parseInt(this.state.cardLength))
            let length = parseInt(this.state.cardLength)
            cardNoNum = (Array(length).join(0) + No).slice(-length)
            // this.props.form.setFieldsValue({ cardNo: num });
            this.setState({
                cardNo: cardNoNum,
            })
        }
        return cardNoNum
    }

    //不足12字补0
    handleLength = () => {

    }
    //卡号修改
    onCardNoChange = (e) => {
        this.setState({
            cardNo: e.target.value,
            number: "",
        })
    }
    //选择卡类型
    onCardTypeChange = (value) => {
        for (var i = 0; i < this.props.cardType.length; i++) {
            if (value == this.props.cardType[i].id) {
                this.setState({
                    cardTypeID: value,
                    cardLength: this.props.cardType[i].cardLength && this.props.cardType[i].cardLength != "" ? this.props.cardType[i].cardLength + "位," : "",
                    replenishZero: this.props.cardType[i].replenishZero,
                })
            }
        }
    }
    //患者ID
    onChange = (e) => {
        this.setState({ patNo: e.target.value });
    };
    //安排或取消安排时调用
    handleArrangePat = (status) => {
        if (this.state.admList.length === 0) {
            message.warn("请先查询患者");
            return;
        }
        if (this.state.admID == "") {
            message.warn("请选择就诊记录");
            return;
        }
        let data = {
            params: [{
                userID: user.userID,
                locID: user.locID,
                admID: this.state.admID,
                seatID: this.props.seatInfo.seatID,
                status: status,
                arrangeID: this.props.seatInfo.patInfo.arrangeID ? this.props.seatInfo.patInfo.arrangeID : "",
                changeSeatID: this.state.changeSeatID,
            }]
        }
        $http.post('urlDeault', this, {
            code: "04080007",
            data: data,
            success: (res) => {
                if (+res.errorCode === 0) {
                    message.success("安排成功");
                    this.props.onClose();
                    this.props.handelThis.handleQuery();
                }
            }
        })
    }
    //读卡时调用
    handleReadCard = (e) => {
        // message.warn("暂不能读卡");
        const cardTypeID = (this.state.cardTypeID == "" ? this.props.defaultCardTypeID : this.state.cardTypeID);
        this.readCard.ReadCard(cardTypeID, "R", (json) => {
            if (!Util.isEmpty(json)) {
                this.setState({
                    cardInfo: json,
                    cardNo: json.cardNo,
                    patNo: !Util.isEmpty(json.patInfo.patNo) ? json.patInfo.patNo : '',
                }, () => {
                    this.handleGetPatInfo(json.patInfo.patNo, "", "", "Y");
                })
            }
        })
    }
    //打印座位号
    handlePrintSeat = () => {
        let data = {};
        data = {
            params: [{
                admID: this.state.admID,
                seatDesc: this.props.seatInfo.seatAreaDesc + " " + this.props.seatInfo.seatCode,
            }]
        }
        // console.log(data);
        $http.post('urlS', this, {
            code: "04030012",
            data: data,
            success: function (res) {
                if (res.errorCode === '0') {
                    const data = res.result
                    //加载模板
                    $loadTemplate("SeatCard", data);
                }
            }
        })
    }
    //换座
    onSeatChange = (value) => {
        this.setState({ changeSeatID: value });
    }
    render() {

        const cardTypeY = [];
        this.state.cardTypeList.map((item) => {
            cardTypeY.push(
                <Option key={item.id} value={item.id} cardlength={item.cardLength}>
                    {user.language == 'CN' ? item.descripts : item.enDescripts} 
                </Option>
            )
        })

        const footer = (
            <div style={{ width: '100%', textAlign: 'center' }}>
                <Button key="back" type="primary" onClick={this.handleReadCard}>
                    <Icon type="idcard" />{this.props.languageObj && this.props.languageObj.SeatMapCardreading && this.props.languageObj.SeatMapCardreading != null ? this.props.languageObj.SeatMapCardreading.descripts : ""}
                </Button>
                <Button disabled={this.state.arrangeDis} key="arrange" type="primary" onClick={this.handleArrangePat.bind(this, "Y")}>
                    <Icon type="lock" />{this.props.languageObj && this.props.languageObj.SeatMaparrangement && this.props.languageObj.SeatMaparrangement != null ? this.props.languageObj.SeatMaparrangement.descripts : ""}
                </Button>
                <Button disabled={this.props.seatInfo === "" ? true : !this.props.seatInfo.patInfo.arrangeID} key="reset" type="primary" onClick={this.handleArrangePat.bind(this, "N")} >
                    <Icon type="unlock" /> {this.props.languageObj && this.props.languageObj.SeatMapCancelarrangement && this.props.languageObj.SeatMapCancelarrangement != null ? this.props.languageObj.SeatMapCancelarrangement.descripts : ""}
                </Button>
                <Button key="print" type="primary" onClick={this.handlePrintSeat}>
                    <Icon type="printer" />{this.props.languageObj && this.props.languageObj.SeatMapPrintseatnumber && this.props.languageObj.SeatMapPrintseatnumber != null ? this.props.languageObj.SeatMapPrintseatnumber.descripts : ""}
                </Button>
            </div>
        )
        const admList = [];
        this.state.admList.map((adm) => {
            admList.push(
                <Option key={adm.admID} value={adm.admID}>
                    就诊时间:{adm.admDate + " " + adm.admTime}&nbsp;&nbsp;医生:{adm.admDocDesc}
                </Option>
            )
        })
        const cardType = [];
        this.props.cardType.map((item) => {
            cardType.push(
                <Option key={item.id} value={item.id}>
                    {item.descripts}
                </Option>
            )
        })

        let emptySeat = [];
        this.props.emptySeat.map((item) => {
            item.seatList.map((seat) => {
                emptySeat.push(
                    <Option key={seat.seatID} value={seat.seatID}>
                        {seat.seatAreaDesc + " " + seat.seatCode}
                    </Option>
                )
            })
        })

        return (
            <Modal
                title={"安排座位：" + this.props.seatInfo.seatAreaDesc + " " + this.props.seatInfo.seatCode}
                visible={this.props.visible}
                onOk={this.props.onOk}
                onCancel={this.props.onClose}
                width="460px"
                style={{
                    height: '320px',
                    background: '#FFFFFF',
                    borderRadius: '6px',
                    top: '310px'
                }}
                destroyOnClose
                maskClosable={false}
                footer={footer}
            >
                <Row style={{ padding: '5px 5px 5px 5px' }}>
                    <Col span={5}>
                     {this.props.languageObj && this.props.languageObj.SeatMapCardType && this.props.languageObj.SeatMapCardType != null ? this.props.languageObj.SeatMapCardType.descripts : ""}
                    </Col>
                    <Col style={{ textAlign: 'left' }} span={19}>
                        <Select
                            value={this.state.cardTypeID === "" ? this.props.defaultCardTypeID : this.state.cardTypeID}
                            style={{ width: '100%' }}
                            onChange={this.onCardTypeChange}
                        >
                            {cardType}
                        </Select>
                    </Col>
                </Row>
                <Row style={{ padding: '5px 5px 5px 5px' }}>
                    <Col span={5}>
                    {this.props.languageObj && this.props.languageObj.SeatMapCardNo && this.props.languageObj.SeatMapCardNo != null ? this.props.languageObj.SeatMapCardNo.descripts : ""}
                    </Col>
                    <Col style={{ textAlign: 'left' }} span={19}>
                        <Input style={{ width: '100%' }}
                            onPressEnter={this.onCardNoEnter}
                            placeholder="请输入卡号(刷卡)(Enter查询患者)"
                            value={this.state.cardNo}
                            onChange={this.onCardNoChange}
                            className='input' />
                    </Col>
                </Row>
                <Row style={{ padding: '5px 5px 5px 5px' }}>
                    <Col span={5}>
                    {this.props.languageObj && this.props.languageObj.SeatMapPatientID && this.props.languageObj.SeatMapPatientID != null ? this.props.languageObj.SeatMapPatientID.descripts : ""}
                    </Col>
                    <Col style={{ textAlign: 'left' }} span={19}>
                        <Input style={{ width: '100%' }} value={this.state.patNo === "" ? (this.state.patInfo === "" ? "" : this.state.patInfo.patNo) : this.state.patNo}
                            onChange={this.onChange}
                            onPressEnter={this.onPatNoEnter} placeholder="请输入患者ID(Enter查询患者)" className='input' />
                    </Col>
                </Row>
                <Row>
                    <Col span={5}>
                    {this.props.languageObj && this.props.languageObj.SeatMapMedicalrecord && this.props.languageObj.SeatMapMedicalrecord != null ? this.props.languageObj.SeatMapMedicalrecord.descripts : ""}
                    </Col>
                    <Col style={{ textAlign: 'left' }} span={19}>
                        <Select style={{ width: "100%" }} onChange={this.onAdmChange} value={this.state.admID} placeholder="请选择就诊记录">
                            {
                                admList
                            }
                        </Select>
                    </Col>
                </Row>
                <Row style={{ padding: '5px 5px 5px 5px' }}>
                    <Col span={5}>
                    {this.props.languageObj && this.props.languageObj.SeatMapPatientinformation && this.props.languageObj.SeatMapPatientinformation != null ? this.props.languageObj.SeatMapPatientinformation.descripts : ""}
                    </Col>
                    <Col style={{ textAlign: 'left' }} span={19}>
                        <Input
                            disabled={true}
                            value={this.state.patInfo === "" ? "" : this.state.patInfo.patName + " " + this.state.patInfo.patSexDesc + " " + this.state.patInfo.patAge}
                            style={{ width: '100%' }} className='input' />
                    </Col>
                </Row>
                <Row style={{ padding: '5px 5px 5px 5px' }}>
                    <Col span={5}>
                    {this.props.languageObj && this.props.languageObj.SeatMapChangeseat && this.props.languageObj.SeatMapChangeseat != null ? this.props.languageObj.SeatMapChangeseat.descripts : ""}
                    </Col>
                    <Col style={{ textAlign: 'left' }} span={19}>
                        <Select showSearch={true} style={{ width: "100%" }} value={this.state.changeSeatID} onChange={this.onSeatChange} >
                            {emptySeat}
                        </Select>
                    </Col>
                </Row>
                <ReadCard ref={(r) => { return (this.readCard = r) }} />
            </Modal>
        )
    }
}
export default ArrangePat;
