/*
 * Creator:     ML
 * CreatDate:   2020-05-19
 * descripts：   ---评价审核
 * */
import React from 'react';
import { Form, Row, Col, Input, Select, Button, DatePicker, Popconfirm, Modal, Table, Icon, Pagination, message, Divider, Tooltip } from 'antd';
import moment from 'moment';
import { $http } from '../../containers/config/https';
import store from '../../store';
import CommonPagination from 'components/pagination/index';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';
import RangeDatePicker from 'components/rangePicker/index';

const FormItem = Form.Item;
const Option = Select.Option;
const paddRightCol = {
    paddingRight: "0px"
}
const formItemLayout = { // label 和input宽度
    labelCol: { span: 7 },
    wrapperCol: { span: 17 },
}
const formItemLayoutName = {
    labelCol: { span: 6 },
    wrapperCol: { span: 18 }
}
const searchColConfig = {
    xs: { span: 24 },
    sm: { span: 12 },
    md: { span: 10 },
    lg: { span: 6 }
}
const formItemLayoutType = {
    labelCol: { span: 5 },
    wrapperCol: { span: 18 }
}
const EvaluationReview = Form.create()(
    class EvaluationReview extends React.Component {
        constructor(props) {
            super(props)
            let userData = JSON.parse(sessionStorage.getItem('userData'))
            this.state = {
                userData: userData,
                loading: false,
                visible: false,
                baseParms: [],//下拉框数据
                total: 0,//表格总数据
                bedData: [],//查询数据
                values: {},//查询条件数据
                searchLoading: false,//查询请求
                initCard: '',
                rowIds: '',//表格行选中 页面数据
                bindVail: true,//点击绑定前是否通过验证
                bindLoading: false,//点击绑定loading
                headerHeight: "",
                page: 1,
                pageSize: 10,
                size: "small",
                search: "",
                isShowCommonTableModal: false,
                pageSizeTop: 10,
                pageTop: 1,
                startDate: moment().format('YYYY-MM-DD'),
                endDate: moment().format('YYYY-MM-DD'),
                selectedRow_right:[]
            }
        }
        componentDidMount() {
            // 初始化设置table的高度以及表体的高度
            document.querySelector('.ant-table-body').style.height = store.getState().tableHeight.y + 88 + 'px';
            let box = document.querySelector(".department-header");
            if (box) { //此处在加一层判断，更加严密，如果box存在的情况下获取
                this.setState({ headerHeight: box.offsetHeight })
            }
            this.getHopSelect()
            this.findData()
            this.getMainTableColumns()
            this.getStatus()
        }
        //获取医院下拉框
        getHopSelect = () => {
            let data = {
                params: [{
                    hospID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).hospID : "",
                    logonGroupID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).groupID : "",
                    logonHospID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).hospID : "",
                }],
            }
            $http.post('urlS', this, {
                code: '01040001',
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        this.setState({
                            hospArr: res.result
                        })
                    }
                }
            })
        }
        //医院选择带出科室
        handleBaseHosp = (id) => {
            this.props.form.setFieldsValue({ locID: undefined })
            if (id) {
                this.setState({
                    hosID: id
                }, () => {
                    this.getPublicBaseLocSelect()
                })
            } else {
                this.setState({
                    hosID: "",
                    publicBaseLocArr: [],
                }, () => {
                    // this.getPublicBaseLocSelect()
                })
            }

        }
        //获取科室下拉框
        getPublicBaseLocSelect = () => {
            let data = {}
            data = {
                params: [{
                    hospID: this.state.hosID || "",
                    locTypeID: this.state.locID || ""
                }],
            }
            $http.post('urlS', this, {
                code: '01050029',
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0 && res.result.Data) {
                        let arr = res.result.Data && res.result.Data.map((item, index) => {
                            res.result.Data[index].key = Number(index)
                        })
                        this.setState({
                            publicBaseLocArr: res.result.Data,
                        })
                    } else {

                    }
                }
            })
        }
        //动态表头
        onColumnRef = (ref) => {
            this.columnRef = ref;
        }
        // 获取主列表columns
        getMainTableColumns = () => {
            let data = {
                params: [{
                    compontName: "PatientEvaluationInformation",
                    reactCode: ['PatientEvaluationInformation'],
                    type: 'C',
                }]
            }
            $http.post('urlS', this, {
                code: '01040073',
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        let arr = res.result && res.result.C.length > 0 ? JSON.parse(JSON.stringify(res.result.C)).map(item => {
                            return {
                                align: item.align,
                                widthNum: parseInt(item.width),
                                width: item.width,
                                dataIndex: item.dataIndex,
                                title: <div onDoubleClick={() => this.columnRef.onOpenModel()}>{item.title}</div>,
                                display: item.display,
                                key: item.seqNo,
                                // render: (text, record) => {
                                //    if (item.code == "status") {
                                //      return (
                                //      <span>{record.status=="Y"?"生效":"失效"}</span>
                                //      )
                                //    }
                                //    return text
                                //  }
                            }
                        }) : '';
                        let filterArr = arr.filter(function (item) { return item.display === 'Y' });
                        let seqArr = {
                            align: "center",
                            widthNum: 140,
                            width: "120px",
                            code: "edit",
                            dataIndex: "edit",
                            title: "操作",
                            display: "Y",
                            render: (value, row, index) => {
                                if(row.statusID=="1"){
                                    return (
                                        <span>
                                            <a onClick={() => this.toggleEditable("2",row)}>通过</a>
                                            <Divider type="vertical" />
                                            <Popconfirm title="是否要拒绝该评价" onConfirm={() => this.toggleEditable("3",row)}>
                                                <a style={{ color: "red" }} >拒绝</a>
                                            </Popconfirm>
                                        </span>
                                    ) 
                                }else{
                                   return(
                                    <span>--</span>
                                   )
                                }
                                return value
                               
                            },
                        }
                        filterArr.push(seqArr)
                        this.setState({ columns: filterArr, widthTotal: res.totalWidth })
                        // console.log("res.totalWidth",res.totalWidth)
                    }
                }
            })
        }

        // 修改page和pageSize 跳转至---
        onChange = (e, pageSize) => {
            this.setState({ page: e, pageSize: this.state.pageSize }, () => {
                // 重新调用查询方法
                let { values } = this.state;
                this.getFindDate(values);
            })
        }
        //下拉选择页数
        onShowSizeChange = (page, pageSize) => {
            this.setState({ page: 1, pageSize: pageSize }, () => {
                // 重新调用查询方法
                let { values } = this.state;
                this.getFindDate(values, "search");
            })
        }
        // 显示分页总条数
        showTotal(total) {
            return `共 ${total} 条`;
        }

        startChange(date) {
            this.setState({
                startDate: date,
            })
        }
        endChange(date) {
            this.setState({
                endDate: date,
            })
        }
        //获取查询数据
        getFindDate = ( e) => {
            if (this.state.total == 0) {
                this.setState({
                    searchLoading: true
                })
            }
            let { page, pageSize, values} = this.state;
            let data = {}
            data = {
                params: [{
                    hospID:this.state.hosID || "",
                    docName: values && values.docName || "",
                    locID: values && values.locID || "",
                    statusID: values && values.statusID || "",
                    patName: values && values.patName || "",
                    startDate: this.state.startDate ? moment(this.state.startDate).format('YYYY-MM-DD') : undefined,//生效日期
                    endDate: this.state.endDate ? moment(this.state.endDate).format('YYYY-MM-DD') : undefined,//失效日期
                }],
                pagination: [{
                    pageSize: pageSize,
                    currentPage: page,
                }]
            }
            $http.post('urlS', this, {
                code: '03100030',
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0 && res.result) {
                        this.setState({
                            searchLoading: false,
                            search: e
                        })
                        for (var i = 0; i < res.result.length; i++) {
                            res.result[i].key = i + 'bed'
                        }
                        this.setState({ bedData: res.result, total: res.TotalCount, }, () => {
                        })
                    } else {
                        this.setState({
                            searchLoading: false
                        })
                    }
                    //  if (res.result.data && res.result.data.length == 0 && res.result.totalCount > 0) {
                    //      let prevPage = this.state.page - 1
                    //      this.onChange(prevPage, this.state.pageSize)
                    //  }
                },
                error: function () {
                    this.setState({
                        searchLoading: false
                    })
                }
            })

        }
        //点击查询---
        findData = () => {
            this.props.form.validateFields((err, values) => {
                if (!err) {
                    this.setState({
                        values: values,
                        rowIds: "",
                        selectedRowKeys_right:[],
                        selectedRow_right:[]
                    }, () => {
                        this.onShowSizeChange("1", this.state.pageSize)
                    })
                }
            })
        }
      
     
        //点击查询后 表格行
        setRowClassNames = (record) => {
            return record.ID === this.state.rowIds ? 'clickRowStyle' : '';
        }
        //点击Row
        onClickRow = (record) => {
            return {
                onClick: () => {
                    this.setState({
                        parms: record,
                    })
                    if (this.state.rowId === "") {
                        this.setState({
                            rowIds: record.ID,
                        });
                    } else {
                        if (this.state.rowId !== record.ID) {
                            this.setState({
                                rowIds: record.ID,
                            });
                        } else {
                            this.setState({
                                rowIds: "",
                                detailInfo: {},
                            });
                        }
                    }
                },
            };
        }
        //通过 /拒绝 
        toggleEditable = (num, row,) => {
            const {selectedRowKeys_right} =this.state
            let arr = []
            if(row){
                arr.push(row.ID)
            }
                let datas = {}
                datas = {
                    params: [{
                        userID: JSON.parse(sessionStorage.userData).userID || '',
                        data: arr&&arr.length>0?arr:selectedRowKeys_right,
                        statusID:num
                    }],
                }
                $http.post('urlS', this, {
                    code: '03100031',
                    data: datas,
                    success: function (res) {
                        if (+res.errorCode === 0) {
                            if(num=="2"){
                                message.success("已通过")
                            }else{
                                message.success("已拒绝")
                            } 
                            this.setState({
                                selectedRowKeys_right:[],
                                selectedRow_right:[]
                            },)
                            this.getFindDate()
                        }
                    }
                })
        }
        //获取状态
        getStatus = () => {
            let data = {
                params: [{

                }],
            }
            $http.post('urlS', this, {
                code: '03100089',
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        this.setState({
                            statusArr: res.result
                        })
                    }
                }
            })
        }


        onRef = (ref) => {
            this.childs = ref;
        }
        setRowClassNamePublic = (record) => {
            return (record.id || record.id) === this.state.rowMedID ? 'clickRowStyle' : '';
        }
        onClickRowPublic = (record) => {
            // console.log("onClickRowPublic", record)
            return {
                onClick: () => {
                    this.setState({
                        rowMedID: record.id
                    })
                },
                onDoubleClick: () => {
                    this.rowClick(record)
                }
            }

        }
        handleValue = () => {

        }
        //分页切换
        changePageSize(current, pageSize) {
            this.setState({ pageSizeTop: pageSize, pageTop: current }, () => {
            });
        }
        rowClick = (record) => {
            this.setState({
                rowMedID: record.id
            }, () => {
                this.props.form.setFieldsValue({ getItem: record.descripts })
                this.childs.handleCancel();
            })
        }
        render() {
            const { getFieldDecorator } = this.props.form;
            const { searchLoading, columns } = this.state;
            const mesIcon = <Icon type="exclamation-circle" />
            //医院
            let hosOp = []
            this.state.hospArr && this.state.hospArr.map((item) => {
                hosOp.push(<Option key={item.id} onClick={(e, ) => this.handleBaseHosp(item.id)} role={item.descripts + '^' + item.descriptsSPCode} value={String(item.id)}>{item.descripts}</Option>)
            })
            //科室类型
            let locOp = []
            this.state.publicBaseLocArr && this.state.publicBaseLocArr.map(item => {
                locOp.push(<Option key={item.id} role={item.descripts + '^' + item.descriptsSPCode} title={item.descripts} value={String(item.id)}>{item.descripts}</Option>)
            })
            //状态
            let statusOp = []
            this.state.statusArr && this.state.statusArr.map((item) => {
                statusOp.push(<Option key={item.id} value={String(item.id)} role={item.descripts + '^' + item.descriptsSPCode} >{item.descripts}</Option>)
            })
            const rowSelection_right = {
                selectedRowKeys: this.state.selectedRowKeys_right,
                onChange: (selectedRowKeys, selectedRows) => {
                    let btnStatus = false;
                    let canSaveStatus = false;
                    let selectrow = "";
                    if (selectedRowKeys.length === 0) {
                        btnStatus = true;
                        canSaveStatus = true;
                    } else {
                        selectrow = selectedRowKeys[selectedRowKeys.length - 1];
                    }
                    this.setState({ btnStatus: btnStatus, canSaveStatus: canSaveStatus, selectrow: selectrow, selectedRow_right: selectedRows, selectedRowKeys_right: selectedRowKeys });
                },
                getCheckboxProps: record => ({
                    disabled: record.statusID!='1', // Column configuration not to be checked
                }),
                onSelectAll: (selected, selectedRows, changeRows) => {
                    // console.log("selected, selectedRows, changeRows",selected, selectedRows, changeRows)
                    if (selectedRows.length > 0) {
                        this.setState({
                            btnStatus: false,
                            canSaveStatus: false,
                        })
                    } else {
                        this.setState({
                            btnStatus: true,
                            canSaveStatus: true,
                        })
                    }
                    this.setState({ selectedRow_right: selectedRows, });
                }
            };
            return (
                <div style={{ padding: '4px 2px' }} className="bedDom">
                    <div className="evaluationReview-dom">
                        <Form>
                            <Row gutter={60} style={{ margin: '0' }}>
                                <Col span={4} style={paddRightCol}>
                                    <FormItem {...formItemLayoutType} label='医院'>
                                        {getFieldDecorator('getHop', {
                                            initialValue: undefined,
                                            rules: [{ required: false, message: '' }],
                                        })(
                                            <Select
                                                showSearch allowClear optionFilterProp="role"
                                                onChange={this.handleBaseHosp}
                                            >
                                                {hosOp}
                                            </Select>
                                        )}
                                    </FormItem>
                                </Col>
                                <Col span={4} style={paddRightCol}>
                                    <FormItem {...formItemLayoutType} label='科室'>
                                        {getFieldDecorator('locID', {
                                            initialValue: undefined,
                                            rules: [{ required: false, message: '' }],
                                        })(
                                            <Select
                                                showSearch allowClear optionFilterProp="role"
                                                placeholder={"请先选择医院"}
                                            >
                                                {locOp}
                                            </Select>
                                        )}
                                    </FormItem>
                                </Col>
                                <Col span={5} style={paddRightCol}>
                                    <FormItem {...formItemLayoutName} label='医生信息'>
                                        {getFieldDecorator('docName', {
                                            initialValue: undefined,
                                            rules: [{ required: false, message: '' }],
                                        })(
                                            <Input placeholder="支持姓名/拼音模糊检索" allowClear onPressEnter={this.findData}></Input>
                                        )}
                                    </FormItem>
                                </Col>
                                <Col span={5} style={paddRightCol}>
                                    <FormItem {...formItemLayoutName} label='患者信息'>
                                        {getFieldDecorator('patName', {
                                            initialValue: undefined,
                                            rules: [{ required: false, message: '' }],
                                        })(
                                            <Input placeholder="支持姓名/拼音模糊检索" allowClear onPressEnter={this.findData}></Input>
                                        )}
                                    </FormItem>
                                </Col>
                                <Col span={4} style={paddRightCol}>
                                    <FormItem {...formItemLayout} label='审核状态'>
                                        {getFieldDecorator('statusID', {
                                            initialValue: undefined,
                                            rules: [{ required: false, message: '' }],
                                        })(
                                            <Select
                                                showSearch allowClear optionFilterProp="role"
                                            >
                                                {statusOp}
                                            </Select>
                                        )}
                                    </FormItem>
                                </Col>
                                <Col {...searchColConfig} style={{ padding: "5px 0px 0 39px" }}>
                                    <RangeDatePicker isChange={true} label={this.state.userData.language == 'EN' ? 'evaluation Date：' : '评价日期：'} format='YYYY-MM-DD' width={'300px'}
                                        locale={this.state.userData.language}
                                        startDate={this.state.startDate} endDate={this.state.endDate}
                                        startChange={this.startChange.bind(this)} endChange={this.endChange.bind(this)} />
                                </Col>
                                <Col span={2} style={{ paddingLeft: "10px", paddingRight: "0px", width: "5%" }}>
                                    <FormItem  {...formItemLayout}>
                                        {getFieldDecorator('posInp', {
                                            initialValue: undefined,
                                            rules: [{ required: false, message: '' }],
                                        })(
                                            <Button onClick={this.findData} loading={searchLoading} style={{ background: 'rgba(66,185,131,1)', color: '#fff' }}>查询</Button>
                                        )}
                                    </FormItem>
                                </Col>
                                <Col span={2} style={{ paddingLeft: "10px", paddingRight: "0px", width: "5%" }}>
                                    <FormItem  {...formItemLayout}>
                                        {getFieldDecorator('t', {
                                            initialValue: undefined,
                                            rules: [{ required: false, message: '' }],
                                        })(
                                            <Button 
                                            style={{color:(this.state.selectedRow_right&&this.state.selectedRow_right.length==0?"#bfbfbf":"#096dd9")}} 
                                            disabled={this.state.selectedRow_right&&this.state.selectedRow_right.length==0} 
                                            onClick={(e) => this.toggleEditable("2",)} >通过</Button>
                                        )}
                                    </FormItem>
                                </Col>
                                <Col span={2} style={{ paddingLeft: "10px", paddingRight: "0px", width: "5%" }}>
                                    <FormItem  {...formItemLayout}>
                                        {getFieldDecorator('j', {
                                            initialValue: undefined,
                                            rules: [{ required: false, message: '' }],
                                        })(
                                            <Button 
                                            style={{color:(this.state.selectedRow_right&&this.state.selectedRow_right.length==0?"#bfbfbf":"#f5222d")}} 
                                            disabled={this.state.selectedRow_right&&this.state.selectedRow_right.length==0} 
                                            onClick={(e) => this.toggleEditable("3",)} >拒绝</Button>
                                        )}
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row>
                            </Row>
                        </Form>
                    </div>
                    <div>
                        <Table
                            // scroll={{ x: 1160, y: store.getState().tableHeight.y + 156 }}
                            columns={columns}
                            dataSource={this.state.bedData}
                            pagination={false}
                            rowKey={record => record.ID}
                            onRow={this.onClickRow}
                            rowClassName={this.setRowClassNames}
                            bordered
                            style={{ height: store.getState().tableHeight.y + 96 + 'px' }}
                            rowSelection={rowSelection_right}
                        />
                        <CommonPagination size={this.state.size} page={this.state.page} current={this.state.page} total={this.state.total} search={this.state.search}
                            onShowSizeChange={this.onShowSizeChange.bind(this)} complete={true} dataSource={this.state.bedData}
                            onChange={this.onChange.bind(this)} />
                    </div>
                    <ColumnAuthoritysModel
                        clientWidth='800px'
                        compontName='PatientEvaluationInformation'
                        configType="C"
                        onRef={this.onColumnRef}
                        reloadData={this.getMainTableColumns}
                    />
                    {/* <div className='doctor-advice-common-modal'
                        tabIndex={1}
                        onKeyDown={this.handleOnKeydown.bind(this)}
                        style={{ outline: 'none' }}
                    >
                    <ShowCommonTableModal
                        onClickRowPublic={this.onClickRowPublic}
                        setRowClassNamePublic={this.setRowClassNamePublic}
                        isShow={this.state.isShowCommonTableModal}
                        // handleFocus={this.handleFocus.bind(this)}
                        onHide={this.hideModal.bind(this, 'isShowCommonTableModal')}
                        param={param}
                        onRef={this.onRef}
                        search={this.state.search}
                        id="orderItem"
                        compilePage={this.changePageSize.bind(this)}
                    >
                    </ShowCommonTableModal></div> */}
                </div>

            )
        }
    })
export default EvaluationReview    