import React, { Component } from 'react';
import { $http } from '../../../containers/config/https';
import { Table, Steps, Card, Spin } from 'antd';
import PatientInfo from './PatientDetail.jsx';
import asyncComponent from '../../../routers/AsyncComponent.js';
import ColumnAuthoritysModel from '../../columnAuthority/ColumnAuthoritysModel';
import { Util } from 'tools/index';
let user;
let patientData;
const { Step } = Steps;

class PatientCourse extends Component {
    constructor(props) {
        patientData = JSON.parse(sessionStorage.getItem('patientData'));
        user = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {}
        super(props);
        this.state = {
            admID: this.props.admID ? this.props.admID : '',
            patient: [],
            total: 0,
            page: 1,
            pageSize: 20,
            columns: [],
            data: [],
            nextPrograme: '',
            startDate: '',
            stateCode: '',
            tableWidth: '',
            component: '',
            patID: '',
            current: 0,
            colunmsCode: '',
            // 图文咨询/线上问诊相关
            consultationInfo: {},       // 04020007+03100070 返回的预约信息
            chatMessages: [],           // 02090005 返回的聊天记录
            chatLoading: false,         // 聊天记录加载状态
            isVideoConsult: false,      // 是否是视频问诊（预留录频）
            isConsultStep: false,       // 当前是否是互联网就诊
            showChat: false,            // 是否显示聊天记录
        }
    }

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

    componentDidUpdate(prevProps) {
        if (prevProps.admID !== this.props.admID && this.props.admID) {
            this.loadPatienCourse()
        }
    }

    loadPatienCourse = () => {
        // 清空旧数据
        this.setState({
            patient: [],
            data: [],
            columns: [],
            component: '',
            current: 0,
            colunmsCode: '',
            isConsultStep: false,
        });
        const admID = this.props.admID ? this.props.admID : (patientData.admID ? patientData.admID : this.state.admID);

        // 调用 04040015 获取患者历程步骤
        let data = {
            params: [{
                admID: admID,
                cbEventID: '',
                course: "course",
            }]
        }
        $http.post('urlDeault', this, {
            code: "04040015",
            data: data,
            success: (res) => {
                if (+res.errorCode === 0) {
                    this.setState({
                        patient: res.result.Data,
                        current: 0,
                    });
                    if (res.result.Data.length > 0) {
                        this.selectCourseDetail(res.result.Data[0]);
                    }
                }
            }
        })

        // 调用 04020007 获取 admTypeDesc，判断是否是互联网就诊
        let userData = JSON.parse(sessionStorage.userData || '{}');
        let infoData = {
            params: [{
                admID: admID,
                hospID: userData.hospID || '',
            }]
        }
        $http.post('urlDeault', this, {
            code: "04020007",
            data: infoData,
            success: (res) => {
                if (res.errorCode == '0' && res.result) {
                    const admTypeDesc = res.result.admInfo?.admTypeDesc || '';
                    const isInternet = admTypeDesc === '互联网';
                    this.setState({
                        consultationInfo: res.result.admInfo || {},
                        isConsultStep: isInternet,
                    }, () => {
                        if (isInternet) {
                            this.loadConsultationInfo();
                            this.loadChatMessages();
                        }
                    });
                }
            }
        });
    }

    loadCheckInfo = () => {
        let data = {
            params: [{
                admID: this.props.admID ? this.props.admID : (patientData.admID ? patientData.admID : this.state.admID),
                startDate: this.state.startDate,
                code: this.state.nextPrograme,
                state: this.state.stateCode,
            }]
        }
        $http.post('urlS', this, {
            code: '04040022',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    this.setState({
                        data: res.result.data,
                    })
                }
            }
        })
    }

    // 加载图文咨询/线上问诊预约信息 (03100070) - 只获取 symptom
    loadConsultationInfo = () => {
        let admID = this.props.admID ? this.props.admID : patientData.admID;
        let data = {
            params: [{
                admID: admID,
            }]
        }
        $http.post('urlDeault', this, {
            code: "03100070",
            data: data,
            success: (res) => {
                if (res.errorCode == '0') {
                    this.setState({
                        // 只更新 symptom，其他字段（admDate, admTime, admTypeDesc）来自 04020007
                        consultationInfo: {
                            ...this.state.consultationInfo,
                            symptom: res.result?.symptom || '',
                        },
                        isVideoConsult: res.result?.admType === '线上问诊',
                    });
                }
            }
        });
    }

    // 加载聊天记录 (02090005)
    loadChatMessages = () => {
        let userData = JSON.parse(sessionStorage.userData || '{}');
        let admID = this.props.admID ? this.props.admID : patientData.admID;
        let data = {
            params: [{
                admID: admID,
                frUser: 'user' + (this.state.consultationInfo?.admDocID || userData.userID || ''),
                toUser: 'patient' + (this.props.patID || patientData.patID || ''),
                lastMsgID: ''
            }]
        }
        this.setState({ chatLoading: true, chatMessages: [] });
        $http.post("urlS", this, {
            code: "02090005",
            data: data,
            namespace: "HIS",
            success: (res) => {
                if (+res.errorCode === 0) {
                    // 只取 msgType 为 "1" 的消息，避免重复
                    const msgData = res.result?.msgData?.filter(item => item.msgType === '1') || [];
                    this.setState({
                        chatMessages: msgData,
                        chatLoading: false,
                    });
                } else {
                    this.setState({ chatMessages: [], chatLoading: false });
                }
            },
            error: () => {
                this.setState({ chatMessages: [], chatLoading: false });
            }
        });
    }

    // 点击聊天记录入口
    showChatRecord = () => {
        // 如果还没有加载聊天记录，先加载
        if (this.state.chatMessages.length === 0 && !this.state.chatLoading) {
            this.loadChatMessages();
        }
        this.setState({ showChat: true });
    }

    selectCourseDetail(item) {
        let { code, date, nextPrograme, colunmsCode, component } = item;

        if (component != '') {
            this.setState({
                component: component,
                stateCode: code,
                showChat: false,  // 点击步骤时隐藏聊天记录
            })
        } else {
            this.setState({
                stateCode: code,
                startDate: date,
                component: component,
                nextPrograme: nextPrograme,
                showChat: false,  // 点击步骤时隐藏聊天记录
            }, () => {
                if (colunmsCode != '') this.getDetailTableColumns(colunmsCode)
            })
        }
    }

    // 获取明系列表头数据
    getDetailTableColumns = (ColunmsCode, code, date) => {
        let data = {
            params: [{
                reactCode: [ColunmsCode],
                compontName: ColunmsCode,
                type: 'C',
            }]
        }
        $http.post('urlS', this, {
            code: '01040073',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    var columns = []
                    columns = res.result.C
                    if (columns) {
                        if (ColunmsCode == "OrderSearch") {
                            for (var ci = 0; ci < columns.length; ci++) {
                                if (columns[ci].dataIndex == 'lifeCycle') {
                                    var diagColumns = [];
                                    diagColumns.push({
                                        title: user.language != 'EN' ? user.language != 'EN' ? columns[ci].title : columns[ci].enDescripts : columns[ci].enDescripts,
                                        dataIndex: columns[ci].dataIndex,
                                        //width: width,
                                        align: 'center',
                                        render: (text, data, index) => {
                                            return <span style={{ cursor: "pointer" }} onClick={(e) => this.handleOpen(e, data.ordID)}><span style={{ color: "#096dd9" }}>生命周期</span></span>
                                        }
                                    })
                                    columns[ci] = diagColumns[0]
                                }
                            }
                        }
                    }
                    this.setState({
                        ENObj: res.result.language.EN,
                        CNObj: res.result.language.CN,
                        columns: columns,
                        tableWidth: res.totalWidth,
                        colunmsCode: ColunmsCode
                    }, () => {
                        this.loadCheckInfo()
                    })
                }
            }
        })
    };

    ChangeCurrent = (current) => {
        this.setState({
            current: current
        });
    }

    // 显示分页总条数
    showTotal(total) {
        return `共 ${total} 条`;
    }

    // 页码改变的回调，参数是改变后的页码及每页条
    onChange = (page, pageSize) => {
        this.compilePage(page, pageSize);
    }

    // 条数改变的回调
    onShowSizeChange = (current, size) => {
        this.compilePage(1, size);
    }

    onColumnRef = (ref) => {
        this.columnRef = ref;
    }

    render() {
        const { consultationInfo, isConsultStep } = this.state;
        let patientCourse = []
        this.state.patient && this.state.patient.map((item, index) => {
            patientCourse.push(
                <Step disabled={item.nextPro == "N"}
                    title={(
                        <div className={((this.state.current == index) && (item.nextPro == "Y")) ? "selected" : item.nextPro == "N" ? "disabledItem" : "unSelected"}>
                            <span style={{ "line-height": "32px", "float": "left", "font-size": "16px" }}>【{item.patEventDesc}】</span>
                        </div>
                    )}
                    onClick={this.selectCourseDetail.bind(this, item)}
                    description={(
                        <div className={((this.state.current == index) && (item.nextPro == "Y")) ? "selected" : 'normalText'}>
                            <span style={{ "line-height": "36px", "vertical-align": "bottom" }}>{item.patEventStartDate}&nbsp;&nbsp;{item.patEventStartTime}&nbsp;&nbsp;{item.user}</span>
                        </div>
                    )} />
            )
        })

        const Component = asyncComponent(() => import('../../' + this.state.component));
        return (
            <div className="patientCourseModal">
                <ColumnAuthoritysModel
                    clientWidth="800px"
                    compontName={this.state.colunmsCode}
                    configType="C"
                    onRef={this.onColumnRef}
                    reloadData={this.getDetailTableColumns.bind(this, this.state.colunmsCode)}
                />
                <PatientInfo admID={(this.props.admID) && (!Util.isEmpty(this.props.admID)) ? this.props.admID : this.state.admID} />
                <div style={{ width: '100%', height: 'calc(100% - 45px)' }}>
                    <Card className="course" >
                        <div style={{ width: '100%', height: '100%', overflow: 'auto' }}>
                            {/* 聊天记录入口 - 放在 Steps 上方 */}
                            <div
                                onClick={() => this.showChatRecord()}
                                style={{
                                    padding: '10px 12px',
                                    cursor: 'pointer',
                                    background: this.state.showChat ? '#e6f7ff' : '#fafafa',
                                    border: this.state.showChat ? '1px solid #1890ff' : '1px solid #d9d9d9',
                                    borderRadius: 4,
                                    marginBottom: 8,
                                    fontSize: 13,
                                    display: 'flex',
                                    alignItems: 'center',
                                    justifyContent: 'space-between'
                                }}
                            >
                                <span style={{ color: this.state.showChat ? '#1890ff' : '#333', fontWeight: this.state.showChat ? 500 : 400 }}>
                                    聊天记录
                                </span>
                                <span style={{ color: '#999', fontSize: 12 }}>
                                    {this.state.chatMessages.length > 0 ? `${this.state.chatMessages.length} 条` : ''}
                                </span>
                            </div>
                            {/* 步骤列表 */}
                            <Steps direction="vertical" size="small" onChange={this.ChangeCurrent} current={this.state.current}>
                                {patientCourse}
                            </Steps>
                        </div>
                    </Card>
                    <div className="courseInfo">
                        {/* showChat 为 true：显示聊天记录 */}
                        {this.state.showChat ? (
                            <div style={{ width: '100%', height: '100%', overflow: 'hidden', display: 'flex', flexDirection: 'column', padding: '0 8px 8px 0' }}>
                                {/* 顶部预约信息（互联网患者显示） */}
                                {this.state.isConsultStep && (
                                    <div style={{ padding: '8px 12px', background: '#fafafa', border: '1px solid #e8e8e8', borderRadius: 4, marginBottom: 8, flexShrink: 0 }}>
                                        <div style={{ display: 'flex', gap: 24, fontSize: 13, flexWrap: 'wrap' }}>
                                            <div>
                                                <span style={{ color: '#999' }}>预约时间：</span>
                                                <span>{consultationInfo?.admDate || '--'} {consultationInfo?.admTime || ''}</span>
                                            </div>
                                            <div>
                                                <span style={{ color: '#999' }}>就诊类型：</span>
                                                <span>{consultationInfo?.admTypeDesc || '--'}</span>
                                            </div>
                                            <div>
                                                <span style={{ color: '#999' }}>病情描述：</span>
                                                <span>{consultationInfo?.symptom || '--'}</span>
                                            </div>
                                        </div>
                                    </div>
                                )}

                                {/* 线上问诊预留录频播放区域 */}
                                {this.state.isVideoConsult && (
                                    <div style={{ height: 60, background: '#f5f5f5', borderRadius: 4, display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#999', marginBottom: 8, flexShrink: 0 }}>
                                        录频文件播放区域（待后台接口提供）
                                    </div>
                                )}

                                {/* 聊天记录区域 - 气泡样式 */}
                                <div style={{ flex: 1, overflow: 'auto', background: '#fff', border: '1px solid #e8e8e8', borderRadius: 4, padding: 12 }}>
                                    <div style={{ marginBottom: 8, color: '#333', fontWeight: 500 }}>聊天记录</div>
                                    <Spin spinning={this.state.chatLoading}>
                                        {this.state.chatMessages.length > 0 ? (
                                            <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
                                                {this.state.chatMessages.map((msg, index) => {
                                                    // direction: right=医生发送(蓝色), left=患者发送(灰色)
                                                    const isSent = msg.direction === 'right';
                                                    return (
                                                        <div key={index} style={{
                                                            display: 'flex',
                                                            flexDirection: 'column',
                                                            alignItems: isSent ? 'flex-end' : 'flex-start'
                                                        }}>
                                                            <div style={{
                                                                padding: '10px 14px',
                                                                background: isSent ? '#1890ff' : '#f5f5f5',
                                                                color: isSent ? '#fff' : '#333',
                                                                borderRadius: isSent ? '16px 16px 4px 16px' : '16px 16px 16px 4px',
                                                                maxWidth: '70%',
                                                                wordBreak: 'break-all',
                                                            }}>
                                                                {msg.consultText || '(图片/语音消息)'}
                                                            </div>
                                                            <span style={{ fontSize: 11, color: '#999', marginTop: 4 }}>
                                                                {isSent ? '我' : '患者'} {msg.sendTime || ''}
                                                            </span>
                                                        </div>
                                                    );
                                                })}
                                            </div>
                                        ) : (
                                            <div style={{ padding: 40, textAlign: 'center', color: '#999' }}>
                                                {this.state.chatLoading ? '加载中...' : '暂无聊天记录'}
                                            </div>
                                        )}
                                    </Spin>
                                </div>
                            </div>
                        ) : this.state.component != '' ? (
                            /* 外部组件（诊断、医嘱等） */
                            <Component admID={this.props.admID} patID={this.props.patID} />
                        ) : (
                            /* 原有表格展示 */
                            <div style={{ width: '100%', height: '100%', overflow: 'hidden' }} className="coursetable">
                                <Table
                                    style={{ width: '100%', "padding": "5px" }}
                                    dataSource={this.state.data}
                                    columns={this.state.columns}
                                    rowClassName="editable-row"
                                    bordered
                                    pagination={false}
                                    onHeaderRow={column => {
                                        return {
                                            onDoubleClick: () => {
                                                this.columnRef.onOpenModel();
                                            }
                                        };
                                    }
                                    }
                                    scroll={{ y: 'calc(100% - 45px)', x: this.state.tableWidth }}
                                />
                            </div>
                        )}
                    </div>
                </div>
            </div>
        )
    }
};

export default PatientCourse;