// 拒绝Modal
import React from 'react';
import { Modal, Steps, Icon, Card, Row, Col, Input, Button, Tree, message, List } from 'antd';
import { $http } from 'containers/config/https';
import {Util} from 'tools'

const { TextArea } = Input;
const Step = Steps.Step;
const { TreeNode } = Tree;

export default class RejectPrescription extends React.Component {
	constructor(props) {
        super(props);
        var userData = JSON.parse(sessionStorage.getItem('userData'));
        this.state = {
            userData,
            visible: false,
            refusalCause: [], // 拒绝原因
            auditLogging: [], // 获取审核记录
            detailData: [],
            reasonsPreview: [], // 原因预览
            remark: undefined, // 备注
            reasonsPreviewDis: [],
            remarkDis: undefined, // 备注
            prescno: '', // 处方号
            rowData: {}, // 行数据
            loggingDetail: {}, // 审核记录当中的一条
            processNode: '1', // 当为流程节点
            audStID: '',
            selectedKeys: [], // 设置选中的树节点
            historyData: {}, // 点击历史节点选中的数据
        };
    }

	componentDidMount() {
        let {userData} = this.state;
        userData.language == 'EN' ? this.getMainTableColumns() : "";
        this.props.onRef(this);
    }

    // 获取数据列表columns
    getMainTableColumns = () => {
        let {userData} = this.state;
        let data = {
			params: [{
                compontName: "RejectPrescription",
                reactCode: ['RejectPrescription'],
            }]
		}
		$http.post('urlS', this, {
			code: '01040073',
			data: data,
			success: function (res) {
                if (+res.errorCode === 0) {
                    this.setState({
                        localeProvider: userData.language == 'EN' ? res.result.language.EN : res.result.language.CN
                    })
                }
			}
		})
    }

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

	// 打开弹框
    showModal = (rowData, detailData) => {
        this.setState({
            // selectedKeys: [], // 取消选中的树节点
            visible: true,
            detailData: detailData ? detailData : [],
            ordPrescNo: rowData.ordPrescNo,
            rowData: rowData
        }, () => {
            this.getRefusalCause();
            if (rowData.statusID !== "Before") {
                this.getAuditLogging(rowData.ordPrescNo);
            } else {
                this.setState({auditLogging: [], loggingDetail: {}, processNode: '1', audStID: ''})
            }
        });
    }

    // 获取拒绝原因
    getRefusalCause = () => {
        let data = {
			params: []
		}
		$http.post('urlS', this, {
			code: "02030027",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					this.setState({refusalCause: res.result})
				} else {
					this.setState({refusalCause: []})
				}
			}
		})
    }

    // 获取审核记录
    getAuditLogging = (ordPrescNo) => {
        let data = {
			params: [{
                ordPrescNo: ordPrescNo
            }]
		}
		$http.post('urlS', this, {
			code: "02030025",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0 && res.result[0].rows.length > 0) {
                    let endObj =  res.result[0].rows.slice(-1);
                    let processNode = endObj[0].audStID === "" ? '1' : '0';
					this.setState({auditLogging: res.result[0].rows, processNode: processNode, loggingDetail: endObj[0], audStID: endObj[0].audStID}, () => {
                        if (this.state.rowData.statusID && (this.state.rowData.statusID === 'No' || this.state.rowData.statusID === 'Rec')) {
                            // 取到最后一个数据然后查询出拒绝原因
                            this.handleSpan(endObj[0]);
                        }
                    })
				} else {
					this.setState({auditLogging: [], loggingDetail: {}})
				}
			}
		})
    }

	// 确定
    handleOk = (e) => {
        let {ordPrescNo, remark, reasonsPreview} = this.state;
        if (reasonsPreview&&reasonsPreview.length < 1) {
            message.error(this.setMessage("RejectPrescriptionPSTRFEATCM", "descripts", "请选择拒绝原因以及对应药品"))
        } else {
            let flag = false;
            for (var i = 0; i < reasonsPreview.length; i++) {
                if (!reasonsPreview[i].ordInfo || (reasonsPreview[i].ordInfo&&reasonsPreview[i].ordInfo.length < 1)) {
                    flag = true;
                    break;
                } else {
                    flag = false;
                }
            }
            if (flag) {
                message.error(this.setMessage("RejectPrescriptionDrugs_must_be_selected", "descripts", "选择拒绝原因之后必须选择拒绝药品"))
            } else {
                let reasonInfo = reasonsPreview&&reasonsPreview.map(item => {
                    return {
                        reasonID: item.reasonID,
                        ordInfo: item.ordInfo&&item.ordInfo.map(child => {
                            return {
                                ordID: child.ordID
                            }
                        })
                    }
                })
                let data = {
                    params: [{
                        ordPrescNo: ordPrescNo,
                        remark: remark,
                        reasonInfo: reasonInfo,
                    }]
                }
                $http.post('urlADS', this, {
                    code: "02030022",
                    data: data,
                    success: function (res) {
                        if (+res.errorCode === 0) {
                            message.success(res.errorMessage);
                            if(this.props.discern == 'PrescriptionChecking'){
                                this.props.handleThis.clearData();
                            }
                            this.handleCancel('handle');
                            // 重新查询列表数据
                        }
                    }
                })
            }
        }
    }

    // 清空数据
    emptyData() {
        this.setState({
            reasonsPreview: [],
            remark: undefined,
            selectedKeys: []
        });
    }

	// 关闭
    handleCancel = (flag) => {
	    this.emptyData()
        if (flag === 'handle') {
            this.setState({
                visible: false,
                reasonsPreview: [],
                remark: undefined,
                selectedKeys: []
            });
            this.props.handleThis.refreshTableData();
            this.props.handleThis.resetData();
        } else {
            this.setState({
                visible: false,
            });
        }
    }

    arrTest(arr,title){
        let ststus = false;
        for(var i = 0;i < arr.length; i++){
            if (arr[i].title === title) {
                ststus = false;
                break
            } else {
                ststus = true;
            }
        }
        return ststus
    }

    // 选择拒绝原因
    onSelectTreeNodeOne = (keys, event, extra) => {
        this.setState({selectedKeys: keys})
        let obj = {
            reasonID: keys[0],
            title: event.node.props.title
        }
        let reasonsPreview = [...this.state.reasonsPreview];
        if (reasonsPreview.length && reasonsPreview.length > 0) {
            if (!this.arrTest(reasonsPreview, obj.title)) {
                message.error(this.setMessage("RejectPrescriptionRejectionRAE", "descripts", "该拒绝原因已存在"))
            } else {
                let status = false;
                for (var i = 0; i < reasonsPreview.length; i++) {
                    if (reasonsPreview[reasonsPreview.length - 1].ordInfo&&reasonsPreview[reasonsPreview.length - 1].ordInfo.length > 0) {
                        status = true;
                    } else {
                        status = false;
                    }
                }
                if (status) {
                    if (obj.reasonID) {
                        reasonsPreview.push(obj);
                        this.setState({reasonsPreview});
                    } else {
                        message.error(this.setMessage("RejectPrescriptionPSARR", "descripts", "请选择一条拒绝原因"))
                    }
                } else {
                    message.error(this.setMessage("RejectPrescriptionPSTCM", "descripts", "请选择对应药品"))
                }
            }
        } else {
            if (obj.reasonID) {
                reasonsPreview.push(obj);
                this.setState({reasonsPreview});
            } else {
                message.error(this.setMessage("RejectPrescriptionPSARR", "descripts", "请选择一条拒绝原因"))
            }
        }

    };

    // 选择对应药品
    onSelectTreeNodeTwo = (item) => {
        let arr = [...this.state.reasonsPreview];
        if (arr&&arr.length > 0) {
            let pop = arr[arr.length - 1];
            let status = true;
            pop.ordInfo = pop.ordInfo ? pop.ordInfo : [];
            for(var i = 0; i < pop.ordInfo.length; i++) {
                if (JSON.stringify(pop.ordInfo[i]) === JSON.stringify(item)) {
                    status = false;
                    break;
                } else {
                    status = true;
                }
            }
            if (status) {
                pop.ordInfo.push(item);
            } else {
                message.error(this.setMessage("RejectPrescriptionTCDAE", "descripts", "该对应药品已存在"))
            }
            this.setState({reasonsPreview: arr});
        } else {
            message.error(this.setMessage("RejectPrescriptionPSARR", "descripts", "请选择一条拒绝原因"))
        }
    };

    // 点击查看历史流程
    handleSpan = (rowData) => {
        this.setState({historyData: rowData})
        if (rowData.audStID) {
            let data = {
                params: [{
                    audStID: rowData.audStID,
                }]
            }
            $http.post('urlS', this, {
                code: "02030026",
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        let reasonsPreview = res.result[0].reasonInfo&&res.result[0].reasonInfo.map(item => {
                            return {
                                title: item.reasonDesc,
                                reasonID: item.reasonID,
                                ordInfo: item.ordInfo&&item.ordInfo.map((child, index) => {
                                    return {
                                        ordID: child.ordID,
                                        medDesc: child.medDesc,
                                        ordDoseUnitDesc:child.ordDoseUnitDesc,
                                        ordDurationDesc:child.ordDurationDesc,
                                        ordFreqDesc:child.ordFreqDesc,
                                        ordUnitDesc:child.ordUnitDesc,
                                        ordUsage:child.ordUsage
                                    }
                                })
                            }
                        })
                        let processNode = rowData.audStID === "" ? '1' : '0';
                        this.setState({remarkDis: res.result[0].remark, reasonsPreviewDis: reasonsPreview, processNode: processNode, audStID: rowData.audStID})
                    }
                }
            })
        } else {
            // 返回当前节点
            this.handleGoBack()
        }
    }

    // 备注
    handleTextArea = (e) => {
        this.setState({remark: e.target.value})
    }

    // 删除
    handleDelete = (rowData) => {
        const dataSource = JSON.parse(JSON.stringify(this.state.reasonsPreview));
        this.setState({ reasonsPreview: dataSource.filter(item => item.reasonID !== rowData.reasonID)});
    }

    // 删除数组中的某一个对象
    removeAaary(_arr, _obj) {
        var length = _arr.length;
        for (var i = 0; i < length; i++) {
            if (_arr[i].ordID === _obj.ordID) {
                if (i === 0) {
                    _arr.shift(); //删除并返回数组的第一个元素
                    return _arr;
                }
                else if (i === length - 1) {
                    _arr.pop();  //删除并返回数组的最后一个元素
                    return _arr;
                }
                else {
                    _arr.splice(i, 1); //删除下标为i的元素
                    return _arr;
                }
            }
        }
    }

    // 删除拒绝原因预览中的对应药品
    handleDeleteDetail = (mainData, detailData, e) => {
        e.preventDefault();
        const dataSource = JSON.parse(JSON.stringify(this.state.reasonsPreview));
        for (var i = 0; i < dataSource.length; i++) {
            // if (dataSource[i].ordInfo&&dataSource[i].ordInfo.length > 1) {}
            if (dataSource[i].reasonID === mainData.reasonID) {
                let arr = this.removeAaary(dataSource[i].ordInfo, detailData);
                dataSource[i].ordInfo = arr ? arr : [];
                this.setState({ reasonsPreview: dataSource});
            }
        }
    }

    // 返回当前节点
    handleGoBack = () => {
        // 改变状态
        this.setState({processNode: '1', audStID: ''})
    }

    render() {
        let {auditLogging} = this.state;
        let length = auditLogging ? auditLogging.length : 0;
        let showStatus = this.state.loggingDetail && this.state.loggingDetail.audStID ? true : false;
        let {statusID} = this.state.rowData
        return (
            <Modal
                title={<div><div className="modal-title-top"></div>{this.props.modalTitle ? this.props.modalTitle : this.setMessage("RejectPrescriptionReasons_for_refusal", "descripts", "拒绝原因")}</div>}
                visible={this.state.visible}
                onCancel={this.handleCancel}
                width={900}
                footer={null}
                className="reject-prescription modal-header-line"
            >
                <div style={{minHeight: '500px'}} className="reject-steps">
                    <div style={{width: '100%', overflow: 'auto'}} className="none-scroll">
                        <Steps style={{width: length * 172 + 'px', margin: '0 auto'}}>
                            {auditLogging&&auditLogging.map((item, index) => {
                                return (
                                    <Step
                                        style={{color: '#1890ff'}}
                                        key={index} icon={<Icon type="user" />}
                                        status={item.clickFlag === 1 ? (item.audStID === this.state.audStID ? "process" : "finish") : 'wait'}
                                        title={item.clickFlag === 0 ? item.role : <span style={{cursor: 'pointer'}}
                                        onClick={() => this.handleSpan(item)}>{item.role}</span>}
                                        description={
                                            <div key={index+'descriptopn'} style={{fontSize: '12px', }}><Icon type="check" style={{marginRight: '8px'}} />{item.userName + ' ' + item.stautsDesc + ' ' + item.date + ' ' + item.time}</div>
                                        }
                                    />
                                )
                            })}
                        </Steps>
                    </div>
                    <div style={{display: this.state.processNode === '1' ? 'block' : 'none'}}>
                        <div style={{marginBottom: '10px'}}>
                            <Row>
                                <Col span={8}>
                        <Card title={<div style={{textAlign: 'center'}}>1、{this.setMessage("RejectPrescriptionSelect_reason_for_rejection", "descripts", "选择拒绝原因")}</div>} size="small">
                                        <div style={{height: '320px', overflow: 'auto'}}>
                                            <Tree disabled={showStatus} onSelect={this.onSelectTreeNodeOne} selectedKeys={this.state.selectedKeys}>
                                                {this.state.refusalCause&&this.state.refusalCause.map(item => {
                                                    return (
                                                        <TreeNode title={item.title} key={item.key}>
                                                            {item.children&&item.children.map(child => {
                                                                return <TreeNode title={child.title} key={child.key} isLeaf />
                                                            })}
                                                        </TreeNode>
                                                    )
                                                })}
                                            </Tree>
                                        </div>
                                    </Card>
                                </Col>
                                <Col span={8}>
                                    <Card title={<div style={{textAlign: 'center'}}>2、{this.setMessage("RejectPrescriptionSelect_corresponding_drugs", "descripts", "选择对应药品")}</div>} size="small">
                                        <div style={{height: '320px', overflow: 'auto'}} className="corresponding-drugs">
                                            <ul style={{paddingLeft: '0px', marginBottom: '0px'}}>
                                                {this.state.detailData&&this.state.detailData.map((item, index) => {
                                                    return  (<li key={index}
                                                                onClick={showStatus ? null : () => this.onSelectTreeNodeTwo(item)}
                                                                className={showStatus ? "disabled-yes" : "disabled-none"}
                                                            >
                                                                <Row>
                                                                    <span style={{marginRight: '15px'}}>{index + 1}、{item.medDesc}</span>
                                                                    <span>{item.medSpec+this.setMessage("RejectPrescriptionFilm", "descripts", "*1片")}</span>
                                                                </Row>
                                                                <Row style={{marginLeft: '15px'}}>{this.setMessage("RejectPrescriptionUsage", "descripts", "用法：")+item.ordDoseUnitDesc+ ' ' + item.ordFreqDesc+ ' ' + item.ordUsageDesc+ ' ' + item.ordDurationDesc}</Row>
                                                            </li>)
                                                })}
                                            </ul>
                                        </div>
                                    </Card>
                                </Col>
                                <Col span={8}>
                                    <Card title={<div style={{textAlign: 'center'}}>3、{this.setMessage("RejectPrescriptionReject_reason_Preview", "descripts", "拒绝原因预览")}</div>} size="small">
                                        <div style={{height: '320px', overflow: 'auto'}}>
                                            <List
                                                itemLayout="horizontal"
                                                dataSource={this.state.reasonsPreview}
                                                renderItem={(item, num) => (
                                                    <List.Item>
                                                        <List.Item.Meta
                                                        // avatar={<Avatar src="https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png" />}
                                                        title={<div style={{position: 'relative', paddingRight: '30px'}}>{Util.numberConvertToUppercase(num + 1) + '、' + item.title}<span className="span" style={{position: 'absolute', right: '0', color: 'red', display: showStatus ? "none" : "inline-block"}} onClick={() => this.handleDelete(item)}>{this.setMessage("RejectPrescriptionDelete", "descripts", "删除")}</span></div>}
                                                        description={
                                                            item.ordInfo&&item.ordInfo.map((child, index) => {
                                                                return (
                                                                    (<li key={index} style={{position: 'relative', paddingRight: '20px'}}>
                                                                        <Row style={{marginRight: '10px'}}>
                                                                            <span style={{marginRight: '15px'}}>{index + 1}、{child.medDesc}</span>
                                                                            {child.medSpec ? <span span={14}>{child.medSpec+this.setMessage("RejectPrescriptionFilm", "descripts", "*1片")}</span> : ''}
                                                                        </Row>
                                                                        {child.ordDoseUnitDesc&&child.ordFreqDesc ? <Row style={{marginLeft: '20px'}}>{this.setMessage("RejectPrescriptionUsage", "descripts", "用法：")+child.ordDoseUnitDesc+ ' ' + child.ordFreqDesc+ ' ' + child.ordUsageDesc+ ' ' + child.ordDurationDesc}</Row>: ''}
                                                                        {!showStatus ? <Icon onClick={(e) => this.handleDeleteDetail(item, child, e)} type="close-circle" style={{position: 'absolute', top: '4px', right: '4px', fontSize: '16px', cursor: 'pointer'}} /> : ''}
                                                                    </li>)
                                                                )
                                                            })
                                                        }
                                                        />
                                                    </List.Item>
                                                )}
                                            />
                                        </div>
                                    </Card>
                                </Col>
                            </Row>
                        </div>
                        <Row>
                            <Col span={2} style={{textAlign: 'center'}}>{this.setMessage("RejectPrescriptionRemarks", "descripts", "备注：")}</Col>
                            <Col span={22}>
                                <TextArea
                                    rows={2}
                                    style={{width: '100%'}}
                                    value={this.state.remark}
                                    onChange={this.handleTextArea}
                                    disabled={showStatus}
                                />
                            </Col>
                        </Row>
                        <div style={{marginTop: '20px', textAlign: 'center'}}>
                        <Button type="primary" onClick={this.handleOk} style={{display: statusID !== "Apply" && statusID !== "Rec" && statusID !== "No" ? 'inline-block' : 'none'}}>{this.setMessage("RejectPrescriptionConfirm", "descripts", "确认")}</Button>
                        {(statusID === "Before" || statusID === "Rec" || statusID === "Yes") ? "" : (<div>
                            <Button
                                type="primary"
                                disabled={this.state.rowData.statusID !== "Apply"}
                                style={{margin: '0 15px'}}
                                onClick={() => this.props.handleThis.handleGetApproved('detail')}
                            >{this.setMessage("RejectPrescriptionAudit_pass", "descripts", "审核通过")}</Button>
                            <Button
                                type="danger"
                                disabled={this.state.rowData.statusID !== "Apply"}
                                onClick={this.handleOk}
                            >{this.setMessage("RejectPrescriptionAudit_reject", "descripts", "审核拒绝")}</Button>
                        </div>)}
                    </div>
                    </div>
                    <div style={{display: this.state.processNode === '0' ? 'block' : 'none'}}>
                        {this.state.historyData.role&&this.state.historyData.role === '药房' ? (
                            <div>
                                <div style={{margin: '10px 0'}}>
                                    <Card title={this.setMessage("RejectPrescriptionReject_reason_Preview", "descripts", "拒绝原因预览")} size="small">
                                        <div style={{height: '320px', overflow: 'auto'}}>
                                            <List
                                                itemLayout="horizontal"
                                                dataSource={this.state.reasonsPreviewDis}
                                                renderItem={item => (
                                                    <List.Item>
                                                        <List.Item.Meta
                                                        // avatar={<Avatar src="https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png" />}
                                                        title={<div>{item.title}</div>}
                                                        description={
                                                            item.ordInfo&&item.ordInfo.map((child, index) => {
                                                                return (
                                                                    (<li key={index} style={{position: 'relative', paddingRight: '20px'}}>
                                                                        <Row style={{marginRight: '10px'}}>
                                                                            <span style={{marginRight: '15px'}}>{index + 1}、{child.medDesc}</span>
                                                                            {child.medSpec ? <span span={14}>{child.medSpec+this.setMessage("RejectPrescriptionFilm", "descripts", "*1片")}</span> : ''}
                                                                        </Row>
                                                                        <Row style={{marginLeft: '20px'}}>{this.setMessage("RejectPrescriptionUsage", "descripts", "用法：")+child.ordUsage}</Row>
                                                                    </li>)
                                                                )
                                                            })
                                                        }
                                                        />
                                                    </List.Item>
                                                )}
                                            />
                                        </div>
                                    </Card>
                                </div>
                                <Row>
                                    {this.setMessage("RejectPrescriptionRemarks", "descripts", "备注：") + this.state.remarkDis}
                                </Row>
                            </div>) : (
                                <div style={{height: '355px', marginTop: '30px'}}>
                                    <p style={{fontSize: '14px'}}>{this.state.historyData.userName + this.state.historyData.role + this.setMessage("RejectPrescriptionTo", "descripts", "于") + this.state.historyData.date + this.setMessage("RejectPrescriptionAppeal", "descripts", "提出申诉：")}</p>
                                    <Row style={{fontSize: '16px', fontWeight: '900'}}>
                                        {this.setMessage("RejectPrescriptionReasons_for_appeal", "descripts", "申诉理由：") + this.state.remarkDis}
                                    </Row>
                                </div>
                            )}
                        <div style={{marginTop: '20px', textAlign: 'center'}}>
                            {this.state.loggingDetail&&this.state.loggingDetail.audStID === "" ? <Button onClick={this.handleGoBack}>{this.setMessage("RejectPrescriptionRTCPN", "descripts", "返回当前流程节点")}</Button> : (<div>
                                <Button type="primary" onClick={this.handleOk} style={{display: statusID !== "Apply" && statusID !== "Rec" && statusID !== "No" ? 'inline-block' : 'none'}}>{this.setMessage("RejectPrescriptionConfirm", "descripts", "确认")}</Button>
                                {(statusID === "Before" || statusID === "Rec" || statusID === "Yes") ? "" : (<div>
                                    <Button type="primary" disabled={this.state.rowData.statusID !== "Apply"} style={{margin: '0 15px'}}>{this.setMessage("RejectPrescriptionTo_examine", "descripts", "审核")}</Button>
                                    <Button type="danger" disabled={this.state.rowData.statusID !== "Apply"}>{this.setMessage("RejectPrescriptionRefuse", "descripts", "拒绝")}</Button>
                                </div>)}
                            </div>)}
                        </div>
                    </div>
                </div>
            </Modal>
        );
    }
}
