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

const { TextArea } = Input;
const Step = Steps.Step;
const { TreeNode } = Tree;
import '../style/index.less';

export default class AuditRefusedTo extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            visible: false,
            refusalCause: [], // 拒绝原因
            selectedKeys: [], // 设置选中的树节点
            reasonsPreview: [], // 原因预览
            processNode: '', // 当为流程节点
            audStID: '',
            historyData: {}, // 点击历史节点选中的数据
        }
    }

    componentDidMount() {
        this.props.onRef(this);
    }

    handleShowModal = (selectedRows) => { // 打开弹窗
        this.setState({visible: true, selectedRows}, () => {
            if (!(this.state.refusalCause&&this.state.refusalCause.length > 0)) {
                this.getRefusalCause();
            }
            if (selectedRows[0].statusID !== "Before") {
                this.getAuditLogging(selectedRows[0].ordMainOrdID);
            } else {
                this.setState({auditLogging: [], historyData: {}, processNode: '1', audStID: ''})
            }
        })
    }

    handleCancel = (flag) => { // 关闭弹窗
        if (flag === 'handle') {
            this.setState({
                visible: false,
                reasonsPreview: [],
                remark: undefined
            });
            this.props.handleQuery();
        } else {
            this.setState({
                visible: false,
            });
        }
    }

    // 获取拒绝原因
    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 = (ordMainOrdID) => {
        let data = {
			params: [{
                ordMainOrdID
            }]
		}
		$http.post('urlS', this, {
			code: "02040050",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0 && res.result[0].rows.length > 0) {
                    let endObj =  res.result[0].rows.slice(-1);
					this.setState({auditLogging: res.result[0].rows}, () => {
                        // 取到最后一个数据然后查询出拒绝原因
                        this.handleSpan(endObj[0]);
                    })
				} else {
					this.setState({auditLogging: []})
				}
			}
		})
    }

    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("已经包含该条拒绝原因")
            } 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("请选中拒绝原因")
                    }
                } else {
                    message.error("请选择对应药品")
                }
            }
        } else {
            if (obj.reasonID) {
                reasonsPreview.push(obj);
                this.setState({reasonsPreview});
            } else {
                message.error("请选中拒绝原因")
            }
        }
    };

    // 选择对应药品
    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.setState({reasonsPreview: arr});
        } else {
            message.error("请选择拒绝原因")
        }
    };

    // 删除数组中的某一个对象
    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});
            }
        }
    }

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

    // 确定
    handleOk = (e) => {
        let {remark, reasonsPreview} = this.state;
        if (reasonsPreview&&reasonsPreview.length < 1) {
            message.error("请选择拒绝原因以及对应药品")
        } 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("选择拒绝原因之后必须选择拒绝药品")
            } 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: [{
                        auditType: "0",
                        remark,
                        reasonInfo,
                    }]
                }
                $http.post('urlADS', this, {
                    code: "02040009",
                    data: data,
                    success: function (res) {
                        if (+res.errorCode === 0) {
                            message.success("拒绝成功");
                            this.handleCancel('handle');
                            // 重新查询列表数据
                        }
                    }
                })
            }
        }
    }

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

    // 点击查看历史流程
    handleSpan = (rowData) => {
        let processNode = rowData.audStID === "" ? '1' : '0';
        console.log(rowData)
        this.setState({historyData: rowData, audStID: rowData.audStID, processNode});
        if (rowData.audStID) {
            let data = {
                params: [{
                    audStID: rowData.audStID,
                }]
            }
            $http.post('urlS', this, {
                code: "02040051",
                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.ordDr,
                                        medDesc: child.medDesc,
                                        ordDoseUnitDesc:child.ordDoseUnitDesc,
                                        ordDurationDesc: child.ordDurationDesc,
                                        ordFreqDesc: child.ordFreqDesc,
                                        ordQty: child.ordQty,
                                        ordUnitDesc:child.ordUnitDesc,
                                        ordUsage: child.ordUsage,
                                        ordUsageDesc:child.ordUsageDesc,
                                    }
                                })
                            }
                        })
                        this.setState({remarkDis: res.result[0].remark, reasonsPreviewDis: reasonsPreview})
                    }
                }
            })
        } else {
            // 返回当前节点
            this.handleGoBack()
        }
    }

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

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

    render() {
        let {visible, refusalCause, selectedKeys, selectedRows, reasonsPreview, remark, auditLogging} = this.state;
        let showStatus = false;
        let length = auditLogging ? auditLogging.length : 0;
        let statusID = selectedRows&&selectedRows.length > 0 ? selectedRows[0].statusID : "";
        // console.log(statusID)
        return (
            <Modal
                title="拒绝医嘱"
                visible={visible}
                onCancel={this.handleCancel}
                width={900}
                footer={null}
                className="audit-refused-to"
            >
                <div style={{minHeight: '500px'}}>
                    <div style={{width: '100%', overflow: 'auto'}}>
                        <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={{margin: '10px 0'}}>
                            <Row>
                                <Col span={8}>
                                    <Card title="1、选择拒绝原因" size="small">
                                        <div style={{height: '320px', overflow: 'auto'}}>
                                            {/* onDoubleClick={this.handleDblclickTreeNodes} */}
                                            <Tree onSelect={this.onSelectTreeNodeOne} selectedKeys={selectedKeys}>
                                                {refusalCause&&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="2、选择对应药品" size="small">
                                        <div style={{height: '320px', overflow: 'auto'}}>
                                            <ul style={{paddingLeft: '0px', marginBottom: '0px'}}>
                                                {selectedRows&&selectedRows.map((item, index) => {
                                                    return  (<li key={index}
                                                                onClick={showStatus ? null : () => this.onSelectTreeNodeTwo(item)}
                                                                className="disabled-none"
                                                            >
                                                                <Row>
                                                                    <span style={{marginRight: '15px'}}>{index + 1}、{item.medDesc}</span>
                                                                    <span>{item.medSpec}*1片</span>
                                                                </Row>
                                                                <Row style={{marginLeft: '15px'}}>用法：{item.ordDoseUnitDesc+ ' ' + item.ordFreqDesc+ ' ' + item.ordUsageDesc+ ' ' + item.ordDurationDesc}</Row>
                                                            </li>)
                                                })}
                                            </ul>
                                        </div>
                                    </Card>
                                </Col>
                                <Col span={8}>
                                    <Card title="3、拒绝原因预览" size="small">
                                        <div style={{height: '320px', overflow: 'auto'}}>
                                            <List
                                                itemLayout="horizontal"
                                                dataSource={reasonsPreview}
                                                renderItem={(item, num) => (
                                                    <List.Item>
                                                        <List.Item.Meta
                                                        title={<div
                                                            style={{position: 'relative', paddingRight: '30px'}}>
                                                            {Util.numberConvertToUppercase(num + 1) + '、' + item.title}
                                                            <span
                                                                className="span" style={{position: 'absolute', right: '0', color: 'red',}}
                                                                onClick={() => this.handleDelete(item)}>
                                                                删除
                                                            </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}*1片</span> : ''}
                                                                        </Row>
                                                                        {child.ordDoseUnitDesc&&child.ordFreqDesc ? <Row style={{marginLeft: '20px'}}>用法：{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'}}>备注：</Col>
                            <Col span={22}>
                                <TextArea
                                    rows={2}
                                    style={{width: '100%'}}
                                    value={remark}
                                    onChange={this.handleTextArea}
                                />
                            </Col>
                        </Row>
                        <div style={{marginTop: '20px', textAlign: 'center'}}>
                            <Button onClick={this.handleOk} type="primary" style={{marginRight: '15px'}}>确认</Button>
                            <Button onClick={this.handleCancel}>取消</Button>
                        </div>
                    </div>
                    <div style={{display: this.state.processNode === '1' ? 'none' : 'block'}}>
                        {this.state.historyData.role&&this.state.historyData.role === '药房' ? (<div>
                            <div style={{margin: '10px 0'}}>
                                <Card title="拒绝原因预览" size="small">
                                    <div style={{height: '320px', overflow: 'auto'}}>
                                        <List
                                            itemLayout="horizontal"
                                            dataSource={this.state.reasonsPreviewDis}
                                            renderItem={item => (
                                                <List.Item>
                                                    <List.Item.Meta
                                                    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}*1片</span> : ''}
                                                                    </Row>
                                                                    <Row style={{marginLeft: '20px'}}>用法：{(child.ordDoseUnitDesc || '')+ ' ' + (child.ordFreqDesc || '')+ ' ' + (child.ordUsageDesc || '')+ ' ' + (child.ordDurationDesc || '')}</Row>
                                                                </li>)
                                                            )
                                                        })
                                                    }
                                                    />
                                                </List.Item>
                                            )}
                                        />
                                    </div>
                                </Card>
                            </div>
                            <Row>
                                备注：{this.state.remarkDis}
                            </Row>
                        </div>) : (
                            <div style={{height: '355px', marginTop: '30px'}}>
                                <p style={{fontSize: '14px'}}>{this.state.historyData.userName + this.state.historyData.role + '于' + this.state.historyData.date + '提出申诉：'}</p>
                                <Row style={{fontSize: '16px', fontWeight: '900'}}>
                                    申诉理由：{this.state.remarkDis}
                                </Row>
                            </div>
                        )}
                        <div style={{marginTop: '20px', textAlign: 'center'}}>
                            {this.state.historyData&&this.state.historyData.audStID&&statusID === 'Yes' ? <Button onClick={this.handleGoBack}>返回当前流程节点</Button> : (<div>
                               <Button type="primary" onClick={this.handleOk} style={{display: statusID !== "Apply" && statusID !== "Rec" && statusID !== "No" ? 'inline-block' : 'none'}}>确认</Button>
                                {(statusID === "Before" || statusID === "Rec" || statusID === "Yes") ? "" : (<div>
                                    <Button type="primary" disabled={statusID !== "Apply"} style={{margin: '0 15px'}}>审核</Button>
                                    <Button type="danger" disabled={statusID !== "Apply"}>拒绝</Button>
                                </div>)}
                            </div>)}
                        </div>
                    </div>
                </div>
            </Modal>
        )
    }
}
