/**
 * 诊断模板编辑
 */
import React, { Component } from 'react';
import { Input, Form, Select, Modal, Button, DatePicker, Radio, Table, Card, Row, Col, Checkbox, Pagination, message } from 'antd';
import { Util } from 'tools/index';
import moment from 'moment';
import { $http } from 'containers/config/https';
import CommonPagination from 'components/pagination/index';
import '../style/index.less';

const Option = Select.Option;
var userData;
class AddDiagTemplateModal extends Component {
    constructor(props) {
        var sessionData = JSON.parse(sessionStorage.getItem('userData'));
        super(props);
        this.state = {
            newTemplate: true,
            desc: "",
            alias: "",
            activeDate: new Date().toLocaleDateString(),
            invalidDate: "",
            findDesc: "",
            activeCheck: true,
            dataSource: [],
            total: 0,
            page: 1,
            pageSize: 10,
            selectedRow: '',
            defTempletTypeID: '',
            templetTypeID: '',
            userData:sessionData
        }
        this.columns = [
            {
                title: '级别',
                dataIndex: 'templetTypeDesc',
                width: 120,
                align: 'center',
            }, {
                title: '名称',
                dataIndex: 'descripts',
                width: 120,
                align: 'center',
            }, {
                title: '别名',
                dataIndex: 'alias',
                width: 120,
                align: 'center',
            }, {
                title: '状态',
                dataIndex: 'status',
                width: 120,
                align: 'center',
            },
        ]
    }
    componentWillUnmount() {
        // 组件销毁前将静止让setState修改state的状态
        this.setState = (state, callback) => { return; }
    }
    componentDidMount() {

    }
    loadTypeData() {

    }
    componentWillReceiveProps(nextprops) {
        if (nextprops.visible) {
            this.initModalData();
            this.loadTemplateData('', '', '');
        }
    }
    loadTemplateData = (value, page, pageSize) => {
        var params = {
            params: [{
                findDesc: value,
                locID: this.state.userData.locID,
                active: this.state.activeCheck ? "Y" : "N",
            }],
            pagination: [{
                pageSize: this.state.pageSize,
                currentPage: page
            }]

        }
        $http.post('urlDeault', this, {
            code: "03050035",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    this.setState({
                        dataSource: res.result.templateList,
                        total: res.result.totalCount
                    })
                }
            }
        });
    }
    initModalData() {
        let templetTypeID = "";
        this.props.templetType.map((item) => {
            if (item.defID !== "") {
                templetTypeID = item.defID;
            }
        })
        this.setState({
            newTemplate: true,
            desc: "",
            alias: "",
            activeDate: new Date().toLocaleDateString(),
            invalidDate: "",
            findDesc: "",
            activeCheck: true,
            dataSource: [],
            total: 0,
            page: 1,
            pageSize: 10,
            selectedRow: '',
            templetTypeID: templetTypeID,
            defTempletTypeID: templetTypeID,
        })
    }

    //保存模板
    onSubmit = () => {
        if ((Util.isEmpty(this.state.desc)) && (Util.isEmpty(this.state.activeDate))) {
            message.warn("模板名称和生效日期均不能为空!",this.state.userData && this.state.userData.messageTime)
            return;
        }
        if ((!this.state.newTemplate) && (Util.isEmpty(this.state.selectedRow.id))) {
            message.warn("请选择要添加的历史模板!",this.state.userData && this.state.userData.messageTime)
            return;
        }
        var params = {
            params: [{
                desc: this.state.desc,
                alias: this.state.alias,
                activeDate: this.state.activeDate,
                invalidDate: this.state.invalidDate,
                newTemplate: this.state.newTemplate ? "Y" : "N",
                id: this.state.selectedRow.id,
                templetTypeID: this.state.templetTypeID,
                userID: this.state.userData.userID,
                locID: this.state.userData.locID,
                diagList: this.props.diagList,
            }]
        }
        $http.post('urlDeault', this, {
            code: "03050034",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    message.success("保存成功！",this.state.userData && this.state.userData.messageTime);
                    this.props.handleThis.initTempletTreeData();
                    this.props.onCancel();
                }
            }
        });

    }
    //选择模板类型事件
    onTemplateChange(flag, e) {
        this.setState({
            newTemplate: flag,
        })
    }
    onFindChange = (e) => {
        this.setState({
            findDesc: e.target.value,
        })
        this.loadTemplateData(e.target.value, '', '');
    }
    //输入框文本改变
    onChange(flag, e) {
        this.setState({
            [flag]: e.target.value,
        })
    }

    //日期改变事件
    onDateChange(flag, date, dateString) {
        this.setState({
            [flag]: dateString,
        })
    }
    //仅显示有效
    onActiveCheckChange = (e) => {
        this.setState({
            activeCheck: e.target.checked,
        }, () => {
            this.loadTemplateData('', this.state.page, '');
        })
    }

    //改变单页显示数量
    changePageSize(current, pageSize) {
        this.setState({ pageSize: pageSize, page: current }, () => {
            this.loadTemplateData('', current, pageSize);
        });
    }

    //分页切换
    onPageChange = (page, pageSize) => {
        this.setState({ page: page }, () => {
            this.loadTemplateData('', page, '');
        });
    }
    //点击table中的行
    onTableRowClick = (record, index, e) => {
        if (this.state.selectedRow.id === record.id) {
            //再次点击相同行,清空选中
            this.setState({
                selectedRow: '',
                desc: "",
                alias: "",
                activeDate: new Date().toLocaleDateString(),
                invalidDate: "",
                templetTypeID: this.state.defTempletTypeID,
                newTemplate: true,
            })
        } else {
            this.setState({
                selectedRow: record,
                desc: record.descripts,
                alias: record.alias,
                activeDate: record.startDate,
                invalidDate: record.stopDate,
                templetTypeID: record.templetTypeID,
                newTemplate: false,
            })
        }
    }

    //输入名车回车/失去焦点自动生成别名
  getOtherName=()=>{
    let data = {}
    data = {
      params: [{
        descripts: this.state.desc||"",
    }]     
    }
    $http.post('urlS', this, {
      code: "01040117",
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
            console.log(res)
            this.setState({
                alias:res.result
            })
        //   this.props.form.setFieldsValue({othName:this.props.form.getFieldValue("docMesName")+"_"+res.result})
        //   setTimeout(() => {
        //     this.otherName.current.focus();
        // }, 300)
        } 
      }
    })
  }


    ///行背景色
    setRowClassName = (row) => {
        return row.id === this.state.selectedRow.id ? 'clickRowStyle' : '';
    }
    //保存类型发生改变时调用
    onTypeChange = (value) => {
        this.setState({
            templetTypeID: value,
        })
    }
    render() {
        let templetType = [];
        let templetTypeID = this.state.templetTypeID;
        this.props.templetType.map((item) => {
            if ((templetTypeID === '') && (item.defID !== "")) {
                templetTypeID = item.defID;
            }
            templetType.push(<Option value={item.id} key={item.id}>{item.descripts}</Option>)
        })
        return (
            <Modal className='doctor-diag-template'
                title={'添加诊断模板'}
                width="780px"
                maskClosable={false}
                visible={this.props.visible}
                onCancel={this.props.onCancel}
                onOk={this.onSubmit}
                style={{
                    height: '640px',
                    background: '#FFFFFF',
                    borderRadius: '6px',
                    top: '140px'
                }}
            >

                <div style={{ background: '#FFFFFF' }}>
                    <div>
                    <Radio style={{background:'#FFFFFF'}} checked={this.state.newTemplate} onChange={this.onTemplateChange.bind(this, true)} /><span>{this.state.selectedRow.id ? '编辑诊断模板' : '添加到新模板'}</span>
                    <Card>
                        <Row style={{ padding: '13px' }}>
                            <Col span={3}>
                                <span style={{ color: '#f5222d', fontFamily: 'SimSun' }}>*</span>
                                名称：
                            </Col>
                            <Col span={5}>
                                <Input value={this.state.desc} onBlur={this.getOtherName} onPressEnter={this.getOtherName} onChange={this.onChange.bind(this, "desc")} placeholder='请输入名称' style={{ width: '90%' }} />
                            </Col>
                            <Col span={3}>
                                {/* <span style={{ color: '#f5222d', fontFamily: 'SimSun' }}>*</span> */}
                                模板别名：
                            </Col>
                            <Col span={5}>
                                <Input value={this.state.alias}    onChange={this.onChange.bind(this, "alias")} placeholder='不能超过15个字' style={{ width: '90%' }} maxLength={15} />
                            </Col>

                            <Col span={3}>
                                <span style={{ color: '#f5222d', fontFamily: 'SimSun' }}>*</span>
                                使用级别:
                            </Col>
                            <Col span={5}>
                                <Select
                                    onChange={this.onTypeChange}
                                    value={templetTypeID}
                                    style={{ width: '90%' }}
                                >
                                    {templetType}
                                </Select>
                            </Col>
                            
                        </Row>
                        <Row style={{ padding: '8px' }}>
                            <Col span={3}>
                                <span style={{ color: '#f5222d', fontFamily: 'SimSun' }}>*</span>
                                生效日期:
                            </Col>
                            <Col span={5}>
                                <DatePicker
                                    style={{ width: '90%' }}
                                    onChange={this.onDateChange.bind(this, "activeDate")}
                                    value={this.state.activeDate !== "" ? moment(this.state.activeDate, 'YYYY-MM-DD') : moment(new Date(), 'YYYY-MM-DD')}>
                                </DatePicker>
                            </Col>
                            <Col span={3}>
                                失效日期：
                            </Col>
                            <Col span={5}>
                                <DatePicker
                                    style={{ width: '90%' }}
                                    onChange={this.onDateChange.bind(this, "invalidDate")}
                                    value={this.state.invalidDate !== "" ? moment(this.state.invalidDate, 'YYYY-MM-DD') : null}>
                                </DatePicker>
                            </Col>
                        </Row>
                        <Row style={{ padding: '3px' }}>
                           
                        </Row>
                    </Card>
                    </div>
                    <div style={{"margin-top":"35px"}}>
                    <Radio checked={!this.state.newTemplate}onChange={this.onTemplateChange.bind(this, false)}/> 添加到历史模板
                    <Card>
                        <Table columns={this.columns}
                            style={{ height: 300 }}
                            scroll={{ y: 180 }}
                            dataSource={this.state.dataSource}
                            title={() => {
                                return <div>
                                    <Input
                                        value={this.state.findDesc}
                                        onChange={this.onFindChange.bind(this)}
                                        placeholder='输入模版名称/别名查询' style={{ width: 240 }}
                                    />
                                    <Checkbox style={{ marginLeft: 10 }}
                                        checked={this.state.activeCheck}
                                        onChange={this.onActiveCheckChange}
                                    />仅显示有效
                            </div>
                            }}
                            rowKey={(data) => {
                                return data.id
                            }}
                            rowClassName={this.setRowClassName}
                            onRow={(record, index) => ({ onClick: (e) => { this.onTableRowClick(record, index, e) } })}
                            pagination={false}></Table>
                        {/*<Pagination
                            size="small"
                            showQuickJumper
                            showSizeChanger
                            defaultCurrent={1}
                            current={this.state.page}
                            total={this.state.total}
                            bordered
                            onShowSizeChange={this.changePageSize.bind(this)}
                            onChange={this.onPageChange.bind(this)}
                            style={{ textAlign: "right", marginTop: '13px' }}
                        />*/}
                         <CommonPagination
							size='small'
							current={this.state.page}
							total={this.state.total}
							search='search'
							onShowSizeChange={this.changePageSize.bind(this)}
							dataSource={this.state.tableData}
							onChange={this.onPageChange.bind(this)}
							style={{ textAlign: "right", marginTop: '13px' }}
						/> 
                    </Card>
                    </div>
                </div>
            </Modal>
        )
    }

}
export default AddDiagTemplateModal;