import React, { useState, useEffect, useRef } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { Form, Input, Button, Table, Row, Col, Select, Modal, DatePicker, Space, message, Spin } from 'antd';
import moment from "moment";
import "moment/locale/zh-cn"
import '@common/common.less';
import './index.less'
import apiObj from '@api/index';
import EditBlock from './editBlock';
import BlockContext from './block-context';
import { getValueFromEvent, disabledDate, getDaysBetween } from '@utils/index'
const { post, api, xPost } = apiObj;
const { Option } = Select;
function BlockLossManage() {

    const [blockList, setBlockList] = useState([]);
    const [total, setTotal] = useState(0);
    const [title, setTitle] = useState(0);
    const [visible, setVisible] = useState(false);
    const [size, setSize] = useState(15);
    const [loading, setLoading] = useState(false);
    const [current, setCurrent] = useState(1);
    const [type, setType] = useState(null);
    const [blockData, setBlockData] = useState({});
    const [blockDetail, setBlockDetail] = useState(null);//详情数据
    const [params, setParams] = useState({
        pages: 1,
        current: 1,
        size: 15,
        asc: ['status'],
        desc: ['gmt_modified'],
        startDate: getCurrentDataFront().split('/').join('-') + ' 00:00:00',
        endDate: getCurrentData().split('/').join('-') + ' 23:59:59'
    });
    const [form] = Form.useForm();
    let data = {
        pages: 1,
        current: 1,
        size: 15,
        asc: ['status'],
        desc: ['gmt_modified'],
        startDate: getCurrentDataFront().split('/').join('-') + ' 00:00:00',
        endDate: getCurrentData().split('/').join('-') + ' 23:59:59'
    }
    let date = {
        startDate: getCurrentDataFront().split('/').join('-') + ' 00:00:00',
        endDate: getCurrentData().split('/').join('-') + ' 23:59:59'
    }
    const { lossNum } = useSelector((state) => {
        return state.userInfo;
    });
    useEffect(() => {
        setCurrent(1)
        setParams(data)
        form.resetFields();
        getBlockLossPage(data);
        blockLossTypeGather(date)
    }, [lossNum]);
    //表格数据
    function getBlockLossPage(param) {
        const hide = message.loading('加载中...', 0);
        post(api.getBlockLossPage, param || params).then((res) => {
            hide()
            if (res.data.code === 200) {
                const data = res.data.data;
                setBlockList(data.records);
                setTotal(data.total)
            } 
        }).catch((err) => {
            hide()
        })
    }
    //丢失量分类汇总
    function blockLossTypeGather(param) {
        post(api.blockLossTypeGather, param).then((res) => {
            if (res.data.code === 200) {
                const data = res.data.data;
                setBlockData(data)
            }
        })
    }
    //修改
    function showModal(title, row, type) {
        setVisible(true)
        setBlockDetail(row)
        setTitle(title)
        setType(type)
    }
    function onSizeChange(current, pageSize) {
        params.current = current
        params.size = pageSize
        setSize(pageSize)
        setCurrent(current)
        setParams(params)
    }
    function changePage(page, pageSize) {
        params.current = page
        params.size = pageSize
        setParams(params)
        setCurrent(page)
        getBlockLossPage()
    }

    //返回
    function cancel() {
        setVisible(false)
        setBlockDetail(null)
    }
    function userChange(type) {
        if (type == 2) {
            params.current = 1
            setParams(params)
            setCurrent(1)
            getBlockLossPage();
        }
        setVisible(false)
        blockLossTypeGather({ startDate: params.startDate, endDate: params.endDate })
        setBlockDetail(null)
    }
    const onFinish = (value) => {
        value.startDate = moment(value.startDate).format('YYYY-MM-DD 00:00:00');
        value.endDate = moment(value.endDate).format('YYYY-MM-DD 23:59:59');
        if (value.startDate > value.endDate) {
            message.warning('开始时间不能大于结束时间');
            return
        } else if (getDaysBetween(value.startDate, value.endDate) > 364) {
            message.warning('开始时间与结束时间相差不能超过一年');
            return
        }
        params.current = 1
        const param = {
            ...params,
            ...value,
        }
        setCurrent(1)
        setParams(param)
        getBlockLossPage(param);
        blockLossTypeGather({ startDate: value.startDate, endDate: value.endDate })
    };
    const onReset = () => {
        setCurrent(1)
        setSize(15)
        setParams(data)
        form.resetFields();
        getBlockLossPage(data);
        blockLossTypeGather(date)
    };
    function getCurrentDataFront() {
        let time = new Date((new Date() - 30 * 24 * 3600 * 1000)).toLocaleDateString()
        return time
    }
    // 结束时间
    function getCurrentData() {
        let time = new Date().toLocaleDateString()
        return time
    }
    const columns = [
        { title: '序号', dataIndex: 'index', render: (text, record, index) => (current - 1) * params.size + index + 1 },
        { title: '住院序号', dataIndex: 'behospitalCode', key: 'behospitalCode' },
        {
            title: '文书编号', dataIndex: 'recId', key: 'recId', render: (text, record) => {
                return record.recId || '-';
            }
        },
        {
            title: '文书标题', dataIndex: 'recTitle', key: 'recTitle', render: (text, record) => {
                return record.recTitle || '-';
            }
        },
        {
            title: '丢失原因', dataIndex: 'lossCause', key: 'lossCause', render: (text, record) => {
                return record.lossCause ? record.lossCause.length > 15 ? <span title={record.lossCause}>{record.lossCause.substring(0, 15) + '...'}</span> : record.lossCause : '-';
            }
        },
        {
            title: '丢失类型', dataIndex: 'lossType', key: 'lossType', render: (text, record) => {
                return (<span>{record.lossType == 0 ? '文书丢失' : record.lossType == 1 ? '病案首页丢失' : record.lossType == 2 ? '患者信息丢失' : '-'}</span>);
            }
        },
        {
            title: '丢失途径', dataIndex: 'lossWay', key: 'lossWay', render: (text, record) => {
                return (<span>{record.lossWay == 0 ? '外部丢失' : record.lossWay == 1 ? '内部丢失' : '-'}</span>);
            }
        },
        {
            title: '更新时间', dataIndex: 'gmtModified', key: 'gmtModified', render: (text, record) => {
                return record.gmtModified || '-';
            }
        },
        {
            title: '状态', key: 'status', render: (text, record) => {
                return (<span className={record.status === '0' ? 'Delete' : 'Adopt'}>{record.status == 0 ? '已丢失' : record.status == 1 ? '已恢复' : '-'}</span>);
            }
        },
        {
            title: '核查结果', key: 'isAudited', render: (text, record) => {
                return (<span className={(record.isAudited === '0') ? 'delete' : (record.isAudited === '1') ? 'adopt' : 'disable'}>{record.isAudited == 0 ? '核查未通过' : record.isAudited == 1 ? '核查通过' : record.isAudited == 2 ? '未核查' : '-'}</span>);
            }
        },
        {
            title: '操作', dataIndex: 'key', render: (text, record) => (
                <Space size="middle">
                    <a onClick={e => showModal('修改病历数据块丢失明细', record, 3)}>修改</a>
                </Space>
            )
        }
    ];
    return (
        <div className="wrapper">
            <div className="filter-box">
                <Form
                    form={form}
                    name="normal_login"
                    onFinish={onFinish}
                    initialValues={{ lossType: '', lossWay: '', isAudited: '', status: '', startDate: moment(getCurrentDataFront()), endDate: moment(getCurrentData()) }}
                >
                    <Row gutter={24}>
                        <Col span={7} key={0}>
                            <Form.Item label="日期" >
                                <Form.Item name="startDate" className='times'>
                                    <DatePicker
                                        allowClear={false}
                                        disabledDate={disabledDate}
                                        placeholder="请选择开始日期"
                                    />

                                </Form.Item>
                                <span style={{ margin: '0 5px', position: 'relative', top: '2px' }}>-</span>
                                <Form.Item name="endDate" className='times'>
                                    <DatePicker
                                        allowClear={false}
                                        disabledDate={disabledDate}
                                        placeholder="请选择结束日期"
                                    />
                                </Form.Item>
                            </Form.Item>
                        </Col>
                        <Col span={5} key={1}>
                            <Form.Item label="住院序号" name="behospitalCode" getValueFromEvent={getValueFromEvent}>
                                <Input placeholder="请输入" autoComplete='off' allowClear maxLength='30' />
                            </Form.Item>
                        </Col>
                        <Col span={5} key={2}>
                            <Form.Item label="文书编号" name="recId" getValueFromEvent={getValueFromEvent}>
                                <Input placeholder="请输入" autoComplete='off' allowClear maxLength='30' />
                            </Form.Item>
                        </Col>
                        <Col span={5} key={3}>
                            <Form.Item label="文书标题" name="recTitle" getValueFromEvent={getValueFromEvent}>
                                <Input placeholder="请输入" autoComplete='off' allowClear maxLength='30' />
                            </Form.Item>
                        </Col>
                        <Col span={5} key={4}>
                            <Form.Item label="丢失类型" name="lossType">
                                <Select
                                    placeholder="请选择"
                                >
                                    <Option value="" key={3}>全部</Option>
                                    <Option value="0" key={0}>文书丢失</Option>
                                    <Option value="1" key={1}>病案首页丢失</Option>
                                    <Option value="2" key={2}>患者信息丢失</Option>
                                </Select>
                            </Form.Item>
                        </Col>
                        <Col span={5} key={5}>
                            <Form.Item label="丢失途径" name="lossWay">
                                <Select
                                    placeholder="请选择"
                                >
                                    <Option value="" key={2}>全部</Option>
                                    <Option value="0" key={0}>外部丢失</Option>
                                    <Option value="1" key={1}>内部丢失</Option>
                                </Select>
                            </Form.Item>
                        </Col>
                        <Col span={5} key={6}>
                            <Form.Item label="核查结果" name="isAudited">
                                <Select
                                    placeholder="请选择"
                                >
                                    <Option value="" key={3}>全部</Option>
                                    <Option value="0" key={0}>核查未通过</Option>
                                    <Option value="1" key={1}>核查通过</Option>
                                    <Option value="2" key={2}>未核查</Option>
                                </Select>
                            </Form.Item>
                        </Col>
                        <Col span={5} key={7}>
                            <Form.Item label="状态" name="status">
                                <Select
                                    placeholder="请选择"
                                >
                                    <Option value="" key={3}>全部</Option>
                                    <Option value="0" key={0}>已丢失</Option>
                                    <Option value="1" key={1}>已恢复</Option>
                                </Select>
                            </Form.Item>
                        </Col>
                        <Col span={4} key={8}>
                            <Form.Item>
                                <Button type="primary" htmlType="submit">
                                    查询
                                </Button>
                                <Button onClick={onReset}>
                                    重置
                                </Button>
                            </Form.Item>
                        </Col>
                    </Row>
                </Form>
            </div>

            <div className="table">
                <div className="table-header">
                    <h2 className="table-title">病历数据块丢失明细</h2>
                    <Space size="middle">
                        <Button type="primary" onClick={() => showModal('数据补录设置', { behospitalCode: '', time: '' }, 1)}>数据补录</Button>
                        <Button type="primary" onClick={() => showModal('数据对比设置', { behospitalCode: '', time: '' }, 2)}>数据对比</Button>
                    </Space>

                </div>
                <div className="table-data">
                    <Row className="data-box">
                        <Col span={6} order={1} className="data-item">
                            <p>{blockData.hisNum || blockData.hisNum == 0 ? blockData.hisNum : '-'}</p>
                            <p>HIS</p>
                        </Col>
                        <Col span={6} order={2} className="data-item">
                            <p>{blockData.logNum || blockData.logNum == 0 ? blockData.logNum : '-'}</p>
                            <p>接口日志</p>
                        </Col>
                        <Col span={6} order={3} className="data-item">
                            <p>{blockData.realNum || blockData.realNum == 0 ? blockData.realNum : '-'}</p>
                            <p>实际</p>
                        </Col>
                        <Col span={6} order={4} className="data-item item" >
                            <p>{blockData.allLossNum || blockData.allLossNum == 0 ? blockData.allLossNum : '-'}</p>
                            <p>合计丢失</p>
                        </Col>
                    </Row>
                    <Row className="data-box">
                        <Col span={6} order={1} className="box-item">
                            <p>{blockData.outRecNum || blockData.outRecNum == 0 ? blockData.outRecNum : '-'}</p>
                            <p>文书丢失</p>
                        </Col>
                        <Col span={6} order={2} className="box-item">
                            <p>{blockData.outHomePageNum || blockData.outHomePageNum == 0 ? blockData.outHomePageNum : '-'}</p>
                            <p>病案首页丢失</p>
                        </Col>
                        <Col span={6} order={3} className="box-item">
                            <p>{blockData.outCodeNum || blockData.outCodeNum == 0 ? blockData.outCodeNum : '-'}</p>
                            <p>患者信息丢失</p>
                        </Col>
                        <Col span={6} order={4} className="box-item box">
                            <p>{blockData.outLossNum || blockData.outLossNum == 0 ? blockData.outLossNum : '-'}</p>
                            <p>外部丢失</p>
                        </Col>
                    </Row>
                    <Row className="data-box">
                        <Col span={6} order={1} className="box-item">
                            <p>{blockData.inRecNum || blockData.inRecNum == 0 ? blockData.inRecNum : '-'}</p>
                            <p>文书丢失</p>
                        </Col>
                        <Col span={6} order={2} className="box-item">
                            <p>{blockData.inHomePageNum || blockData.inHomePageNum == 0 ? blockData.inHomePageNum : '-'}</p>
                            <p>病案首页丢失</p>
                        </Col>
                        <Col span={6} order={3} className="box-item">
                            <p>{blockData.inCodeNum || blockData.inCodeNum == 0 ? blockData.inCodeNum : '-'}</p>
                            <p>患者信息丢失</p>
                        </Col>
                        <Col span={6} order={4} className="box-item box">
                            <p>{blockData.inLossNum || blockData.inLossNum == 0 ? blockData.inLossNum : '-'}</p>
                            <p>内部丢失</p>
                        </Col>
                    </Row>
                </div>
                <Table
                    columns={columns}
                    dataSource={blockList}
                    rowKey={record => record.id}
                    pagination={{
                        pageSize: size,
                        size: 'small',
                        current: current,
                        showSizeChanger: true,
                        pageSizeOptions: ['15', '30', '60', '120'],
                        showTotal: (total, range) => `第${range[0]}-${range[1]} 条/共 ${total} 条数据`,
                        onShowSizeChange: (current, pageSize) => onSizeChange(current, pageSize), // 改变每页数量时更新显示
                        onChange: (page, pageSize) => changePage(page, pageSize),//点击页码事件
                        total: total,
                        showQuickJumper:true,
                    }} />

            </div>
            {visible && blockDetail ?
                <Modal
                    title={title}
                    okText='确定'
                    cancelText='取消'
                    width="500px"
                    visible={visible}
                    onCancel={cancel}
                    footer={null}
                    forceRender={true}
                    maskClosable={false}
                >
                    <BlockContext.Provider value={{ blockDetail, type }}>
                        <EditBlock cancel={cancel} userChange={userChange} />
                    </BlockContext.Provider>

                </Modal>
                : ''}
        </div >
    )
}

export default BlockLossManage;