import React, { useState, useEffect, useRef } from 'react';
import { Form, Input, Button, Table, Row, Col, Select, Modal, DatePicker, Space, message } from 'antd';
import { getCookie, disabledDate } from '@utils/index'
import '@common/common.less';
import moment from "moment";
import "moment/locale/zh-cn"
import './index.less'
import apiObj from '@api/index';
import EditProblem from './editProblem';
import ProblemContext from './problem-context';
const { post, api, xPost } = apiObj;
const { RangePicker } = DatePicker;
const { Option } = Select;
function FieldProblem() {
    useEffect(() => {
        getColumnResultPage();
        getColumnResultNumber()
        console.log(new Date((new Date() - 30 * 24 * 3600 * 1000)).toLocaleDateString());
        // getCurrentDataFront() {
        //     let time = new Date((new Date() - 30 * 24 * 3600 * 1000)).toLocaleDateString()
        //     return time
        // },
        // // 结束时间
        // getCurrentData() {
        //     let time = new Date().toLocaleDateString()
        //     return time
        // },
    }, []);
    const [logList, setLogList] = useState([]);
    const [total, setTotal] = useState(0);
    const [type, setType] = useState(0);//1新增 2修改
    const [visible, setVisible] = useState(false);
    const [size, setSize] = useState(15);
    const [current, setCurrent] = useState(1);
    const [probleData, setProbleData] = useState({});
    const [problemDetail, setProblemDetail] = useState(null);//详情数据
    const [title, setTitle] = useState();//正则式数据
    const [params, setParams] = useState({
        pages: 1,
        current: 1,
        size: 15,
        solveTimeStart: getCurrentDataFront().split('/').join('-') + ' 00:00:00',
        solveTimeEnd: getCurrentData().split('/').join('-') + ' 23:23:59'
    });
    const [form] = Form.useForm();
    let data = {
        pages: 1,
        current: 1,
        size: size,
    }
    //表格数据
    function getColumnResultPage(param) {
        post(api.getColumnResultPage, param || params).then((res) => {
            if (res.data.code === 200) {
                const data = res.data.data;
                setLogList(data.records);
                setTotal(data.total)
            }
        })
    }
    function getColumnResultNumber() {
        post(api.getColumnResultNumber, { hospitalId: getCookie('hospitalId') }).then((res) => {
            if (res.data.code === 200) {
                const data = res.data.data || [];
                setProbleData(data)
            }
        })
    }

    //修改
    function showModal(title, row, type) {
        setVisible(true)
        setProblemDetail(row)
        setTitle(title)
        setType(type)
    }
    //返回
    function cancel() {
        setVisible(false)
        setProblemDetail(null)
    }
    function userChange() {
        setVisible(false)
        getColumnResultPage();
    }
    function onSizeChange(current, pageSize) {
        params.current = current
        params.size = pageSize
        setSize(pageSize)
        setCurrent(current)
        setParams(params)
        getColumnResultPage()
    }
    function changePage(page, pageSize) {
        params.current = page
        params.size = pageSize
        setParams(params)
        setCurrent(page)
        getColumnResultPage()
    }
    const onFinish = (value) => {
        if (value.time) {
            value.solveTimeStart = moment(value.time[0]).format('YYYY-MM-DD 00:00:00');
            value.solveTimeEnd = moment(value.time[1]).format('YYYY-MM-DD 23:23:59');
        }
        delete value.time
        const param = {
            ...data,
            ...value,
        }
        setCurrent(1)
        setParams(param)
        getColumnResultPage(param);
    };
    const onReset = () => {
        setCurrent(1)
        setParams(data)
        form.resetFields();
        getColumnResultPage(data);
    };
    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: 'hosptialDatatmpCode', key: 'hosptialDatatmpCode' },
        { title: '文书标题', dataIndex: 'hosptialDatatmpName', key: 'hosptialDatatmpName' },
        { title: '质控模块名称', dataIndex: 'modeName', key: 'modeName' },
        { title: '表名称（中文）', dataIndex: 'tableCname', key: 'tableCname' },
        { title: '表名称（英文）', dataIndex: 'tableEname', key: 'tableEname' },
        { title: '字段名称（中文）', dataIndex: 'columnCname', key: 'columnCname' },
        { title: '字段名称（英文）', dataIndex: 'columnEname', key: 'columnEname' },
        { title: '上传字段值', dataIndex: 'tableVal', key: 'tableVal' },
        { title: '备注', dataIndex: 'description', key: 'description' },
        {
            title: '问题类型', dataIndex: 'type', render: (text, record) => {
                return record.type == 1 ? "数据缺失" : record.type == 2 ? "非标准值" : "正则校验失败";
            }
        },
        { title: '更新时间', dataIndex: 'auditTime', key: 'auditTime' },
        {
            title: '状态', dataIndex: 'isRequired', key: 'isRequired', render: (text, record) => {
                return record.isSolved == 1 ? "已解决" : "未解决";
            }
        },
        {
            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={{
                        isSolved: '', type: '', time: [moment(getCurrentDataFront()), moment(getCurrentData())]
                    }}
                >
                    <Row gutter={24}>
                        <Col span={6} key={0}>
                            <Form.Item label="日期" name="time">
                                <RangePicker
                                    disabledDate={disabledDate}
                                    placeholder={['开始时间', '结束时间']}
                                />
                            </Form.Item>
                        </Col>
                        <Col span={5} key={1}>
                            <Form.Item label="住院序号" name="behospitalCode">
                                <Input placeholder="住院序号" autoComplete='off' />
                            </Form.Item>
                        </Col>
                        <Col span={5} key={2}>
                            <Form.Item label="文书编号" name="recId">
                                <Input placeholder="文书编号" autoComplete='off' />
                            </Form.Item>
                        </Col>
                        <Col span={5} key={3}>
                            <Form.Item label="文书标题" name="recTitle">
                                <Input placeholder="文书标题" autoComplete='off' />
                            </Form.Item>
                        </Col>
                        <Col span={5} key={4}>
                            <Form.Item label="质控模块名称" name="modeName">
                                <Input placeholder="质控模块名称" autoComplete='off' />
                            </Form.Item>
                        </Col>
                        <Col span={5} key={5}>
                            <Form.Item label="问题类型" name="type">
                                <Select
                                    placeholder="请选择"
                                    allowClear
                                >
                                    <Option value="" key={0}>全部</Option>
                                    <Option value="1" key={1}>数据缺失</Option>
                                    <Option value="2" key={2}>非标准值</Option>
                                    <Option value="3" key={3}>正则校验失败</Option>
                                </Select>
                            </Form.Item>
                        </Col>
                        <Col span={5} key={7}>
                            <Form.Item label="状态" name="isSolved">
                                <Select
                                    placeholder="请选择"
                                    allowClear
                                >
                                    <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>
                    </Space>

                </div>
                <div className="table-data" style={{ justifyContent: 'left' }}>
                    <Row className="data-box">
                        <Col span={6} order={1} className="box-item">
                            <p>{probleData.notSolvedNonnull || '-'}</p>
                            <p>数据缺失</p>
                        </Col>
                        <Col span={6} order={2} className="box-item">
                            <p>{probleData.notSolvedStandardvalue || '-'}</p>
                            <p>非标准值</p>
                        </Col>
                        <Col span={6} order={3} className="box-item">
                            <p>{probleData.notSolvedRegular || '-'}</p>
                            <p>正则校验失败</p>
                        </Col>
                        <Col span={6} order={4} className="box-item item">
                            <p>{probleData.notSolved || '-'}</p>
                            <p>未处理</p>
                        </Col>
                    </Row>
                    <Row className="data-box">
                        <Col span={6} order={1} className="box-item">
                            <p>{probleData.resolvedNonnull || '-'}</p>
                            <p>数据缺失</p>
                        </Col>
                        <Col span={6} order={2} className="box-item">
                            <p>{probleData.resolvedStandardvalue || '-'}</p>
                            <p>非标准值</p>
                        </Col>
                        <Col span={6} order={3} className="box-item">
                            <p>{probleData.resolvedRegular || '-'}</p>
                            <p>正则校验失败</p>
                        </Col>
                        <Col span={6} order={4} className="box-item box">
                            <p>{probleData.resolved || '-'}</p>
                            <p>已处理</p>
                        </Col>
                    </Row>
                </div>
                <Table
                    columns={columns}
                    scroll={{ y: 'calc(100vh - 470px)' }}
                    dataSource={logList}
                    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
                    }} />
            </div>

            {visible && problemDetail ?
                <Modal
                    title={title}
                    okText='确定'
                    cancelText='取消'
                    width="500px"
                    visible={visible}
                    onCancel={cancel}
                    footer={null}
                    forceRender={true}
                >
                    <ProblemContext.Provider value={{ problemDetail, type }}>
                        <EditProblem userChange={userChange} />
                    </ProblemContext.Provider>

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

export default FieldProblem;