/**
 * Creator:     WRX
 * CreatDate:   2023-12-18
 * descripts：  预复诊记录
 * */
import React, {Component} from 'react';
import {
    Button,
    Card,
    Col,
    Divider,
    Empty,
    Icon,
    Input,
    message,
    Modal,
    Popconfirm,
    Row,
    Select,
    Steps,
    Tag
} from "antd";
import RangeDatePicker from 'components/rangePicker'
import moment from 'moment'
import {$http} from 'containers/config/https'
import PubilcTablePagination from 'pages/common/PubilcTablePagination'
import store from 'store'

const Option = Select.Option;
const { Step } = Steps;

class PreVisitRecords extends Component {
    constructor(props) {
        super(props);
        this.userData = React.$getSessionData();
        this.state = {
            cardType: undefined, // 卡类型,
            startDate: '',
            endDate: '',
            sendStatus:'',
            preAdmStatus:'',
            locID:'',
            doctorID:'',
            locList:[],
            userList:[],
            sendStatusList:[],
            preAdmStatusList:[],
            visitList:[],
            reason:[],
            selectReason:'',
            msgInfo: {},
            cancelInfo:{},
            contentRecordArr:[],
            pageSize:20,
            page:1,
            loading:false,
            columns:[],
            selectedRowKeys:[],
            selectedRowIDs:[]
        }
    }

    componentDidMount() {
        this.getBasicData()
        this.getTableColumns();
    }

    getBasicData(){
        $http.post('urlS', this, {
            code: '03060035',
            data: { params:[{}] },
            success: function (res) {
                if (+res.errorCode === 0) {
                    this.setState({
                        locList:res.result?.loc,
                        userList:res.result?.user,
                        sendStatusList:res.result?.sendStatus,
                        preAdmStatusList:res.result?.preAdmStatus,
                        reason:res.result?.reason,
                        startDate: res.result?.startDate,
                        endDate: res.result?.endDate
                    },()=>{
                        this.getVisitRecordList()
                    })
                }
            }
        })
    }


    getVisitRecordList() {
        this.setState({loading:true})
        let data = {
            params: [{
                startDate:this.state.startDate,
                endDate:this.state.endDate,
                patNo:this.state.patNo,
                locID:this.state.locID,
                docID:this.state.doctorID,
                sendStatus:this.state.sendStatus,
                preAdmStatus:this.state.preAdmStatus,
            }],
            pagination: [{
                pageSize:this.state.pageSize,
                currentPage: this.state.page
            }]
        };
        $http.post('urlS', this, {
            code: '03060036',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    this.setState({visitList:res.result.rows,total:res.result.total,loading:false})
                }
            }
        })
    }

    commonInputChange = (name,value) => {
        this.setState({
            [name]: value || ''
        })
    }

    // 分页操作
    compilePage = (page, pageSize) => {
        this.setState({ page, pageSize }, () => {
            this.getVisitRecordList();
        })
    }

    // 发送
    sendMsg = (record) => {
        let data = {
            params: [{
                preAdmRecordIDArr: [record.preAdmRecordID]
            }]
        };
        $http.post('urlS', this, {
            code: '03060039',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    message.success('成功')
                    this.getVisitRecordList();
                }
            }
        })
    }

    // 批量发送
    batchSendMsg = () => {
        let data = {
            params: [{
                preAdmRecordIDArr: this.state.selectedRowIDs
            }]
        };
        $http.post('urlS', this, {
            code: '03060039',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    message.success('批量发送成功')
                    this.getVisitRecordList();
                }
            }
        })
    }

    // 撤销发送
    cancelSendMsg = () => {
        let data = {
            params: [{
                preAdmRecordID: this.state.msgInfo?.preAdmRecordID,
                reasonID: this.state.selectReason
            }]
        };
        $http.post('urlS', this, {
            code: '03060037',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    this.setState({visible:false})
                    message.success('撤销成功')
                    this.getVisitRecordList();
                }
            }
        })
    }
    // 获取列表头数据 -- 01040073
    getTableColumns = async () => {
        let operationObj = {
            width: 100,
            title: '操作',
            align: 'center',
            key: 'operation',
            render: (text, record) => {
                const disable = record.sendStatusCode==='20'||record.sendStatusCode==='30'||record.preAdmStatusCode === '20';
                return (
                    <span>
                    <Popconfirm
                        title="确定要发送吗?"
                        onClick={(e) => React.$stopPropagation(e)}
                        onConfirm={(e) => this.sendMsg(record)}
                        disabled={disable}>
                        <Button type="link" size="small" disabled={disable} style={{ color: disable ? "grey" :'#1677ff' }}>
                            发送
                        </Button>
                    </Popconfirm>
                    <Divider type="vertical" />
                    <Button style={{ color: disable ? "grey" : "red" }}
                        disabled={disable} type="link" size="small"
                        onClick={()=>{this.handleOpenModal(record)}}>
                        撤销
                    </Button>
                </span>
                )
            },
        };
        try {
            let data = {
                params: [{
                    compontName: "PreAdmColumns",
                    type: 'C',
                }]
            }
            let res = await React.$asyncPost(this, '01040073', data);
            let filterArr = res.result && res.result.C && res.result.C.length > 0 ? res.result.C : [];
            if (filterArr && filterArr.length > 0) {
                let columns = []
                if (filterArr && filterArr.length > 0) {
                    filterArr.map(item => {
                        if (item.dataIndex === 'sendStatusDesc') {
                            const statusColumns = {
                                title: item.descripts,
                                width: item.width,
                                dataIndex: item.dataIndex,
                                key: item.dataIndex,
                                align: item.align,
                                render: (text, record) => (
                                    <span style={{color: this.switchStatus(record.sendStatusCode,'sendStatus')}}>{record.sendStatusDesc}</span>
                                ),
                            }
                            columns.push(statusColumns)
                        }else if (item.dataIndex === 'preAdmStatusDesc') {
                            const statusColumns = {
                                title: item.descripts,
                                dataIndex: item.dataIndex,
                                width: item.width,
                                key: item.dataIndex,
                                align: item.align,
                                render: (text, record) => (
                                    <span style={{color: this.switchStatus(record.preAdmStatusCode,'preAdmStatus')}}>{record.preAdmStatusDesc}</span>
                                ),
                            }
                            columns.push(statusColumns)
                        } else {
                            columns.push(item)
                        }
                    })
                }
                columns = filterArr && filterArr.length > 0 ? [...columns, operationObj] : []
                this.setState({
                    columns: columns,
                    totalWidth: res.totalWidth
                })
            }
        } catch (error) {
            console.log(error)
        }
    }

    // 操作弹框
    onClickRowPublic = (record, index) => {
        return {
            onClick: () => {
                this.setState({ msgInfo:record,contentRecordArr:record.contentRecordArr})
            }
        }
    }

    setRowClassNamePublic = (record) => {
        return record.preAdmRecordID === this.state.msgInfo.preAdmRecordID ? 'clickRowStyle' : '';
    }

    switchStatus(code,type){
        if (type==='sendStatus'){
            switch (code) {
                case '10':
                    return '#108ee9'
                case '20':
                    return '#87d068'
                case '30':
                    return ''
                case '40':
                    return '#f50'
                default : return ''
            }
        }if (type==='preAdmStatus'){
            switch (code) {
                case '10':
                    return ''
                case '20':
                    return '#87d068'
                case '30':
                    return '#f50'
                default : return ''
            }
        }else {
            switch (code) {
                case '10':
                    return 'wait'
                case '20':
                    return 'finish'
                case '30':
                    return 'wait'
                case '40':
                    return 'error'
                default : return 'wait'
            }
        }
    }

    handleOpenModal(record){
        this.setState({visible:true,cancelInfo:record})
    }

    rowSelectionOnChange = (selectedRowKeys, selectedRows) => {
        let ids = []
        selectedRows.forEach(item=>{
            ids.push(item.preAdmRecordID)
        })
        this.setState({
            selectedRowKeys: selectedRowKeys,
            selectedRowIDs:ids
        })
    }

    render() {
        const {
            patNo,
            startDate,
            endDate,
            totalWidth,
            page,
            pageSize,
            total,
            loading,
            visitList,
            msgInfo,
            contentRecordArr,
            columns,
            selectedRowKeys
        } = this.state;

        let rowSelection = {
            selectedRowKeys,
            onChange: this.rowSelectionOnChange,
        };
        return (
            <>
                <div style={{ lineHeight: 'inherit' }} className="gmaf-header common-query-header flex-align-items">
                    <span style={{ marginLeft: '12px' }}>人员标识：</span>
                    <Input
                        placeholder="请输入"
                        value={patNo}
                        onChange={(e)=>{this.commonInputChange('patNo',e.target.value)}}
                        style={{ width: '150px', marginRight: '12px' }}
                        onPressEnter={this.getVisitRecordList}
                    />

                    <span >选择科室：</span>
                    <Select allowClear style={{ width: 180, marginRight: 15 }} showSearch
                            onChange={(value,option)=> this.commonInputChange('locID',option?.props.id)}
                            optionFilterProp="children"
                            filterOption={(input, option) =>
                                option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                            }
                    >
                        {
                            this.state.locList.map((item,index) => {
                                return <Option key={index} id={item.id}>{item.descripts}</Option>
                            })
                        }
                    </Select>

                    <span >选择医生：</span>
                    <Select allowClear style={{ width: 180, marginRight: 15 }} showSearch
                            onChange={(value,option)=> this.commonInputChange('doctorID',option.props.id)}
                            optionFilterProp="children"
                            filterOption={(input, option) =>
                                option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                            }
                    >
                        {
                            this.state.userList.map((item,index) => {
                                return <Option key={index} id={item.id}>{item.descripts}</Option>
                            })
                        }
                    </Select>

                    <div style={{ marginRight: 15, display: 'inline-block' }}>
                        <RangeDatePicker
                            allowClear={false}
                            width="300px"
                            label="预约日期："
                            isChange={true}
                            format='YYYY-MM-DD'
                            className='express-select-border'
                            startDate={moment(startDate)}
                            endDate={moment(endDate)}
                            startChange={(event)=>{this.commonInputChange('startDate',event)}}
                            endChange={(event)=>{this.commonInputChange('endDate',event)}}
                        />
                    </div>

                    <span >短信状态：</span>
                    <Select defaultValue='全部' allowClear style={{ width: 180, marginRight: 15 }} onChange={(value,option)=> this.commonInputChange('sendStatus',option.props.id)}>
                        {
                            this.state.sendStatusList.map((item,index) => {
                                return <Option key={index} id={item.id}>{item.descripts}</Option>
                            })
                        }
                    </Select>

                    <span >复诊状态：</span>
                    <Select defaultValue='全部' allowClear style={{ width: 180, marginRight: 15 }} onChange={(value,option) => this.commonInputChange('preAdmStatus',option.props.id)}>
                        {
                            this.state.preAdmStatusList.map((item,index) => {
                                return <Option key={index} id={item.id}>{item.descripts}</Option>
                            })
                        }
                    </Select>
                    <Button type='primary' onClick={()=>{this.getVisitRecordList()}}>查询</Button>
                    <Button style={{marginLeft:20}} type='primary' onClick={() => {this.batchSendMsg()}}>批量发送</Button>
                </div>
                <div className="common-query-split-line" style={{ height: 8 }}></div>
                <Row>
                    <Col span={18}>
                        <Card bordered={false} size="small">
                            <PubilcTablePagination
                                param={{
                                    page,
                                    pageSize,
                                    total,
                                    loading,
                                    data: visitList, // 表格数据
                                    x: totalWidth, // 表格的宽度
                                    y: store.getState().tableHeight.y - 15,
                                    componentName: 'PreAdmColumns',
                                    height: store.getState().tableHeight.y + 100 + 'px',
                                    columns: columns && columns.length > 0 ? columns : this.staticColumns, // 表头配置
                                }}
                                compilePage={this.compilePage}
                                getColumns={this.getTableColumns}
                                onRef={ref => this.commonTableRef = ref}
                                onClickRowPublic={this.onClickRowPublic}
                                rowKey={record=>record.preAdmRecordID}
                                setRowClassNamePublic={this.setRowClassNamePublic}
                                rowSelectionPublic={rowSelection}
                            />
                            <Modal
                                title="撤销短信发送"
                                bodyStyle={{height:200}}
                                visible={this.state.visible}
                                onOk={this.cancelSendMsg}
                                onCancel={()=>{this.setState({visible:false})}}
                            >
                                <span >患者姓名：{msgInfo.patName}</span>
                                <span style={{marginLeft:50}}>自动发送日期：{msgInfo.autoSendDate}</span>

                                <div>
                                    <span >撤销原因：</span>
                                    <Select allowClear style={{ marginTop:30,width:'70%' }}
                                            onChange={(value,option)=> this.commonInputChange('selectReason',option.props.id)}
                                    >
                                        {
                                            this.state.reason.map((item,index) => {
                                                return <Option key={index} id={item.id} >{item.descripts}</Option>
                                            })
                                        }
                                    </Select>
                                </div>
                            </Modal>
                        </Card>
                    </Col>
                    <Col span={6}>
                        <Card bordered={false} size="small">
                            <div style={{fontSize:20}}>短信内容</div>
                            <div style={{marginTop:5,fontWeight:'normal',padding:10,fontSize:15,height:250,border:'2px solid #e8e8e8',borderRadius:8,backgroundColor:'#f5f5f5'}}>{msgInfo?.content}</div>
                        </Card>
                        <Card bordered={false} size="small">
                            <div style={{fontSize:20,marginBottom:5}}>短信记录</div>
                            {
                                contentRecordArr.length===0?<Empty style={{border:'2px solid #e8e8e8',borderRadius:8,margin:'unset',padding:'50% 0',height:500}} image={Empty.PRESENTED_IMAGE_SIMPLE} />:
                                    <Steps direction="vertical" size="small" style={{border:'2px solid #e8e8e8',borderRadius:8,margin:'unset',padding:'10px',height:550,marginTop:5}}>
                                        {
                                            contentRecordArr.map((item,index)=>{
                                                return <Step key={index} title={item.strInfo} status={this.switchStatus(item.statusCode)} />
                                            })
                                        }
                                    </Steps>
                            }
                        </Card>
                    </Col>
                </Row>
            </>
        )
    }
}
export default PreVisitRecords;
