/*
 * Creator:     ML
 * CreatDate:   2020-02-28
 * descripts：  患者分类配置
 * */
import React from 'react';
import { Form, Row, Col, Input, Select, Button, DatePicker, Popconfirm, Modal, Table, Icon, Pagination, message, Divider, Tooltip,Checkbox } from 'antd';
import moment from 'moment';
import { $http } from '../../containers/config/https';
import store from '../../store';
// import './css/error.less';
import PatientClassificationModal from './component/PatientClassificationModal';
import CommonPagination from 'components/pagination/index';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';


const FormItem = Form.Item;
const Option = Select.Option;
const paddRightCol = {
    paddingRight: "8px"
}
const formItemLayoutType = {
    labelCol: { span: 4 },
    wrapperCol: { span: 20 }
}

const formItemLayout = { // label 和input宽度
    labelCol: { span: 8 },
    wrapperCol: { span: 14 },
}

const PatientClassification = Form.create()(
    class PatientClassification extends React.Component {
        constructor(props) {
            super();
            var userData = JSON.parse(sessionStorage.getItem('userData'))
            this.state = {
                userData: userData,
                total: 0,//表格总数据
                bedData: [],//查询数据
                values: {},//查询条件数据
                searchLoading: false,//查询请求
                rowIds: '',//表格行选中 页面数据
                headerHeight: "",
                page: 1,
                pageSize: 10,
                size: "small",
                search: "",
                checkedStatus:true
            }
        }
        componentDidMount() {
            let self = this
            // 初始化设置table的高度以及表体的高度
            document.querySelector('.ant-table-body').style.height = store.getState().tableHeight.y + 52 + 'px';
            let box = document.querySelector(".department-header");
            if (box) { //此处在加一层判断，更加严密，如果box存在的情况下获取
                this.setState({ headerHeight: box.offsetHeight })
            }
            this.getFindDate()
            this.getMainTableColumns()
        }
        //国际化
        setMessage(name, message) {
            return this.state.localeProvider ? this.state.localeProvider[name][message] : ''
        }
        //动态表头
        onColumnRef = (ref) => {
            this.columnRef = ref;
        }
        // 获取主列表columns
        getMainTableColumns = () => {
            let data = {
                params: [{
                    compontName: "PatientCat",
                    reactCode: ['PatientCat'],
                    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 == "pregnantFlag") {
                                     return (
                                     <span>{record.pregnantFlag=="Y"?"是":"否"}</span>
                                     )
                                   }
                                   return text
                                 }
                            }
                        }) : '';
                        let filterArr = arr.filter(function (item) { return item.display === 'Y' });
                        let seqArr = {
                            align: "center",
                            widthNum: 140,
                            width: "100px",
                            code: "edit",
                            dataIndex: "edit",
                            title: this.state.localeProvider && this.state.localeProvider.PatientCatOperating? this.setMessage('PatientCatOperating', 'descripts') : '操作',
                            display: "Y",
                            render: (value, row, index) => {
                                return (
                                    <span>
                                        <a onClick={(e) => this.toggleEditable(row, "1")}>{this.state.localeProvider && this.state.localeProvider.PatientCatEdit? this.setMessage('PatientCatEdit', 'descripts') : '编辑'}</a>
                                        <Divider type="vertical" />
                                        <Popconfirm title={this.state.localeProvider && this.state.localeProvider.PatientCatDoYou? this.setMessage('PatientCatDoYou', 'descripts') : '是否要删除此行'} onConfirm={() => this.toggleEditable(row, "2")}>
                                            <a style={{ color: "red" }} >{this.state.localeProvider && this.state.localeProvider.PatientCatDel? this.setMessage('PatientCatDel', 'descripts') : '删除'}</a>
                                        </Popconfirm>
                                    </span>
                                )
                            },
                        }
                        filterArr.push(seqArr)
                        this.setState({localeProvider: this.state.userData.language == 'EN' ? res.result.language.EN : res.result.language.CN, 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} 条`;
        }
        //定位到最新添加/当前修改的记录
        getNewData = (id) => {
            //跳至最后一页 并定位到刚添加的这条记录
            if (id) {
                let lastPage = Math.ceil((this.state.total + 1) / this.state.pageSize)
                this.onChange(lastPage, this.state.pageSize)
                this.setState({
                    rowIds: id
                })
            } else {
                this.onChange(this.state.page, this.state.pageSize)
            }

        }
        //获取查询数据
        getFindDate = (values, e) => {
            if (this.state.total == 0) {
                this.setState({
                    searchLoading: true
                })
            }
            let { page, pageSize, } = this.state;
            let data = {}
            data = {
                params: [{
                    number: values && values.number || '',
                    status:this.state.checkedStatus==true?"Y":"N"
                }],
                pagination: [{
                    pageSize: pageSize,
                    currentPage: page,
                }]
            }
            $http.post('urlS', this, {
                code: '03050195',
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0 && res.result) {
                        this.setState({
                            searchLoading: false,
                            search: e
                        })
                        for (var i = 0; i < res.result.data.length; i++) {
                            res.result.data[i].key = i
                        }
                        this.setState({ bedData: res.result.data, total: res.result.TotalCount, }, () => {
                        })
                    } else {
                        this.setState({
                            searchLoading: false
                        })
                    }
                },
                error: function () {
                    this.setState({
                        searchLoading: false
                    })
                }
            })

        }
        //点击查询---
        findData = () => {
            this.props.form.validateFields((err, values) => {
                if (!err) {
                    this.setState({
                        values: values,
                        rowIds: ""
                    })
                    this.onShowSizeChange("1", this.state.pageSize)
                }
            })
        }
        // 调用子组件的连接事件 -- 添加新
        OnChildrefs = (ref) => {
            this.child = ref
        }
        add = () => {
            this.child.showModal()
        }
        //点击查询后 表格行
        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 = (record, num) => {
            if (num == "1") {
                this.child.showModal(record, num)
            } else {
                let datas = {}
                datas = {
                    params: [{
                        updateUserID: JSON.parse(sessionStorage.userData).userID || '',
                        ID: record.ID,
                    }],
                }
                $http.post('urlS', this, {
                    code: '03050197',
                    data: datas,
                    success: function (res) {
                        if (+res.errorCode === 0) {
                            message.success(this.state.localeProvider && this.state.localeProvider.PatientCatDelS? this.setMessage('PatientCatDelS', 'descripts') : '删除成功');
                            this.getFindDate()
                        }
                    }
                })
            }
        }
         //点击是否生效 -- 查询
         changecheckedStatus = (e) => {
            this.setState({
                checkedStatus: e.target.checked,
            }, () => {
                this.findData()
            })
        }

        render() {
            const { getFieldDecorator } = this.props.form;
            const { searchLoading, columns } = this.state;
            return (
                <div style={{ padding: '4px 2px' }} className="bedDom">
                    <div className="department-header">
                        <Form>
                            <Row gutter={60} style={{ margin: '0' }}>
                                <Col span={6} style={paddRightCol}>
                                    <FormItem {...formItemLayoutType} label={this.state.localeProvider && this.state.localeProvider.PatientCatAntibacterialDrugs? this.setMessage('PatientCatAntibacterialDrugs', 'descripts') : '患者'}>
                                        {getFieldDecorator('number', {
                                            initialValue: undefined,
                                            rules: [{ required: false, message: '' }],
                                        })(
                                            <Input placeholder={this.state.localeProvider && this.state.localeProvider.PatientCatIDDesc? this.setMessage('PatientCatIDDesc', 'descripts') : '代码/描述回车检索'} onPressEnter={this.findData}></Input>
                                        )}
                                    </FormItem>
                                </Col>
                                <Col span={3} style={{marginTop:"10px"}}>
                                    <Checkbox checked={this.state.checkedStatus}  onChange={this.changecheckedStatus}>仅显示生效</Checkbox>
                                </Col>
                                {/* <Col span={2} style={paddRightCol}>
                                    <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={{ padding: "0px 0 0 20px" }}>
                                    <FormItem  {...formItemLayout}>
                                        {getFieldDecorator('addNewCard', {
                                            initialValue: undefined,
                                            rules: [{ required: false, message: '' }],
                                        })(
                                            <Button onClick={this.add} style={{ background: 'rgba(66,185,131,1)', color: '#fff' }}>{this.state.localeProvider && this.state.localeProvider.PatientCatAddBasic? this.setMessage('PatientCatAddBasic', 'descripts') : '+患者分类'}</Button>
                                        )}
                                    </FormItem>
                                </Col>
                            </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.key}
                            onRow={this.onClickRow}
                            rowClassName={this.setRowClassNames}
                            bordered
                            style={{ height: store.getState().tableHeight.y + 106 + 'px' }}
                        />
                        <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>
                    <PatientClassificationModal localeProvider={this.state.localeProvider} getNewData={this.getNewData} OnChildrefs={this.OnChildrefs}></PatientClassificationModal>
                    <ColumnAuthoritysModel
                        clientWidth='800px'
                        compontName='PatientCat'
                        configType="C"
                        onRef={this.onColumnRef}
                        reloadData={this.getMainTableColumns}
                    />
                </div>

            )
        }
    })
export default PatientClassification    