/*
 * Creator:     PYH
 * CreatDate:   2020-03-26
 * descripts：检验报告查询
 * */
import React from 'react';
import {Form, Row, Col, Input, Select, Button, Table} from 'antd';
import { $http } from 'containers/config/https';
import store from 'store';
import moment from 'moment';
import CardTypeRead from 'components/cardType/index';
import RangeDatePicker from 'components/rangePicker/index';
import CommonPagination from 'components/pagination/index';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';
import TestResultModal from "./component/TestResultModal.jsx";
import { $loadTemplate } from '../lodop/Common/Print.js';

const FormItem = Form.Item;
const formItemLayoutType = {
    labelCol: { span: 9 },
    wrapperCol: { span: 15 }
}

const formItemLayout = { // label 和input宽度
    labelCol: { span: 8 },
    wrapperCol: { span: 14 },
}
const formItemLayoutInfo = {
    labelCol: { span: 5 },
    wrapperCol: { span: 19 },
}
const searchColConfig = {
    xs: { span: 24 },
    sm: { span: 12 },
    md: { span: 10 },
    lg: { span: 7 }
}
class LisReportLists extends React.Component{

    constructor(){
        super()
        let userData = JSON.parse(sessionStorage.getItem('userData'));
        this.state={
            userData: userData,
            columns: [],
            tableData: [],
            startDate: moment().format('YYYY-MM-DD'),
            endDate: moment().format('YYYY-MM-DD'),
            localeProvider: [],
            values: {},
            size: "small",
            search: "",
            page: 1,
            pageSize: 20,
            total: 0,
        }
    }

    componentDidMount = () => {
        document.querySelector('.reportTable .ant-table-body').style.height = store.getState().tableHeight.y + 30 +'px';
        document.querySelector('.reportTable .ant-table-body').style.maxHeight = store.getState().tableHeight.y + 40+ 'px';
        this.getSpecStatus()
        this.getTableColumns()
    }

    // 获取标本状态
    getSpecStatus() {
         let data = {
            params: [{}],
        }
        $http.post('urlS', this, {
            code: '03050226',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0 && res.result.Data) {
                    this.setState({
                        statusArr: res.result.Data,
                    })
                }
            }
        })
    }

    // 获取table列表columns 
    getTableColumns = () => {
        let data = {
            params: [{
                compontName: "LisReportList",
                reactCode: ['LisReportList'],
                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()}>{this.state.userData.language == 'EN' ? item.descripts : item.title}</div>,
                            display: item.display,
                            key: item.seqNo,
                            render: (text, record) => {
                                if (item.code == "resultStatus") {
                                  return (
                                    <span style={{ cursor: "pointer",display:(record.statusNormal==""?"none":"inline-block") }} onClick={(e) => this.handleOpen(e, record)}><span style={{ color: "#ffffff", background: (record.statusNormal == "Y" ? "#096dd9" :(record.statusNormal=="N"? "#F6A724":"")), padding: "2px", borderRadius: "2px", marginRight: "2px" }}>{record.statusNormal == "Y"&&this.state.userData.language=="EN" ? "nor" :(record.statusNormal == "Y"&&this.state.userData.language=="CN" ? "正":(record.statusNormal == "N"&&this.state.userData.language=="EN"?"abn":"异" ) )}</span><span style={{ color: (record.statusNormal == "Y" ? "#096dd9" : "#F6A724") }}>
                                      {this.state.localeProvider&&this.state.localeProvider.LISReportReportResults?this.setMessage('LISReportReportResults', 'descripts'):"报告结果"}
                                      </span></span>
                                  )
                                }
                                return text
                            }
                        }
                    }) : '';
                    let filterArr = arr.filter(function (item) { return item.display === 'Y' });
                    this.setState({ localeProvider: this.state.userData.language == 'EN' ? res.result.language.EN : res.result.language.CN, columns: filterArr, widthTotal: res.totalWidth })
                }
            }
        })
    }

    // 点击查询---
    handleQuery = () => {
        this.props.form.validateFields((err, values) => {
            if (!err) {
                this.setState({
                    values: values,
                    rowIds: ""
                })
                this.onShowSizeChange("1", this.state.pageSize)
            }
        })
    }
    // 修改page和pageSize 跳转至---
    onChange = (page,pageSize) => {
        this.setState({ page: page, pageSize: pageSize }, () => {
            let { values } = this.state;
            this.searchReport(values);
        })
    }

    // 下拉选择页数
    onShowSizeChange = (page, pageSize) => {
        this.setState({ page: 1, pageSize: pageSize }, () => {
            let { values } = this.state;
            this.searchReport(values, "search");
        })
    }

    // 查询检验报告
    searchReport= (values, e) =>{
        let data = {}
        let { page, pageSize } = this.state;
        data = {
            params: [{
                number: values && values.patInfo || '',
                cardTypeID: this.state.cardType,
                cardNo: this.state.cardNo,
                specNo: values && values.specNo || '',
                specStatusID: values && values.specStatus || '',
                startDate: this.state.startDate,
                endDate: this.state.endDate
            }],
            pagination: [{
                pageSize: pageSize,
                currentPage: page,
            }]
        }
        $http.post('urlS', this, {
            code: '03050227',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    this.setState({
                        search: e,
                        tableData: res.result.data,
                        total: res.result.totalCount,
                    })
                }
            }
        })
    }

    // 获取病人信息
    getPatInfo = (record) => {
        let data = {}
        data = {
            params: [{
            reportID: record.reportID,
            }],
        }
        $http.post('urlS', this, {
            code: '03050136',
            data: data,
            success: function (res) {
            if (+res.errorCode === 0 && res.result) {
                this.childRef.getInfo(res.result)
            }
            }
        })
     }

    // 动态配置表头
    onColumnRef = (ref) => {
        this.columnRef = ref;
    }
    onRef = (ref) => {
        this.childRef = ref
    }
    handleOpen = (e, record) => {
        e.stopPropagation();
         this.setState({
            recordData: record
        }, () => {
            this.getPatInfo(record)
            this.childRef.showModal(this.state.recordData.reportID)
         })
    }
    // 卡类型  
    getValue = (cardType, cardNo) => {
        this.setState({
            cardType,
            cardNo,
        })
    }

    // 开始日期
    startChange(date) {
        this.setState({
           startDate: date,
        })
    }
    // 结束日期
    endChange(date) {
        this.setState({
            endDate: date,
        })
    }
    // 国际化
    setMessage(name, message) {
        return this.state.localeProvider ? this.state.localeProvider[name][message] : ''
    }

    getPrintInfo = (ID) => {
        let data = {}
        data = {
          params: [{
            reportID: ID,
          }],
        }
        $http.post('urlS', this, {
          code: '03050223',
          data: data,
          success: function (res) {
            if (+res.errorCode === 0) {
              if (res.result && res.result.length > 0) {
                res.result.map((item, i) => {
                  $loadTemplate(item.template, item.printStr);
                })
              }
            }
          }
        })
    }
    //打印检验结果
    handlePrint = () => {
        const { selectedRowKeys_rightFry } = this.state
        if (selectedRowKeys_rightFry && selectedRowKeys_rightFry.length > 0) {
            selectedRowKeys_rightFry.map((item, i) => {
            this.getPrintInfo(item)
            })
        }
    }
     render(){
        const { getFieldDecorator } = this.props.form;
        let columns=this.state.columns
        let widthTotal=this.state.widthTotal
        let statusOp=[]
        this.state.statusArr&&this.state.statusArr.map(item=>{
            statusOp.push(<Option key={item.id} role={item.descripts + '^' + item.descriptsSPCode} title={item.descripts} value={String(item.id)}>{item.descripts}</Option>)
        })
        const rowSelection_rightFry = {
            selectedRowKeys: this.state.selectedRowKeys_rightFry,
            onChange: (selectedRowKeys, selectedRows) => {
              let selectrow = "";
              if (selectedRowKeys.length === 0) {
              } else {
                selectrow = selectedRowKeys[selectedRowKeys.length - 1];
              }
              let arr = []
              selectedRows.map((item, i) => {
                arr.push(item.id)
              })
              this.setState({ selectedRowIds_Fry: arr, selectrow: selectrow, selectedRow_right: selectedRows, selectedRowKeys_rightFry: selectedRowKeys }, () => {
              });
            },
            onSelectAll: (selected, selectedRows, changeRows) => {
              let arr = []
              selectedRows.map((item, i) => {
                arr.push(item.id)
              })
              this.setState({ selectedRowIds_Fry: arr, selectedRow_right: selectedRows });
            },
            getCheckboxProps: record => ({
                disabled: record.reportID === '', // Column configuration not to be checked
              }),
        };
        return (
            <div>
                <Form>
                    <Row gutter={60} style={{ margin: '0', paddingLeft: "10px" }}>
                    <CardTypeRead getValue={this.getValue} getQuery={this.handleQuery}></CardTypeRead>
                        <Col span={6} >
                        <FormItem label={this.state.localeProvider && this.state.localeProvider.LisReportListNumber ? this.setMessage('LisReportListNumber', 'descripts') : '人员标识'} {...formItemLayoutInfo}>
                            {getFieldDecorator('patInfo')(
                                <Input
                                    allowClear
                                    placeholder={this.state.localeProvider && this.state.localeProvider.LisReportListNumberMsg ? this.setMessage('LisReportListNumberMsg', 'descripts') : '病人ID/姓名/身份证号码/手机号码'}
                                    onPressEnter={this.handleQuery}
                                    style={{ width: '100%' }}
                                 />
                             )}
                        </FormItem>
                        </Col >
                        <Col span={4} >
                        <FormItem label={this.state.localeProvider && this.state.localeProvider.LisReportListSpecNo ? this.setMessage('LisReportListSpecNo', 'descripts') : '标本号'} {...formItemLayoutInfo}>
                            {getFieldDecorator('specNo')(
                                <Input
                                    allowClear
                                    placeholder={this.state.localeProvider && this.state.localeProvider.LisReportListSpecNoMsg ? this.setMessage('LisReportListSpecNoMsg', 'descripts') : '标本号'}
                                    style={{ width: '100%' }}
                                />
                            )}
                        </FormItem>
                        </Col >
                        <Col span={5} >
                        <FormItem label={this.state.localeProvider && this.state.localeProvider.LisReportListSpecStatus ? this.setMessage('LisReportListSpecStatus', 'descripts') : '标本状态'} {...formItemLayoutType}>
                            {getFieldDecorator('specStatus')(
                                <Select allowClear>
                                    {statusOp}
                                </Select>
                             )}
                        </FormItem>
                        </Col >
                    </Row>
                    <Row gutter={60} style={{ margin: '0', paddingLeft: "10px" }}>
                        <Col {...searchColConfig} style={{ padding: "4px 0" }}>
                            <RangeDatePicker isChange={true} label={this.state.localeProvider && this.state.localeProvider.LisReportListAdmDate ? this.setMessage('LisReportListAdmDate', 'descripts') : "就诊日期: "} format='YYYY-MM-DD' width={419}
                                startDate={this.state.startDate} endDate={this.state.endDate}
                                startChange={this.startChange.bind(this)} endChange={this.endChange.bind(this)} locale={this.state.userData.language} />
                        </Col>
                        <Col span={2} style={{ padding: "0 0 0 30px" }}>
                            <FormItem  {...formItemLayout}>
                                <Button onClick={this.handleQuery} style={{ background: 'rgba(66,185,131,1)', color: '#fff' }}>{this.state.localeProvider && this.state.localeProvider.LisReportListsSearch ? this.setMessage('LisReportListSearch', 'descripts') : "查询"}</Button>
                            </FormItem>
                        </Col>
                        <Col span={2} >
                            <FormItem  {...formItemLayout}>
                                {getFieldDecorator('print', {
                                initialValue: undefined,
                                rules: [{ required: false, message: '' }],
                                })(
                                <Button onClick={this.handlePrint} disabled={this.state.selectedRowKeys_rightFry && this.state.selectedRowKeys_rightFry.length == 0} style={{ background: 'rgba(66,185,131,1)', color: '#fff' }}>{this.state.localeProvider && this.state.localeProvider.LisReportListPrint ? this.setMessage('LisReportListPrint', 'descripts') : "打印"}</Button>
                                )}
                            </FormItem>
                        </Col>
                    </Row>
                    <div className='reportTable'>
                        <Table 
                            scroll={{ x: (columns && columns.length > 0 ? widthTotal : 4000), y: store.getState().tableHeight.y - 90 }}
                            columns={columns}
                            dataSource={this.state.tableData}
                            pagination={false}
                            onRow={this.onClickRow}
                            rowSelection={rowSelection_rightFry}
                            rowKey={record => record.reportID}
                            bordered
                            style={{ height: store.getState().tableHeight.y + 80 + 'px', overflow: "auto" }}
                        />
                        <CommonPagination size={this.state.size} page={this.state.page}  pageSize={this.state.pageSize} current={this.state.page} total={this.state.total} search={this.state.search}
                            onShowSizeChange={this.onShowSizeChange.bind(this)} complete={true} dataSource={this.state.tableData}
                            onChange={this.onChange.bind(this)} />
                        <ColumnAuthoritysModel
                            clientWidth='800px'
                            compontName='LisReportList'
                            configType="C"
                            onRef={this.onColumnRef}
                            reloadData={this.loadTableColumns}
                        />
                        <TestResultModal onRef={this.onRef} getReaultPop={this.getReaultPop}></TestResultModal>
                    </div>
                    
                </Form>
            </div>


        )


     }
}

const LisReportList = Form.create()(LisReportLists);
export default LisReportList;

