//标本容器
import React from 'react';
import { Select, Input, Row, Col, Button, Spin, Divider, Popconfirm, message, Icon, Form, Modal, Card, Switch, DatePicker, Popover, List } from 'antd';
import { $http } from '../../../containers/config/https';
import '../../../assets/css/system.css'
import PubilcTablePagination from '../../common/PubilcTablePagination.jsx';
import store from './../../../store/index';
import moment from 'moment';

const { Option } = Select;
const FormItem = Form.Item;

const formItemLayout = {
    labelCol: { span: 10 },
    wrapperCol: { span: 14 },
}

const formItemLayoutNumber = {
    labelCol: { span: 9 },
    wrapperCol: { span: 14 },
}

const HospitalMaintenance = Form.create()(
    class HospitalMaintenance extends React.Component {
        constructor(props) {
            super(props);
            this.state = {
                data: [],
                columns: [],
                total: 0,
                page: 1,
                pageSize: 10,
                baseParms: [],
                values: {},
                ID: "",
                higherHospID: "",
                cityArr: [],
                areasArr: [],
                VillagesArr: [],
                hamletsArr: [],
                heightTable: "",
            }
        }
        componentDidMount() {
            // 初始化设置table的高度以及表体的高度 内容高度 height 
            if (document.querySelector('.ant-table-body')) {
                document.querySelector('.ant-table-body').style.height = store.getState().tableHeight.y - 40 + 'px'
            }
            this.getHealthBureauArr();
            this.getBaseParams();
        }
        //获取对应的医院基础信息数据
        getBaseParams = () => {
            let data = {
                params: [{

                }],
            }
            $http.post("urlS", this, {
                code: "05100224",
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        this.setState({
                            baseParms: res.result
                        })
                    } else {
                        message.error('失败：' + res.errorMessage);
                    }
                },
                error: function (error) {
                    message.error('失败：' + error);
                }
            })
        }
        
        getHealthBureauArr = () => {
            let data = {
                params: [{
                }],
            }
            $http.post("urlS", this, {
                code: "05100220",
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        this.setState({
                            healthBureauArr: res.result.Data
                        })
                    } else {
                        message.error('失败：' + res.errorMessage);
                    }
                },
                error: function (error) {
                    message.error('失败：' + error);
                }
            })
        }
        setRowClassName = (record) => {
            return record.ID === this.state.rowId ? 'clickRowStyle' : '';
        }
        FindData = () => {
            const { propMethod: { findData } } = this.props;
            this.showModal(false);
            findData();
            this.reset();
        }
        // 页码改变的回调，参数是改变后的页码及每页条数
        PageChange = (page, pageSize) => {
            this.setState({ page: page, pageSize: pageSize }, () => {
                // 重新调用查询方法
                this.FindData()
            });
        }
        // 条数改变的回调
        onShowSizeChange = (current, size) => {
            this.setState({ page: current, pageSize: size }, () => {
                // 重新调用查询方法
                this.FindData()
            });
        }
        onClickRow = (record) => {
            //给右边的编辑form传值
            return {
                onClick: () => {
                    // console.log("record",record)
                    this.reset()
                    this.setState({
                        params: record,
                        ID: record.ID,
                        higherHospID: record.higherHospID,
                        cityArr: [],
                        areasArr: [],
                        VillagesArr: [],
                    })
                    if (this.state.rowId === "") {
                        this.setState({
                            rowId: record.ID,
                        });
                    } else {
                        if (this.state.rowId !== record.ID) {
                            this.setState({
                                rowId: record.ID,
                            });
                        } else {
                            this.setState({
                                rowId: "",
                            });
                            this.reset()
                            this.setState({
                                params: {},
                                ID: "",
                                higherHospID: "",
                                cityArr: [],
                                areasArr: [],
                                VillagesArr: [],
                            })
                        }
                    }
                },
            };
        }
        ImportData = () => {
            this.DataImport.DrawerShow()
        }
        handleSwithChange = (val) => {
        }
        handleStatus = (v) => {
        }
        save = () => {
            this.props.form.validateFields((err, values) => {
                const { page, pageSize } = this.state;
                const { data: params } = this.props;
                if (!err) {
                    let data = {
                        params: [{
                            ID: params && params.ID ? params.ID : "",
                            Code: values && values.Code ? values.Code : "",
                            Descripts: values.Descripts || "",
                            Color: values.Color || "",
                            ENDesc: values.ENDesc || "",
                            StDate: values.StDate ? moment(values.StDate).format('YYYY-MM-DD') : undefined,
                            EndDate: values.EndDate ? moment(values.EndDate).format('YYYY-MM-DD') : '',
                            updateUserID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).userID : ""
                           }],
                        pagination: [{
                            pageSize: pageSize,
                            currentPage: page,
                        }]
                    }             
                    $http.post("urlS", this, {
                        // code: "05100209"src.BasicData.Interface
                        code:"05100268",
                        data: data,
                        success: function (res) {
                            if (+res.errorCode === 0) {
                                if (params && params.ID) {
                                    message.success("修改成功")
                                    this.FindData();
                                } else {
                                    message.success("新增成功")
                                    this.FindData();
                                }
                            } else {
                                message.error('失败：' + res.errorMessage);
                            }
                        },
                        error: function (error) {
                            message.error('失败：' + error);
                        }
                    })
                    
                } else {
                }
            })
        }
        reset = () => {
            this.props.form.resetFields();
        }
     
      
       
        
        // 显示分页总条数
        showTotal(total) {
            return `共 ${total} 条`;
        }
        showModal = (bool) => {
            const { propMethod: { showModal } } = this.props;
            showModal(bool);
            this.reset();
        }
        render() {
            const { modalVisible, data: params, propMethod } = this.props;
            const { getFieldDecorator } = this.props.form;
           
            return (
                <Modal onCancel={() => this.showModal(false)} title={<span>{params ? params.hospDesc : ''}</span>} visible={modalVisible} width={1200} footer={<div style={{ display: "flex", justifyContent: "flex-end" }}>
                    <Button style={{ marginRight: '30px' }} onClick={() => this.showModal(false)}>取消</Button>
                    <Button style={{ marginRight: '30px' }} type="primary" onClick={this.save}>{params && params ? "更新" : "+新增"}</Button>
                    {/* <Popconfirm title="是否要删除此行" onConfirm={this.delete}>
                        <Button type="danger" disabled={this.state.rowId && this.state.rowId ? false : true} >删除</Button>
                    </Popconfirm> */}
                    <Button type="primary" onClick={this.reset}>重置</Button>
                </div>} >
                    <Row style={{ margin: "0" }}>
                        <Col span={24} style={{ paddingLeft: "0px" }}>
                            <Card>
                                <Form style={{ height: "100%", overflow: "hidden auto" }}>
                                    <Row>
                                        <Col span={6} className="patNameDom">
                                            <FormItem {...formItemLayout} label='代码'>
                                                {getFieldDecorator('Code', {
                                                    initialValue: params && params.Code ? params && params.Code : undefined,
                                                    rules: [{ required: true, message: '请输入代码', },
                                                    ],
                                                })(
                                                    <Input />
                                                )}
                                            </FormItem>
                                        </Col>
                                        <Col span={6}>
                                            <FormItem {...formItemLayout} label='描述'>
                                                {getFieldDecorator('Descripts', {
                                                    initialValue: params && params.Descripts ? params.Descripts : undefined,
                                                    rules: [{ required: true, message: '请输入描述' }],
                                                })(
                                                    <Input />
                                                )}
                                            </FormItem>
                                        </Col>
                                        <Col span={6}>
                                            <FormItem {...formItemLayout} label='颜色'>
                                                {getFieldDecorator('Color', {
                                                    initialValue: params && params.Color ? params && params.Color : undefined,
                                                    rules: [{ required: true, message: '请输入颜色' }],
                                                })(
                                                    <Input />
                                                )}
                                            </FormItem>
                                        </Col>
                                        <Col span={6} >
                                            <FormItem {...formItemLayout} label='英文描述'>
                                                {getFieldDecorator('ENDesc', {
                                                    initialValue: params && params.ENDesc ? String(params.ENDesc) : undefined,
                                                    rules: [{ required: true, message: '请输入英文描述' }],
                                                })(
                                                    <Input />
                                                )}
                                            </FormItem>
                                        </Col>
                                    </Row>
                                    <Row>
                                        <Col span={6} className="patNameDom">
                                            <FormItem {...formItemLayout} label='生效日期'>
                                                {getFieldDecorator('StDate', {
                                                    initialValue: params && params.StDate ? moment(params.StDate, "YYYY-MM-DD") : undefined,
                                                  
                                                    rules: [{ required: true, message: '请选择生效日期', },
                                                    ],
                                                })(
                                                    <DatePicker style={{ width: '100%' }} placeholder={'开始日期'} disabledDate={(curDate) => {
                                                        return curDate && curDate > moment().endOf('day');
                                                    }} />
                                                )}
                                            </FormItem>
                                        </Col>
                                        <Col span={6} className="patNameDom">
                                            <FormItem {...formItemLayout} label='失效日期'>
                                                {getFieldDecorator('EndDate', {
                                                     initialValue: params && params.EndDate ? moment(params.EndDate, "YYYY-MM-DD") : undefined,
                                                  
                                                    rules: [{ required: false, message: '请选择失效日期' }],
                                                })(
                                                    <DatePicker style={{ width: '100%' }} placeholder={'请选择失效日期'} disabledDate={(curDate) => {
                                                        return curDate && curDate > moment().endOf('day');
                                                    }} />
                                                )}
                                            </FormItem>
                                        </Col>
                                    </Row>
                                </Form>
                            </Card>
                        </Col>
                    </Row>
                </Modal>
            );
        }
    });

class RoleMaintenance extends React.Component {
    constructor() {
        super();
        this.state = {
            // 角色名称
            name: undefined,
            // 关联岗位
            quarters: undefined,
            // 记录状态
            status: undefined,
            // 表格数据
            tableData: [],
            // 表格数据总条数
            total: 0,
            showLoading: true,
            page: 1,
            pageSize: 10,
            selectData: {}, // 下拉框数据
            headerHeight: 0,

            modalVisible: false,
            editData: {}
        };
        this.columns = [
            {
                key: 1,
                title: '代码',
                dataIndex: 'Code',
                align: "center",
                width: '10%'
            },
            {
                key: 2,
                title: '描述',
                dataIndex: 'Descripts',
                align: "center",
                width: '15%'
            },
            {
                key: 3,
                title: '颜色',
                dataIndex: 'Color',
                align: "center",
                width: '10%',
            },
            {
                key: 5,
                title: '英文描述',
                dataIndex: 'ENDesc',
                align: "center",
                width: '10%'
            },
            {
                key: 6,
                title: '生效日期',
                dataIndex: 'StDate',
                align: "center",
                width: '10%'
            },
            {
                key: 7,
                title: '失效日期',
                dataIndex: 'EndDate',
                align: "center",
                width: '10%'
            },
            {
                key: 8,
                title: '创建日期',
                dataIndex: 'CreateDate',
                align: "center",
                width: '10%'
            },
            {
                key: 9,
                title: '创建时间',
                dataIndex: 'CreateTime',
                align: "center",
                width: '20%',
            },
            {
                title:'创建人员',
                key:10,
                align:"center",
                width:'10%',
                dataIndex:'CreateUserDr'


            },
            {
                title: '操作',
                key: 11,
                align: "center",
                width: 100,
                fixed: 'right',
                render: (text, record) => (
                    <span>
                        <Icon type="edit" style={{ color: '#108EE9' }}></Icon>
                <span className='span' onClick={() => this.handleCompile(record)}>编辑</span>
                    </span>
                ),
            }
        ]

    }

    componentDidMount() {
        // 初始化列表数据
        this.handleQuery();
        this.getSelectData();
        // 组件加载完毕关闭loading
        this.setState({ showLoading: false });
    }

    componentWillUnmount() {
        // 组件销毁前将静止让setState修改state的状态
        this.setState = (state, callback) => { return; }
    }

    // 角色管理下拉框数据
    getSelectData() {
        let data = {
            params: []
        }
        $http.post('urlS', this, {
            code: "01040013",
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    this.setState({ selectData: res })
                } else {
                    this.setState({ selectData: {} })
                }
            }
        })
    }

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

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

    // 请求列表数据
    getTableData() {
        let { page, pageSize } = this.state;
        let data = {};
        this.props.form.validateFields((error, values) => {
            if (error) {
                return;
            }
            data = {
                params: [{
                    Code: values.hospCode ? values.hospCode : '',
                    Descripts: values.hospDesc ? values.hospDesc : '',
                    Color: values.hospStatus ? values.hospStatus : '',
                }],
                pagination: [{
                    pageSize: pageSize,
                    currentPage: page,
                    sortColumn: "",
                    sortOrder: ""
                }]
            };
            $http.post('urlS', this, {
                code:"06010088",
                data: data,
                success: function (res) {
                  
                    if (+res.errorCode === 0 && res.result) {
                        this.setState({ tableData: res.result.Data, total: res.result.TotalCount }, () => {
                            // 数据加载成功关闭loading
                            this.child.handleLoading()
                        })
                    } else {
                        this.setState({ tableData: [], total: 0 }, () => {
                            // 数据加载成功关闭loading
                            this.child.handleLoading();
                        })
                    }
                },
                error: function () {
                    this.setState({ tableData: [], total: 0 }, () => {
                        // 数据加载成功关闭loading
                        this.child.handleLoading();
                    })
                }
            });
        });

    }

    // 查询
    handleQuery = () => {
        this.setState({ page: 1, pageSize: 10 }, () => {
            this.getTableData();
        })
    }

    // 新增跳转到新增界面
    handleAdd = () => {
        this.setState({ editData: undefined });
        this.showModal(true);
    }

    // 编辑
    handleCompile = (record) => {
       // this.setState({ editData: undefined });
        this.setState({ editData: record });
        this.showModal(true);
    }
    //控制模态框显示
    showModal = (bool) => {
        this.setState({ modalVisible: bool });
    }

    render() {
        const { getFieldDecorator } = this.props.form;
        // 组件所需参数
        const param = {
            // 表头配置
            columns: this.columns,
            // 表格数据
            data: this.state.tableData,
            // 数据总条数
            total: this.state.total,
            // 当前页数
            page: this.state.page,
            // 表格的宽度
            x: '115%',
            y: store.getState().tableHeight.y + 81 - this.state.headerHeight,
            height: store.getState().tableHeight.y + 50 - this.state.headerHeight + 'px',
        }
        const statusArr = [
            {
                id: '',
                descripts: '全部',
                descriptsSPCode: 'QB',
            }, {
                id: '1',
                descripts: '可用',
                descriptsSPCode: 'KY',
            }, {
                id: '0',
                descripts: '不可用',
                descriptsSPCode: 'BKY',
            },];
        let statusoP = []
        statusArr && statusArr.map(item => {
            statusoP.push(<Option key={item.id} role={item.descripts + '^' + item.descriptsSPCode} title={item.descripts} value={String(item.id)}>{item.descripts}</Option>)
        });
        return (
            <Spin tip="加载中..." spinning={this.state.showLoading}>
                <div>
                    <Form>
                        <Row style={{ margin: '23px 0 0 0' }}>
                            <Col span={5} >
                                <FormItem {...formItemLayout} label='代码'>
                                    {getFieldDecorator('hospCode', {
                                        //initialValue: params && params.healBureauID ? String(params.healBureauID) : undefined,
                                        rules: [{ required: false, message: '' }],
                                    })(
                                        <Input title="输入内容后可回车检索" placeholder="请输入代码" onPressEnter={this.handleQuery} />
                                    )}
                                </FormItem>
                            </Col>
                            <Col span={4} >
                                <FormItem {...formItemLayout} label='描述'>
                                    {getFieldDecorator('hospDesc', {
                                        //initialValue: undefined,
                                        rules: [{ required: false, message: '' }],
                                    })(
                                        <Input title="输入内容后可回车检索" placeholder="请输入描述" onPressEnter={this.handleQuery} />
                                    )}
                                </FormItem>
                            </Col>
                            <Col span={4} >
                                <FormItem {...formItemLayout} label='颜色'>
                                    {getFieldDecorator('hospStatus', {
                                        //initialValue: undefined,
                                        rules: [{ required: false, message: '' }],
                                    })(
                                        <Input title="输入内容后可回车检索" placeholder="请输入颜色" onPressEnter={this.handleQuery} />
                                    )}
                                </FormItem>
                            </Col>
                            <Col span={2}>
                                <Button onClick={this.handleQuery} style={{ margin: '4px 15px 20px 0', background: 'rgba(255,255,255,1)' }}>查询</Button>
                            </Col>
                            <Col span={7}>
                            </Col>
                            <Col span={2}>
                                <Button icon="plus" onClick={this.handleAdd} style={{ background: 'rgba(247,128,93,1)', color: '#fff', margin: '4px 0 0 0' }}>新增</Button>
                            </Col>
                        </Row>
                    </Form>
                </div>
                <div style={{ width: '100%', height: '10px', background: '#f0f2f5' }}></div>
                <div style={{ padding: '24px 0 0 0' }} className="table-body-height">
                    {/* handelThis将夫组件的属性与方法给子组件访问 */}
                    <PubilcTablePagination param={param} handelThis={this} onRef={this.onRef} />
                </div>
                <HospitalMaintenance data={this.state.editData} modalVisible={this.state.modalVisible} propMethod={{ showModal: this.showModal, findData: this.handleQuery }} />
            </Spin>
        )
    }
}
export default Form.create()(RoleMaintenance);