/**
 * 
 * 互联网医院知识库维护
 */
import React from 'react';
import {
    Card, Tree, Input, Form, Select, Row, Col, Checkbox, Modal,
    DatePicker, Button, Icon, Divider, message,
} from 'antd';
import { Util, dayFormat } from 'tools/index';
import { $http } from 'containers/config/https';
import store from 'store';
import './KnowledgeBase.less';
import { data } from 'autoprefixer';
import moment from 'moment';

const Search = Input.Search;
const Option = Select.Option;
const { TreeNode, DirectoryTree } = Tree;
const TextArea = Input.TextArea;
var userData = JSON.parse(sessionStorage.getItem('userData'));
class KnowledgeBase extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            dataSource: [],     // 模板元素数据源
            // knowledgeBaseData: [],     // 知识库列表数据源
            medicalRecordData: [],  // 病历下拉数据
            medicalRecordID: '',    // 选中病历id
            searchVal: '',      // 搜索框的值
            validFlag: true,  // 生效标志
            id: '',             // 知识库id
            element: '',        // 选中元素id
            title: '',          // 知识库名称
            content: '',        // 知识库内容
            startDate: '',      // 生效日期
            stopDate: '',        // 失效日期
            // expandedKeys: []    // 展开的目录
            currentEMRID: ''      // 当前选择的病历
        }
        this.selectFocus = React.createRef();
    }

    componentDidMount() {
        this.getMedcialRecordData();
    }

    initData() {

    }

    //查询知识库列表
    searchKnowledgeBaseList = () => {
        let { currentEMRID } = this.state;
        if (!currentEMRID) return;
        this.handleChange(currentEMRID);
    }
    //获取病历下拉数据
    getMedcialRecordData = () => {
        let data = {
            params: [{}]
        }
        $http.post('urlDeault', this, {
            code: "10020001",
            data: data,
            success: function (res) {
                if (res.errorCode == '0') {
                    this.setState({ medicalRecordData: res.result.TemplateList })
                }
            }
        });
    }
    // 选择病历查询元素
    handleChange = (value) => {
        let data = {
            params: [{
                IEMRTemplateID: value,
                searchVal: this.state.searchVal,
                validFlag: this.state.validFlag
            }]
        }
        $http.post('urlDeault', this, {
            code: "10020012",
            data: data,
            success: function (res) {
                if (res.errorCode == '0') {
                    console.log('选择病历查询元素', res)
                    this.setState({
                        dataSource: res.result,
                        currentEMRID: value
                    })
                }
            }
        });
    }
    // 搜索框内容改变
    searchInputChange = (e) => {
        this.setState({ searchVal: e.target.value })
    }
    // 生效标志
    changeValidFlag = (e) => {
        this.setState({ validFlag: e.target.checked }, () => {
            this.searchKnowledgeBaseList();
        })
    }
    // 选中叶子节点
    onSelect = (keys, event) => {
        // console.log('选中叶子节点',event)
        if (event.node.props.isLeaf == true) {
            this.setState({
                id: event.node.props.value,
                title: event.node.props.title,
                content: event.node.props.content,
                element: event.node.props.element,
                startDate: event.node.props.startDate,
                stopDate: event.node.props.stopDate
            }, () => console.log('选中叶子节点', this.state))
        }else{
            this.setState({element: event.node.props.eventKey})
        }
    };
    // 加载知识库明细
    loadKnowledgeBaseDetail = () => {
        let data = {
            params: [{
                docID: userData.userID,
                element: this.state.element
            }]
        }
        $http.post('urlDeault', this, {
            code: "03100154",
            data: data,
            success: function (res) {
                if (res.errorCode == '0') {
                    // console.log('加载明细成功');
                    this.setState({
                        knowledgeBaseData: res.result
                    })
                }
            }
        });
    }
    // 知识库展开
    onExpand = (expandedKeys, b) => {
        // if(b.expanded){ 
        //     if(expandedKeys.length>0){ 
        //         expandedKeys.splice(0,expandedKeys.length-1) 
        //     } 
        // } 
        // this.setState({ 
        //     expandedKeys:expandedKeys,
        //     element: expandedKeys[0] ? expandedKeys[0] : ''
        // })
    };
    // 右侧内容改动
    knowledgeBaseOnChange = (code, val) => {
        this.setState({ [code]: val });
    }

    deleteKnowledgeBase = () => {
        if (this.state.element == '') return;
        let data = {
            params: [{
                delArr: [this.state.id]
            }]
        }
        $http.post('urlDeault', this, {
            code: "03100153",
            data: data,
            success: function (res) {
                if (res.errorCode == '0') {
                    // this.loadKnowledgeBaseDetail();
                    this.searchKnowledgeBaseList()
                    message.success('删除成功');
                }
            }
        });
    }
    saveKnowledgeBase = (code) => {
        let { id, title, element, content, startDate, stopDate } = this.state;
        let data = {
            params: [{
                id: code == 'insert' ? '' : id,
                title,
                content,
                element,
                startDate,
                stopDate
            }]
        }
        console.log(data);
        $http.post('urlDeault', this, {
            code: "03100152",
            data: data,
            success: function (res) {
                if (res.errorCode == '0') {
                    // this.loadKnowledgeBaseDetail();
                    this.searchKnowledgeBaseList()
                    message.success(code == 'insert' ? '新增成功' : '更新成功');
                }
            }
        });
    }
    render() {
        return (
            <div className='complete-body' style={{ height: '100%', background: '#f0f2f5' }}>
                <div className='complete-left-card'>
                    <Card className='top-card' hoverable={true} title={<div className="card-title-left-icon"><div></div>
                                    查找知识库</div>}>
                        <div className='input-margin'>
                            <Row>
                                <Col span={5}>选择病历</Col>
                                <Col span={19}>
                                    <Select onChange={this.handleChange}>
                                        {this.state.medicalRecordData.map(item => {
                                            return <Option key={item.id} value={item.id}>{item.IEMRTemplateDesc}</Option>
                                        })}
                                    </Select>
                                </Col>
                            </Row >
                        </div>
                        <div className='input-margin'>
                            <Row >
                                <Col span={5}>查找知识库</Col>
                                <Col span={19}><Input placeholder='输入名称查找知识库' onChange={this.searchInputChange} onPressEnter={this.searchKnowledgeBaseList} /></Col>
                            </Row>
                        </div>
                        <div style={{ marginTop: 5 }}>
                            <Checkbox checked={this.state.validFlag} onChange={this.changeValidFlag} />仅显示生效
                    </div>
                        <div style={{ marginTop: 5 }}>
                        </div>
                    </Card>
                    <Card className='bottom-card' hoverable={true} title={<div className="card-title-left-icon"><div></div>
                    知识库列表</div>}>
                        <DirectoryTree onSelect={this.onSelect} onExpand={this.onExpand}>
                            {this.state.dataSource.map(item => {
                                return (
                                    <TreeNode title={item.IEMRTempElementDesc} key={item.IEMRTempElementID}>
                                        {item.IEMRKnowledge.map(data => {
                                            return (
                                                <TreeNode
                                                    title={data.title}
                                                    key={'leaf' + data.id}
                                                    value={data.id}
                                                    content={data.content}
                                                    element={data.element}
                                                    startDate={data.startDate}
                                                    stopDate={data.stopDate}
                                                    isLeaf
                                                />
                                            )
                                        })}
                                    </TreeNode>
                                )
                            })}
                        </DirectoryTree>
                    </Card>
                </div>
                <Card className='complete-right-card' hoverable={true} title={<div className="card-title-left-icon"><div></div>
                知识库内容</div>}>
                    <Row><span style={{ color: 'red' }}>*</span>知识库名称
                        <Input
                            className='input-margin'
                            value={this.state.title}
                            onChange={(e) => this.knowledgeBaseOnChange('title', e.target.value)}
                        ></Input>
                    </Row>
                    <Row><span style={{ color: 'red' }}>*</span>知识库详细内容
                        <TextArea
                            className='input-margin'
                            autoSize={{ minRows: 15, maxRows: 15 }}
                            onChange={(e) => this.knowledgeBaseOnChange('content', e.target.value)}
                            value={this.state.content}
                        ></TextArea>
                    </Row>
                    <Row className='input-margin'>
                        <Col span={5}><span style={{ color: 'red' }}>*</span>生效日期：
                            <DatePicker
                                onChange={(date) => this.knowledgeBaseOnChange('startDate', date ? date.format('YYYY-MM-DD') : '')}
                                format='YYYY-MM-DD'
                                value={this.state.startDate ? moment(this.state.startDate, 'YYYY-MM-DD') : null}
                            ></DatePicker>
                        </Col>
                        <Col span={5}>失效日期：
                            <DatePicker
                                allowClear
                                onChange={(date) => this.knowledgeBaseOnChange('stopDate', date ? date.format('YYYY-MM-DD') : '')}
                                format='YYYY-MM-DD'
                                value={this.state.stopDate ? moment(this.state.stopDate, 'YYYY-MM-DD') : null}
                            ></DatePicker>
                        </Col>
                    </Row>
                    <Row >
                        <Col span={3} offset={6}>
                            <Button type="danger" ghost onClick={this.deleteKnowledgeBase}>删除</Button>
                        </Col>
                        <Col span={3}>
                            <Button type='primary' onClick={this.saveKnowledgeBase.bind(this, 'update')}>保存</Button>
                        </Col>
                        <Col span={3}>
                            <Button type='primary' style={{ background: "#0079FE" }} onClick={this.saveKnowledgeBase.bind(this, 'insert')}>新增知识库</Button>
                        </Col>
                    </Row>
                </Card>
            </div>)
    }
}

export default KnowledgeBase;