//会诊审核
import React from 'react';
import { Card, Row, Col, Form, DatePicker, Select, Input, Button, Tooltip, message, Pagination, Icon, Divider, Popconfirm } from 'antd';
import { $http } from 'containers/config/https';
import ConsultationAuditModel from './ConsultationAuditModel.jsx';
import PubilcTablePagination from '../../common/PubilcTablePagination.jsx'; // 公共table组件
import Moment from 'moment';
import { $loadTemplate } from '../../lodop/Common/Print.js';
import RangeDatePicker from 'components/rangePicker/index';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';
import { Util, dayFormat } from 'tools/index';
import store from 'store';
import './index.less';

let user ;

const { Option } = Select;
const FormItem = Form.Item;
const formItemLayout = {    // label 和input宽度
    labelCol: { span: 7 },
    wrapperCol: { span: 17 },
};
const ConsultationAudit = Form.create()(
    class extends React.Component {
        constructor(props) {
            user = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
            super(props);
            this.state = {
                admDateFrom: undefined,
                admDateTo: undefined,
                hospID: user.hospID,
                WaListData: [],
                pageSize: 10,
                page: 1,
                pageSize2: 10,
                sortColumn: 'applyDate',
                conTypeData: [],        //会诊类型下拉数据
                locData: [],            //会诊科室下拉数据
                tableData: [],
                total: 0,
                startDate: '',
                stopDate: '',
                auditStatus: '',
                tableType: 'C',
                starNoVisible:false,    //提示信息
            }            
        }
        componentDidMount() {
            
            this.getSelectData();
            this.getLocData()
            this.loadColumn();
        }

        //查询列头数据
        loadColumn = () => {
            let data = {
                params: [{
                    compontName: "ConsultationAudit",
                    type: this.state.tableType,
                }]
            }
            $http.post('urlDeault', this, {
                code: "01040073",
                data: data,
                success: (res) => {
                    if (+res.errorCode === 0) {
                        let resData = res.result && res.result[this.state.tableType].length > 0 ? JSON.parse(JSON.stringify(res.result[this.state.tableType])).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.code
                            }
                        }) : '';
                        for (let index = 0; index < resData.length; index++) {
                            // widthNumber += parseInt(res.result[index].width);
                            let columnCode = resData[index].code;
                            if ((columnCode == 'patAge') || (columnCode == 'admDiag') || (columnCode == 'conAims') || (columnCode == 'conItemIdea')) {
                                resData[index].onCell = () => {
                                    return {
                                        style: {
                                            maxWidth: 150,
                                            overflow: 'hidden',
                                            whiteSpace: 'nowrap',
                                            textOverflow: 'ellipsis',
                                            cursor: 'pointer'
                                        }
                                    }
                                }
                                resData[index].render = (text) => <Tooltip placement="topLeft" title={text}>{text}</Tooltip>
                            }

                        }

                        const optionObj = {
                            title: '操作',
                            key: resData.length,
                            fixed: 'right',
                            align: 'center',
                            width: 200,
                            render: (text, record) => {
                                let disableFlag = record.conAuditStatus == "Y" ? true : false
                                return (
                                    <span>
                                        {record.conAuditStatus == 'Y' ? 
                                    <span><Icon type="edit" style={{ color: '#108EE9' }}></Icon>
                                        <span className='span' onClick={() => this.cancelAudit(record)}>撤销审核</span>
                                        <Divider type="vertical" />
                                    </span> : 
                                        <span><Icon type="edit" style={{ color: '#108EE9' }}></Icon>
                                            <span className='span' onClick={() => this.handleAudit(record)}>处理</span>
                                            <Divider type="vertical" />
                                        </span>}
                                        <Icon type="printer" style={{ color: '#108EE9' }}></Icon>
                                        <span className='span' onClick={() => this.handlePrint(record)}>打印</span>
                                    </span>
                                )
                            }
                        }
                        resData.push(optionObj);

                        this.setState({
                            columns: resData,
                            tableWidth: (parseInt(res.totalWidth.split('px')[0]) + optionObj.width) + "px"
                        })
                    }
                }
            })
        }

        // 获取下拉框数据
        getSelectData = () => {
            let data = {
                "params": [{
                    hospID: user && user.hospID ? user.hospID : '',
                    locID: user.locID,
                    groupID: user.groupID,
                    userID: user.userID,
                    type: 'auditList'
                }]
            };
            $http.post('urlDeault', this, {
                code: "04090011",
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        this.setState({
                            conTypeData: res.result.conType,
                            admDateFrom: res.result.AuditListStartDate,
                            admDateTo: res.result.AuditListStopDate
                        }, () => {
                            this.handleQuery()
                        })
                    }
                },
                error: function (error) {
                    message.error('失败：' + error);
                }
            });
        }

        // 获取科室信息
        getLocData = () => {
            let data = {
                "params": [{
                    hospID: this.state.hospID,          // 会诊医院id
                    type: "O^I^OI^E^W"
                }]
            };
            $http.post('urlDeault', this, {
                code: "04020008",
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        this.setState({
                            locData: res.result.Data
                        })
                    }
                },
                error: function (error) {
                    message.error('失败：' + error);
                }
            });
        }
        //隐藏提示信息
        visibleTip=()=>{
            this.setState({
            starNoVisible:false,
            locNoVisible:false
            })
        }

        handleQuery = () => {
            const formData = this.props.form.getFieldsValue();
            if((this.state.admDateFrom&&this.state.admDateFrom)&&(this.state.admDateTo&&this.state.admDateTo)){
                if(Moment(this.state.admDateFrom).format('YYYYMMDD') > Moment(this.state.admDateTo).format('YYYYMMDD')){
                  this.setState({
                    starNoVisible: true,
                    startNoMessage: "开始日期大于结束日期",
                  })
                  return
                }
              }
            let data = {
                params: [{
                    hospID: user.hospID,
                    startDate: this.state.admDateFrom? Moment(this.state.admDateFrom).utcOffset(480).format('YYYY-MM-DD') : '',
                    stopDate: this.state.admDateTo ? Moment(this.state.admDateTo).utcOffset(480).format('YYYY-MM-DD') : '',
                    // auditStatus: this.state.auditStatus != "" ? this.state.auditStatus : formData.auditStatus,
                    auditStatus: formData.auditStatus,
                    locID: formData.locID,
                    conTypeID: formData.conTypeID,
                    patNo: formData.patNo,
                }],
                pagination: [{
                    pageSize: this.state.pageSize,
                    currentPage: this.state.page,
                    sortColumn: this.state.sortColumn,
                    sortOrder: 'desc'
                }]
            };
            $http.post('urlS', this, {
                code: '04090012',
                data: data,
                success: (res) => {
                    // console.dir(res);
                    if (res.errorCode === "0") {
                        for (let index = 0; index < res.result.Data.length; index++) {
                            res.result.Data[index].key = index + 1;
                        }
                        this.setState({
                            total: res.result.TotalCount,
                            tableData: res.result.Data,
                        });
                    } else {
                        this.setState({
                            total: 0,
                            tableData: []
                        });
                    }
                }
            });
            this.commonChild.handleLoading();
        }

        patNotEnter = (e) => {
            if (e.keyCode = '13') {
                this.setState({
                    patNo: ''
                }, () => {
                    this.handleQuery();
                })
            }
        }

        setConsultType = (id, opt) => {
            this.setState({
                conTypeID: id
            }, () => {
                this.handleQuery();
            })

        }

        setConsultLoc = (id, opt) => {
            this.setState({
                locID: id
            }, () => {
                this.handleQuery();
            })
        }

        auditStatusSelect = (value) => {
            this.setState({
                auditStatus: value
            }, () => {
                this.handleQuery();
            })
        }
        // 审核
        handleAudit(record) {
            this.setState({
                visible: true,
                consultID: record.consultID
            }, () => {
                this.child.cleanData();
            });
        }  
        // 撤销审核
        cancelAudit(record) {
            let data = {
                "params": [{
                    consultID: record.consultID,
                    hospID: user.hospID,
                    code: 'SE',
                    updateUserID: user.userID,
                    conAuditDate: '',
                    conAuditTime: '',
                    conAuditUserID: ''
                }]
            };
            $http.post('urlADS', this, {
                code: "04090015",
                data: data,
                success: function (res) {
                    if (+res.errorCode == '0') {
                        message.success(res.errorMessage);
                        this.handleQuery();
                    }
                },
                error: function (error) {
                    message.error('失败：' + error);
                }
            });
        }
        handlePrint(record) {
            let data = {
                params: [{
                     conItemID: record.consultID
                }]
            }
            $http.post('urlS', this, {
                code: "04090023",
                data: data,
                success: function (res) {
                  //  console.log(res)
                    if (res.errorCode === '0') {
                        const data = res.result
                        //加载模板
                        $loadTemplate("Contsultation", data);
                    }
                }
            })
         }

         


    // 提供修改page和pageSize的回调函数
    compilePage(page, pageSize) {
        // 修改page，或者pageSize
        this.setState({ page: page, pageSize: pageSize }, () => {
            // 重新调用查询方法
            let { status, name, quarters } = this.state;
            this.handleQuery(name, status, quarters);
        })
    }

        // 调用公共组件的连接事件
        onRef = (ref) => {
            this.child = ref
        }
        handleOnRef = (ref) => {
            this.commonChild = ref
        }

        // 页码改变的回调，参数是改变后的页码及每页条数 入库单
        onChange = (page, pageSize) => {
            this.setState({ page: page, pageSize: pageSize }, () => {
                // 重新调用查询方法
                 this.getWarehouseList();
            });
        };

        onShowSizeChange = (current, size) => {
            this.setState({ page: current, pageSize: size }, () => {
                // 重新调用查询方法
                 this.onChange(current,size);
            })
        };
        // 显示分页总条数
        showTotal(total) {
            return `共 ${total} 条`;
        }

        startChange(date) {
            this.setState({
                admDateFrom: date,
            })
        }
    
        endChange(date) {
            this.setState({
                admDateTo: date,
            })
        }
        onColumnRef = (ref) => {
            this.columnRef = ref;
        }
        // 获取主列表columns
        getMainTableColumns = () => {
            let data = {
                params: [{
                    compontName: 'ConsultationAudit', // 接口服务
                    type: 'C',
                }]
            }
        }
        // 验证进价 validator: this.validatorRP2
        // validatorRP2 = (rule, value, callback) => {

        //     if (!value) {
        //         // 当value值不存在的话
        //         callback('结束日期不能为空');
        //     } else {
        //         if (!/^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$/g.test(value)) {
        //             callback('必须为大于0的数字');
        //         }
        //     }
        //     callback();
        // };
        render() {
            var date = new Date()
            // 组件所需参数
            const param = {
                // 表头配置
                columns: this.state.columns,
                // 表格数据
                data: this.state.tableData,
                // 数据总条数
                total: this.state.total,
                // 数据页数
                page: this.state.page,
                // 表格的宽度
                x: this.state.tableWidth
            }
            const mesIcon = <Icon type="exclamation-circle" />
            const { getFieldDecorator } = this.props.form;
            var nowDate=new Date()
            return (
                <div className="WarehouseEntryCheck1" style={{ overflow: 'hidden' }}>
                    <div>
                        <Row>
                            <Card
                                size="small"
                                title="会诊审核"
                                headStyle={{ background: 'rgb(66, 185, 131)' }}
                            >
                                <Col span={18}>
                                    <Form onSubmit={this.handleQuery}>
                                        <Row >
                                            <Col span={8} className="starDataDom" style={{paddingRight:"0"}}> 
                                                <Tooltip getPopupContainer={() => document.querySelector('.starDataDom')} overlayStyle={{ zIndex: 999, }} overlayClassName="toolTipDom starData" title={<div className="titleIcon">{mesIcon}<span >{this.state.startNoMessage}</span></div>} visible={this.state.starNoVisible}>
                                                    <FormItem {...formItemLayout} label="会诊时间">
                                                        <RangeDatePicker  format='YYYY-MM-DD' style={{ width: "100%", textAlign: "center" }}
                                                                    startDate={this.state.admDateFrom} endDate={this.state.admDateTo}
                                                                    startChange={this.startChange.bind(this)} endChange={this.endChange.bind(this)} 
                                                                    locale={user.language}
                                                        /> 
                                                    </FormItem>
                                                </Tooltip>
                                            </Col>
                                            <Col span={8}>
                                                <FormItem {...formItemLayout} label="请会诊科室">
                                                    {getFieldDecorator('locID', {
                                                        initialValue: undefined,
                                                        rules: [{ required: false, message: '会诊科室为空' }]
                                                    })(
                                                        <Select
                                                            allowClear
                                                            showSearch
                                                            optionFilterProp='role'
                                                            onChange={(id, opt) => { this.setConsultLoc(id, opt) }}
                                                        >
                                                            {this.state.locData.map(data => (<Select.Option role={data.code + '^' + data.descripts + '^' + data.descriptsSPCode} key={data.id} code={data.code}>{data.descripts}</Select.Option>
                                                            ))}
                                                        </Select>
                                                    )}
                                                </FormItem>
                                            </Col>
                                            <Col span={8}>
                                                <FormItem {...formItemLayout} label="患者ID">
                                                    {getFieldDecorator('patNo', {
                                                        initialValue: undefined,
                                                        rules: [{ required: false, message: '患者ID' }]
                                                    })(
                                                        <Input onPressEnter={this.patNotEnter} />
                                                    )}
                                                </FormItem>
                                            </Col>
                                        </Row>
                                        <Row>
                                            <Col span={8}>
                                                <FormItem {...formItemLayout} label="会诊类型">
                                                    {getFieldDecorator('conTypeID', {
                                                        initialValue: undefined,
                                                        rules: [{ required: false }]
                                                    })(
                                                        <Select
                                                            allowClear
                                                            showSearch
                                                            optionFilterProp='role'
                                                            onChange={(id, opt) => { this.setConsultType(id, opt) }}
                                                        >
                                                            {this.state.conTypeData.map(data => (<Select.Option role={data.code + '^' + data.descripts + '^' + data.descriptsSPCode} key={data.id} code={data.code}>{data.descripts}</Select.Option>
                                                            ))}
                                                        </Select>
                                                    )}
                                                </FormItem>
                                            </Col>
                                            <Col span={8}>
                                                <FormItem {...formItemLayout} label="审核状态">
                                                    {getFieldDecorator('auditStatus', {
                                                        initialValue: 'N',
                                                        rules: [{ required: false }]
                                                    })(
                                                        <Select allowClear
                                                            onChange={this.auditStatusSelect}
                                                        >
                                                            <Option key="N" value="N">待审</Option>
                                                            <Option key="Y" value="Y">已审</Option>
                                                        </Select>
                                                    )}
                                                </FormItem>
                                            </Col>
                                        </Row>
                                    </Form>
                                </Col>
                                <Col span={6} style={{ marginTop: '4px' }}>
                                    <Row style={{ marginBottom: '18px' }} className="button">
                                        &nbsp;&nbsp;&nbsp;&nbsp;<Button style={{ marginRight: '30px' }} onClick={this.handleQuery}>查询</Button>
                                    </Row>
                                </Col>

                            </Card>
                        </Row>
                    </div>
                    <div>
                        {/* handelThis将夫组件的属性与方法给子组件访问 */}
                        <PubilcTablePagination param={param} handelThis={this} onRef={this.handleOnRef} />
                    </div>
                    <ConsultationAuditModel
                        visible={this.state.visible}
                        handleOk={() => this.setState({ visible: false })}
                        handthis={this}
                        onRef={this.onRef}
                        consultID={this.state.consultID}
                    />
                    <ColumnAuthoritysModel
                        clientWidth='800px'
                        compontName='ConsultationAudit'
                        configType="C"
                        onRef={this.onColumnRef}
                        reloadData={this.getMainTableColumns}
                    />
                </div>
            )
        }

    }
);
export default ConsultationAudit;