import React,{Component} from 'react';
import {
    Button, Col, Row, DatePicker, Select, message, Modal, Form, Table
} from 'antd';
import { $http } from '../../containers/config/https';
import '../../assets/css/system.css';
import ColumnAuthoritysModel from "../columnAuthority/ColumnAuthoritysModel";
const Option = Select.Option;
const { RangePicker } = DatePicker;
/**
 * @ByYQL: 三医监管平台数据上传
 * Create 2022-4-11
 */
const ThreeHealthManage = Form.create()(
    class extends Component {
        constructor(props) {
            super(props);
            this.state = {
                outPatDataLeft:[],   //左侧列表数据
                outPatDataRight:[],  //右侧列表数据
                pickerdate:[],       //筛选条件-日期
                selectstate:"0",       //筛选条件-状态
                rowIds:'',              //左侧列表选择项id
                selectedRowKeys: [],    //右侧列表选择项
                detailsColumns:[],       //详细上传数据的Table表头
                detailsData:[],       //详细上传数据的Table数据源
                detailModalStatus:false  //详细数据弹窗状态
            };
        }

        componentWillMount() {
            this.getMainTableColumnsLeft();
            this.getMainTableColumnsRight();
        }

        //日期回调
        onPickerChange = (e,values) => {
            this.setState({pickerdate:values})
        };

        //状态选择回调
        onStateSelectChange = (e) => {
            this.setState({selectstate:e})
        };

        //查询
        getThreeHealthDataList = () => {
            const {pickerdate,selectstate,rowIds} = this.state;
            let that = this
            let data = {
                params: [{
                    datatype: "BDHEALTH",
                    ssmParam: {
                        seqNo: 7,
                        wsReq: {
                            beginDate:pickerdate[0],
                            endDate:pickerdate[1],
                            status:selectstate
                        }
                    }
                }]
            };
            $http.post('urlS', this, {
                code: "rhip001",
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        if(res.result?.Data.length > 0){
                            let _outPatDataRight = [];
                            res.result?.Data.map((item,index) => {
                                if(item.id == rowIds){
                                    _outPatDataRight = item?.details
                                }
                            });
                            that.setState({outPatDataLeft:res.result?.Data , outPatDataRight: _outPatDataRight})
                        }else{
                            message.warning('未查询到数据...')
                        }
                    }
                }
            })
        };

        //刷新
        toUpdateData = () => {
            const {pickerdate} = this.state;
            let data = {
                params: [{
                    datatype: "BDHEALTH",
                    ssmParam: {
                        seqNo: 7,
                        wsReq: {
                            beginDate:pickerdate[0],
                            endDate:pickerdate[1],
                            HISCode:"H03"
                        }
                    }
                }]
            };
            $http.post('urlS', this, {
                code: "rhip002",
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        this.setState({selectedRowKeys:[]},function () {
                            this.getThreeHealthDataList()
                        })
                    }
                }
            })
        };

        //上传
        onUploadChange = () => {
            const {selectedRowKeys} = this.state;
            let data = {
                params: [{
                    datatype: "BDHEALTH",
                    ssmParam: {
                        seqNo: 7,
                        wsReq: {
                            ids:selectedRowKeys
                        }
                    }
                }]
            };
            $http.post('urlS', this, {
                code: "rhip003",
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        message.success(res.errorMessage);
                    } else {
                        Modal.error({
                            title: res.errorMessage,
                            content: (
                                <div>
                                    {res.result?.Data?.tableFailed.map((item,index) => {
                                        return (<p>{item}</p>)
                                    })}
                                </div>
                            )
                        });
                    }
                    this.getThreeHealthDataList()
                }
            })
        };

        //点击Row
        onClickRow = (record) => {
            return {
                onClick: () => {
                    this.setState({rowIds: record.id,outPatDataRight:record?.details});
                },
            };
        };
        //点击行
        setRowClassNames = (record) => {
            return record.id === this.state.rowIds ? 'clickRowStyle' : '';
        };

        // 获取三医监管平台主列表   ThreeHealthLeft
        // 获取三医监管平台详情列表 ThreeHealthRight
        getMainTableColumnsLeft = () => {
            let data = {
                params: [{
                    compontName: "ThreeHealthLeft",
                    type: 'C',
                }]
            };
            $http.post('urlS', this, {
                code: '01040073',
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        let arr = res.result.C && res.result.C.length > 0 ? JSON.parse(JSON.stringify(res.result.C)).map((item, index) => {
                            return {
                                ...item,
                                key: index + 1,
                                title: <div onDoubleClick={() => this.mainColumnRefLeft.onOpenModel()}>{item.title}</div>,
                                render: (text, record) => {
                                    if(item.code === "status"){
                                        return (<span style={{color: text === "已完成"? "#19c909" : "" }}>{text}</span>)
                                    }
                                    return text;
                                }
                            }
                        }) : '';
                        let filterArr = arr.filter(function (item) { return item.display === 'Y' });
                        this.setState({ columnsLeft: filterArr})
                    }
                }
            })
        };
        getMainTableColumnsRight = () => {
            let data = {
                params: [{
                    compontName: "ThreeHealthRight",
                    type: 'C',
                }]
            };
            $http.post('urlS', this, {
                code: '01040073',
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        let arr = res.result.C && res.result.C.length > 0 ? JSON.parse(JSON.stringify(res.result.C)).map((item, index) => {
                            return {
                                ...item,
                                key: index + 1,
                                title: <div onDoubleClick={() => this.mainColumnRefRight.onOpenModel()}>{item.title}</div>,
                                render: (text, record) => {
                                    if(item.code === "uploadStatus"){
                                        return (<span style={{color: text === "上传成功"? "#19c909" : text === "上传失败"? "#ff000f" : "" }}>{text}</span>)
                                    }
                                    return text;
                                }
                            }
                        }) : '';
                        let filterArr = arr.filter(function (item) { return item.display === 'Y' });
                        console.log('filterArr',filterArr)
                        this.setState({ columnsRight: filterArr})
                    }
                }
            })
        };

        onMainColumnRefLeft = (ref) => {
            this.mainColumnRefLeft = ref;
        };
        onMainColumnRefRight = (ref) => {
            this.mainColumnRefRight = ref;
        };

        queryDetailsUpload =(record)=>{
            let data = {
                params: [{
                    datatype: "BDHEALTH",
                    ssmParam: {
                        seqNo: 7,
                        wsReq:{
                            tableCode:record.tableCode,  //重新上传的表的code
                            uploadDate:record.beginDate //查询上传数据详情的日期
                        }
                    }
                }]
            };
            $http.post('urlS', this, {
                code: 'rhip004',
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        let s = res.result.Data[0]
                        // 取结果中所有的key值放进数组
                        let keys = [];
                        for(let k in s) keys.push(k);
                        // 遍历key值数组将所有的值设置成成表头信息
                        let columns = []
                        keys.map((item,index)=>{
                            columns.push({
                                key:item,
                                title: item,
                                dataIndex: item,
                                align: 'center',
                                width: '160px',
                            })
                        })
                        let list = res.result.Data
                        //给每条数据添加唯一key值
                        for (let i = 0; i < list.length; i++) {
                            list[i].key = i;
                        }
                        this.setState({ detailModalStatus: true})
                        this.setState({ detailColumns: columns})
                        this.setState({ detailsData: list})
                    }
                }
            })
        }

        handleViewOrders=(record)=>{
            let data = {
                params: [
                    {
                        datatype: "BDHEALTH",
                        ssmParam: {
                            seqNo: 7,
                            wsReq:{
                                tableCode:record.tableCode,  //重新上传的表的code
                                uploadDate:record.beginDate  //重新上传数据详情的日期
                            }
                        }
                    }
                ]
            };
            $http.post('urlS', this, {
                code: 'rhip005',
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        message.success(res.errorMessage)
                    }else {
                        message.error(res.errorMessage)
                    }
                }
            })
        }


        render() {
            const {columnsLeft,columnsRight,selectstate,selectedRowKeys } = this.state;
            const rowSelection = {
                selectedRowKeys,
                onChange:(selectedRowKeys, selectedRows) => {
                    this.setState({ selectedRowKeys});
                },
                getCheckboxProps: (record) => ({
                    disabled: record.uploadStatus === '上传成功',
                    name: record.uploadStatus,
                })
            };

            const operationObj = {
                width: 80,
                title: '操作',
                align: 'center',
                key: 'operation',
                render: (text, record) => (
                    <span className='span' onClick={() => this.handleViewOrders(record)}>重新上传</span>
                ),
            };

            return (
                <Row gutter={10}>
                    <Col span={10}>
                        <Row justify='space-between'>
                            <Col span={22}>
                                <RangePicker onChange={(e,values) => this.onPickerChange(e,values)}/>
                                <span style={{paddingLeft:30 }}>状态：</span>
                                <Select defaultValue={selectstate} style={{width:'140px'}} onChange={(e) => this.onStateSelectChange(e)}>
                                    <Option value="0">全部</Option>
                                    <Option value="1">已完成</Option>
                                    <Option value="2">部分完成</Option>
                                    <Option value="3">未完成</Option>
                                </Select>
                            </Col>
                            <Col span={2}>
                                <Button type="primary" onClick={() => this.getThreeHealthDataList()}>查 询</Button>
                            </Col>
                        </Row>
                        <Table
                            style={{marginTop:10}}
                            columns={columnsLeft && columnsLeft.length > 0 ? columnsLeft : []}
                            dataSource={this.state.outPatDataLeft}
                            pagination={true}
                            rowKey={record => record.key}
                            onRow={this.onClickRow}
                            rowClassName={this.setRowClassNames}
                            bordered
                        />
                        <ColumnAuthoritysModel
                            clientWidth='800px'
                            compontName='ThreeHealthLeft'
                            configType="C"
                            onRef={this.onMainColumnRefLeft}
                            reloadData={this.getMainTableColumnsLeft}
                        />
                    </Col>
                    <Col span={14}>
                        <Row>
                            <Col span={3} offset={18}>
                                <Button type="primary" onClick={() => this.toUpdateData()}>刷 新</Button>
                            </Col>
                            <Col span={3}>
                                <Button type="primary" style={{width:'120px'}} onClick={() => this.onUploadChange()}>上 传</Button>
                            </Col>
                        </Row>
                        <Table
                            style={{marginTop:10}}
                            columns={columnsRight && columnsRight.length > 0 ? [...columnsRight,operationObj] : []}
                            dataSource={this.state.outPatDataRight}
                            pagination={false}
                            rowKey={record => record?.id}
                            rowSelection={rowSelection}
                            bordered
                            /*
                                * @ByWRX:双击查询上传数据详情（单表）
                                * Create:2022-8-9
                            */
                            onRow={(record) => ({
                                onDoubleClick: () => {
                                    this.queryDetailsUpload(record)
                                }
                            })}
                        />
                        <ColumnAuthoritysModel
                            clientWidth='800px'
                            compontName='ThreeHealthRight'
                            configType="C"
                            onRef={this.onMainColumnRefRight}
                            reloadData={this.getMainTableColumnsRight}
                        />
                        {/*新增医院弹框*/}
                        <Modal bodyStyle={{height: 260}} title="详细上传信息"
                               visible={this.state.detailModalStatus}
                               onOk={()=>{}}
                               onCancel={()=>{this.setState({detailModalStatus:false})}}
                               width={700}
                        >
                            <Table bordered
                                   dataSource={this.state.detailsData}
                                   columns={this.state.detailColumns}
                                   pagination={false}
                                   scroll={{x:600}}
                            />
                        </Modal>
                    </Col>
                </Row>
            );
        }
    });
export default ThreeHealthManage;
