/**
 * 生命体征配置列表
 */

import React from 'react';
import {
    Input, Row, Col, Button,Table,Spin, Divider, Popconfirm, message, Icon, Select
} from 'antd';
import { $http } from '../../../containers/config/https';
import PubilcTablePagination from '../../common/PubilcTablePagination.jsx'; // 公共table组件
import AddConfig from './AddConfig.jsx';
import store from 'store';
import CommonPagination from 'components/pagination/index';
import ColumnAuthoritysModel from '../../columnAuthority/ColumnAuthoritysModel';
import './CSS/VitalSigns.less'

// 组件const
const { Option } = Select;
let user;
class ConfigPage extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            hospID: "",
            code: "",
            descripts: "",
            configInfo: {},
            tableData: [],
            hospital: [],
            // 表格数据总条数
            total: 0,
            page: 1,
            pageSize: 10,
            flag: "",
            title: "",
            status: "Y",
            column:[],
            ENObj: {},
            CNObj: {},
            tableWidth: "",
        }
        this.columns = [
            {
                key: 0,
                title: '序号',
                dataIndex: 'seqNo',
                align: "center",
                width: '5%'
            },
            {
                key: 1,
                title: '代码',
                dataIndex: 'code',
                align: "center",
                width: '6%'
            },
            {
                key: 2,
                title: '描述',
                dataIndex: 'descripts',
                align: "center",
                width: '8%'
            },
            {
                key: 3,
                title: '数据类型',
                dataIndex: 'type',
                align: "center",
                width: '5%',
            },
            {
                key: 4,
                title: '正常低值',
                dataIndex: 'normalRangeFrom',
                align: "center",
                width: '8%',
            },
            {
                key: 5,
                title: '正常高值',
                dataIndex: 'normalRangeTo',
                align: "center",
                width: '8%',
            },
            {
                key: 6,
                title: '错误低值',
                dataIndex: 'errorRangeFrom',
                align: "center",
                width: '8%',
            },
            {
                key: 7,
                title: '错误高值',
                dataIndex: 'errorRangeTo',
                align: "center",
                width: '5%',
            },
            {
                key: 8,
                title: '婴儿标记',
                dataIndex: 'babyFlag',
                align: "center",
                width: '5%',
            },
            {
                key: 9,
                title: '录入次数',
                dataIndex: 'times',
                align: "center",
                width: '5%',
            },
            {
                key: 10,
                title: '测量单位',
                dataIndex: 'unit',
                align: "center",
                width: '8%',
            },
            {
                key: 11,
                title: '划线颜色',
                dataIndex: 'color',
                align: "center",
                width: '8%',
            },
            {
                key: 12,
                title: '图案',
                dataIndex: 'graph',
                align: "center",
                width: '8%',
            },
            {
                key: 13,
                title: '本院',
                dataIndex: 'currentFlag',
                align: "center",
                width: '3%',
            },
            {
                title: '操作',
                key: 14,
                align: "center",
                width: 130,
                render: (text, record) => (
                    <span>
                        <Icon type="edit" style={{ color: '#108EE9' }}></Icon>
                        <span className='span' onClick={() => this.handleCompile(record)}>编辑</span>
                        {/* 分割线 */}
                        {((record.status !== "N") && (record.hospID != "")) ? <Divider type="vertical" />:''}
                        {((record.status !== "N") && (record.hospID != "")) ? <Icon type="delete" style={{ color: 'rgba(240,65,52,1)' }}></Icon> : ""}
                        {
                            record.hospID === "" ? '' :
                                (
                                    record.status !== "N" ?
                                        <Popconfirm title=" 你确定要停用吗?" onConfirm={() => this.handleStop(record, "N")} >
                                            <span className='span' style={{ color: 'rgba(240,65,52,1)' }}>停用</span>
                                        </Popconfirm>
                                        : <Popconfirm title=" 你确定要启用吗?" onConfirm={() => this.handleStop(record, "Y")} >
                                            <span className='span' style={{ color: 'rgba(240,65,52,1)' }}>启用</span>
                                        </Popconfirm>
                                )
                        }
                    </span>
                ),
            }
        ]
        user = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
    }
    componentDidMount() {
        // 获取医院列表
        this.getHospital();
        // 初始化列表数据
        this.getDetailTableColumns()
    }
    componentWillUnmount() {
        // 组件销毁前将静止让setState修改state的状态
        this.setState = (state, callback) => { return; }
    }

    // 获取明系列表头数据
    getDetailTableColumns = () => {
        let data = {
            params: [{
                reactCode: ['configPage'],
                compontName: 'configPage',
                type: 'C',
            }]
        }
        $http.post('urlS', this, {
            code: '01040073',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    var columns = []
                    columns = res.result.C
                    if (user.language == 'EN') {
						for (let i = 0; i < columns.length; i++) {
							columns[i].title = columns[i].enDescripts
						}
                    }
                    for (var ci = 0; ci < columns.length; ci++) {
                        if (columns[ci].dataIndex == 'operat') {
                            var diagColumns = [];
                            diagColumns.push({
                                title: user.language != 'EN' ? user.language != 'EN' ? columns[ci].title : columns[ci].enDescripts : columns[ci].enDescripts,
                                dataIndex: columns[ci].dataIndex,
                                width: columns[ci].width,
                                align: columns[ci].align,
                                render: (text, data, index) => {
                                  return  <span>
                                        <Icon type="edit" style={{ color: '#108EE9' }}></Icon>
                                        <span className='span' onClick={() => this.handleCompile(data)}>编辑</span>
                                        {/* 分割线 */}
                                        {((data.status !== "N") && (data.hospID != "")) ? <Divider type="vertical" />:''}
                                        {((data.status !== "N") && (data.hospID != "")) ? <Icon type="delete" style={{ color: 'rgba(240,65,52,1)' }}></Icon> : ""}
                                        {
                                            data.hospID === "" ? '' :
                                                (
                                                    data.status !== "N" ?
                                                        <Popconfirm title=" 你确定要停用吗?" onConfirm={() => this.handleStop(data, "N")} >
                                                            <span className='span' style={{ color: 'rgba(240,65,52,1)' }}>停用</span>
                                                        </Popconfirm>
                                                        : <Popconfirm title=" 你确定要启用吗?" onConfirm={() => this.handleStop(data, "Y")} >
                                                            <span className='span' style={{ color: 'rgba(240,65,52,1)' }}>启用</span>
                                                        </Popconfirm>
                                                )
                                        }
                                    </span>
                                }
                            })
                            columns[ci] = diagColumns[0]
                        }
                    }
                    this.setState({
                        ENObj: res.result.language.EN,
                        CNObj: res.result.language.CN,
                        column: columns,
                        tableWidth: res.totalWidth,
                    }, () => {
                        this.handleQuery(user.hospID)
                    })
                }
            }
        })
    }


    handleQuery = (hospID) => {
        // 数据加载成功关闭loading
        if (hospID.type !== undefined) {
            hospID = this.state.hospID;
        }
        let { page, pageSize } = this.state;
        let data = {
            params: [{
                hospID: hospID,    //医院ID
                code: this.state.code,
                descripts: this.state.descripts,
                status: this.state.status,
                addPatCol: "0",
            }],
            pagination: [{
                pageSize: pageSize,
                currentPage: page,
            }]
        };
        $http.post('urlADS', this, {
            code: "04040003",
            data: data,
            success: function (res) {
                let errorCode = res.errorCode;
                if (errorCode === '0') {
                    this.setState({ tableData: res.result.config, total: res.result.TotalCount, hospID: hospID })
                }
            }
        });
        //this.commonChild.handleLoading()
    }

    // 停用配置
    handleStop = (record, status) => {
        let data = {
            "params": [{
                userID: user.userID,    //用户ID
                hospID: record.hospID,    //医院ID
                code: record.code,
                descripts: record.descripts,
                saveType: "H",
                status: status,   //状态
            }]
        };
        $http.post('urlADS', this, {
            code: "04040002",
            data: data,
            success: function (res) {
                let errorCode = res.errorCode;
                if (errorCode === '0') {
                    if (status === "N") message.success("已停用!");
                    if (status === "Y") message.success("已启用!");
                    this.handleQuery(this.state.hospID);
                }
            }
        });
    }
    // 提供修改page和pageSize的回调函数
    compilePage(page, pageSize) {
        // 修改page，或者pageSize
        this.setState({ page: page, pageSize: pageSize }, () => {
            // 重新调用查询方法
            this.handleQuery(this.state.hospID);
        })
    }
    // 查询条件 --- 项目代码
    onChangeCode = (e) => {
        this.setState({ code: e.target.value })
    }
    // 查询条件 --- 医院
    onChangehosp = (value) => {
        this.handleQuery(value);
    }

    // 查询条件 --- 项目描述
    onChangeDescripts = (e) => {
        this.setState({ descripts: e.target.value })
    }
    // 重置信息
    resetConfigInfo() {
        this.setState({ configInfo: {} })
    }
    // 编辑信息
    handleCompile = (record) => {
        // 打开抽屉
        this.child.showDrawer();
        // 初始化数据
        this.setState({ configInfo: record, flag: 'edit', title: '编辑' })
    }
    // 删除信息
    handleDelete = (record) => {
        let data = {
            "params": [{
                userID: user.userID,    //医院ID
                id: record.key,
            }]
        };
        $http.post('urlADS', this, {
            code: "04040004",
            data: data,
            success: function (res) {
                let errorCode = res.errorCode;
                if (errorCode === '0') {
                    message.success("删除成功!");
                    this.handleQuery(this.state.hospID);
                }
            }
        });

    }
    //新增配置
    handleAdd = () => {
        // 打开抽屉
        this.child.showDrawer();
        // 初始化数据
        this.setState({ flag: 'add', title: '新增' })
    }
    componentWillUnmount() {
        // 组件销毁前将静止让setState修改state的状态
        this.setState = (state, callback) => { return; }
    }
    // 调用公共组件的连接事件
    onRef = (ref) => {
        this.child = ref
    }
    handleOnRef = (ref) => {
        this.commonChild = ref
    }
    // 状态改变
    onStatusChange = (value) => {
        this.setState({
            status: value
        }, () => {
            this.handleQuery(this.state.hospID);
        })
    }

    


    ///获取医院列表 (本院及下级医院)
    getHospital = () => {
        let data = {
            params: [{
                hospID: user.hospID,
                logonGroupID: user.groupID,
                logonHospID: user.hospID,
            }]
        }

        $http.post('urlDeault', this, {
            code: "01040001",
            data: data,
            success: (res) => {
                if (+res.errorCode === 0) {
                    this.setState({ hospital: res.depDoctor })
                } else {
                    message.error('保存失败' + res.errorMessage);
                }
            }
        })
    }

    onChange(e, pageSize) {
        this.setState({ page: e, pageSize: pageSize }, () => {
          this.handleQuery(user.hospID);
        });
      }
    
    //分页切换
    changePageSize(page, pageSize) {
        this.setState({ pageSize: pageSize, page: page }, () => {
        this.handleQuery(user.hospID);
        });
    }

    onColumnRef = (ref) => {
        this.columnRef = ref;
    }

    render() {
        // 组件所需参数
        const param = {
            // 表头配置
            columns: this.columns,
            // 表格数据
            data: this.state.tableData,
            // 数据总条数
            total: this.state.total,
            // 数据页数
            page: this.state.page,
            // 表格的宽度
            x: 900
        }
        const hospital = [];
        this.state.hospital.map((item) => {
            hospital.push(
                <Option key={item.id} value={item.id + ""} title={item.descspell} >{item.descripts}</Option>
            )
        })
        return (
            <div className="configPage" style={{ width: '100%', height: '100%',overflow: 'hidden' }}>
                <ColumnAuthoritysModel
                        clientWidth='800px'
                        compontName="configPage"
                        configType="C"
                        onRef={this.onColumnRef}
                        reloadData={this.getDetailTableColumns}
                />
                <div className="table-operations">
                    <Row style={{ minHeight: '80px', padding: '0 24px 24px 24px' }}>
                        <Col span={20}>

                            医院：<Select style={{ width: '180px' }} defaultValue={user.hospID + ""} onChange={this.onChangehosp}>
                                {hospital}
                            </Select>
                            项目代码：<Input allowClear={true} onPressEnter={this.handleQuery} value={this.state.code} onChange={this.onChangeCode} placeholder="项目代码(Enter)" style={{ width: '160px', margin: '23px 15px 0 0' }} />
                            项目描述：<Input allowClear={true} onPressEnter={this.handleQuery} value={this.state.descripts} onChange={this.onChangeDescripts} placeholder="项目描述(Enter)" style={{ width: '160px', margin: '23px 15px 0 0' }} />
                            状态:<Select placeholder="状态" value={this.state.status} style={{ width: '140px', margin: '23px 15px 0 0' }} onChange={this.onStatusChange}>
                                <Option key="Y">使用中</Option>
                                <Option key="N">已停用</Option>
                            </Select>
                            <Button onClick={this.handleQuery} style={{ margin: '23px 15px 0 0', background: 'rgba(255,255,255,1)' }}>查询</Button>
                        </Col>
                        <Col span={4} style={{ textAlign: 'right' }}>
                            <Button icon="plus" onClick={this.handleAdd} style={{ background: 'rgba(247,128,93,1)', color: '#fff', margin: '23px 15px 0 0' }}>新增项目</Button>
                        </Col>
                    </Row>
                </div>
                <div style={{ widht: '100%', height: '10px', background: '#f0f2f5' }}></div>
                 {/*<div style={{ padding: 24 }}>
                    handelThis将夫组件的属性与方法给子组件访问 
                    <PubilcTablePagination param={param} handelThis={this} onRef={this.handleOnRef} />
                </div>*/}
                <div className="operationLeave" style={{ float:"left", width: '100%',height:"100%"}}>
                    <div style={{ width: '100%', height: 'calc(100% - 127px)', overflow: 'hidden' }} >
                        <Table
                            style={{ width: '100%', "padding": "5px",height:"100%",border:'7px soild #eeeeee' }}
                            dataSource={this.state.tableData}
                            columns={this.state.column}
                            //onRow={this.onRow}
                            //rowClassName={this.setRowClassName}
                            onHeaderRow={column => {
                                return {
                                    onDoubleClick: () => {
                                        this.columnRef.onOpenModel();
                                    },
                                };
                            }}
                            bordered={true}
                            pagination={false}
                            scroll={{ y: store.getState().tableHeight.y + 'px', x: this.state.tableWidth }}
                        />
                    </div>
                    <div style={{ width: '100%', height: '45px', overflow: 'hidden' }}>
                        <CommonPagination
                            size='small'
                            current={this.state.page}
                            total={this.state.total}
                            search='search'
                            onShowSizeChange={this.changePageSize.bind(this)}
                            complete={true}
                            dataSource={this.state.tableData}
                            onChange={this.onChange.bind(this)}
                            scroll={{ y: store.getState().tableHeight.y + 'px' }}
                        />
                    </div>
                </div>
                <AddConfig onRef={this.onRef} handelThis={this} configInfo={this.state.configInfo} hospID={this.state.hospID} flag={this.state.flag} title={this.state.title} />
            </div>

        );
    }
}

export default ConfigPage;
