/*
 * Creator:     ML
 * CreatDate:   2019-11-16
 * descripts：  外部代码
 * */
import React from 'react';
import {Form, message, Select, Button, DatePicker, Row, Switch, Checkbox, Icon, Divider, Popconfirm} from 'antd';
import { $http } from 'containers/config/https';
import '../style/childStyle.less';
import Moment from 'moment';
import store from 'store';
import PubilcTablePagination from 'pages/common/PubilcTablePagination.jsx';

const { Option } = Select;

class ExtCode extends React.Component{
    constructor() {
        super();
        var userData = JSON.parse(sessionStorage.getItem('userData'));
        this.state = {
            selectData: {}, // 下拉框数据
            hosp: undefined, // 医院
            status: true, // 仅显示生效
            tableData: [], // 列表数据
            total: 0,
            page: 1,
            pageSize: 10,
            rowData: {}, // 编辑回显数据
            user: userData,
            medID: '',
            locData: [], // 科室下拉数据
            loading: false
        };
        this.columns = [
            {
                key: 1,
                title: '序号',
                dataIndex: 'key',
                align: "center",
                width: 80
            },
            {
                key: 2,
                title: '医院',
                dataIndex: 'hospDesc',
                align: "center",
                width: 200
            },
            {
                key: 3,
                title: '科室',
                dataIndex: 'locDesc',
                align: "center",
                width: 150
            },
            {
                key: 4,
                title: '外部代码',
                dataIndex: 'extCodeDesc',
                align: "center",
                width: 150
            },
            {
                key: 6,
                title: '状态',
                dataIndex: 'status',
                align: "center",
                width: 80,
                render(states){
                    let config = {
                        'Y': '生效',
                        'N': '失效'
                    }
                    return config[states];
                }
            },
            {
                title: '操作',
                key: 7,
                align: "center",
                width: 130,
                render: (text, record) => (
                    <span>
                        <Icon type="edit" style={{color: '#108EE9'}}></Icon>
                        <span className='span' onClick={() => this.handleCompile(record)}>编辑</span>
                        {/* 分割线 */}
                        <Divider type="vertical" />
                            <Icon type="delete" style={{color: 'rgba(240,65,52,1)'}}></Icon>
                        <Popconfirm title="删除不可恢复，你确定要删除吗?" onConfirm={() => this.handleDelete(record)} >
                            <span className='span' style={{color: 'rgba(240,65,52,1)'}}>删除</span>
                        </Popconfirm>
                    </span>
                ),
            }
        ];
    }

    componentDidMount() {
        console.log("document.querySelector('.ant-table-body').style.height",document.querySelector('.ant-table-body').style.height)
        this.getSelectData();
        // this.getLocSelectData();
        if ((this.props.medData&&this.props.medData.medID ? this.props.medData.medID : '') !== this.state.medID) {
            this.setState({medID: this.props.medData.medID}, () => {
                this.handleQuery();
            })
        } else {
            this.child.handleLoading();
        }
    }

    componentWillReceiveProps(nextProps) {
        if ((nextProps.medData&&nextProps.medData.medID ? nextProps.medData.medID : '') !== this.state.medID) {
            this.setState({medID: nextProps.medData.medID}, () => {
                this.handleQuery();
                this.resetFields();
            })
        }
    }


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

    // 获取下拉框数据
    getSelectData = () => {
        let {user} = this.state;
        let data = {
			params: [{
                logonHospID: user.hospID,
                logonGroupID: user.groupID,
                hospFlag: 'Y',
                locTypeFlag: 'Y',
                listExtCodeFlag:"Y"
			}]
		}
		$http.post('urlS', this, {
			code: "03010037",
			data: data,
			success: function (res) { 
				if (+res.errorCode === 0 && res.result) {
					this.setState({selectData: res.result})
				}
			}
		})
    }
    handleHosID=(id)=>{
      this.getLocSelectData(id)
      this.props.form.setFieldsValue({locID:undefined})
    }
    // 获取科室下拉框数据
    getLocSelectData = (id) => {
        let {user} = this.state;
        this.setState({
            locData:[]
        })
        let data = {
			params: [{
                hospID:id || ""
			}] 
		}
		$http.post('urlS', this, {
			code: "01050029",
			data: data,
			success: function (res) { 
				if (+res.errorCode === 0) {
					this.setState({locData: res.result.Data})
				}
			}
		})
    }

    // 请求列表数据
	getTableData () {
        this.setState({loading: true});
		let { page, pageSize, status, hosp, user, medID} = this.state;
		let data = {
			params: [{
                userID: user.userID,
                hospID: hosp, // 医院
                logonHospID: user.hospID,
                logonGroupID: user.groupID,
                medItemID:medID, // 医嘱项id
                hospFlag:"Y",
                status: status ? 'Y' : 'N', // 状态
			}],
			pagination:[{
				pageSize: pageSize,
				currentPage: page,
				sortColumn: "Describe",
				sortOrder: "asc"
			}]
		}
		$http.post('urlS', this, {
			code: "03010098",
			data: data,
			success: function (res) { 
				if (+res.errorCode === 0 && res.result) {
                    for(var  i = 0; i < res.result.length; i++) {
                        res.result[i].key = i + 1
                    }
                    this.setState({tableData: res.result, total: res.totalCount, loading: false}, () => {
						// 数据加载成功关闭loading
						this.child.handleLoading();
					})
				} else {
					this.setState({tableData: [], total: 0, loading: false}, () => {
						// 数据加载成功关闭loading
						this.child.handleLoading();
					})
				}
			},
			error: function () {
				this.setState({tableData: [], total: 0, loading: false}, () => {
					// 数据加载成功关闭loading
					this.child.handleLoading();
				})
			}
		})
	}

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

    handleHospID = e => {
        this.setState({hosp: e}, () => {
            this.handleQuery();
        })
    }

    // 是否生效
    handleCheckbox = e => {
        this.setState({status: e.target.checked}, () => {
            this.handleQuery();
        })
    }

    // 保存
    handleSave = () => {
        const { form: { validateFields } } = this.props;
        let {rowData, user, medID} = this.state;
        validateFields((errors, values) => {
            if (errors === null) {
                let data = {
                    params: []
                };
                let obj = JSON.parse(JSON.stringify(values));
                obj.ID = rowData&&rowData.ID ? rowData.ID : undefined;
                obj.updateUserID = user.userID;
                obj.logonHospID = user.hospID;
                obj.groupID = user.groupID;
                obj.medItemID = medID; // 医嘱项id
                obj.code=obj.code;
                obj.extCodeID= obj.extCodeID;
                obj.startDate = obj.startDate ? Moment(obj.startDate).format("YYYY-MM-DD") : '';
                obj.stopDate = obj.stopDate ? Moment(obj.stopDate).format("YYYY-MM-DD") : '';
                data.params.push(obj);
                $http.post('urlADS', this, {
                    code: rowData&&rowData.ID ? '03010100' : '03010099',
                    data: data,
                    success: function (res) { 
                        if (+res.errorCode === 0) {
                            message.success(rowData&&rowData.ID ? '编辑成功' : '新增成功');
                            this.handleQuery();
                            this.resetFields();
                        }
                    }
                })
            }
        })
    }
    
    // 重置
    resetFields = () => {
        this.props.form.resetFields(); //清空所有
        this.setState({
            rowData: {}
        })
    }

    // 编辑
    handleCompile = record => {
        this.getLocSelectData(record.hospID)
        this.setState({rowData: record})
    }

    // 删除
    handleDelete = record => {
        let {user} = this.state;
        let data = {
			params: [{
                ID: record.ID,
                updateUserID: user.userID,
                logonHospID: user.hospID,
                logonGroupID: user.groupID,
			}]
		}
		$http.post('urlADS', this, {
			code: '03010101',
			data: data,
			success: function (res) { 
				if (+res.errorCode === 0) {
					message.success('删除成功');
					// 刷新列表数据
					this.getTableData();
				}
			}
		})
    }
    compilePage=(page,pageSize)=>{
        this.setState({
            page,
            pageSize,
        },()=>{
            this.getTableData()
        })
        
    }

    render() {
        let {selectData, hosp, status, tableData, total, page, rowData, locData, loading} = this.state;
        const { getFieldDecorator } = this.props.form;
        // 组件所需参数
		const param = {
			// 表头配置
			columns: this.columns,
			// 表格数据
			data: tableData,
			// 数据总条数
			total: total,
			// 当前页数
			page: page,
			// 表格的宽度
            x: 900,
            y: 360,
            TableClassName:"extCode",
            height: store.getState().tableHeight.y-167 + 'px', 
            loading
        };

        // 医院
        let hospOption = selectData.hosp&&selectData.hosp.map((item, index) => {
            return (<Option key={index} value={item.id} onClick={()=>this.handleHosID(item.id)} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
        })
        
        // 科室
        let locOption = locData&&locData.map((item, index) => {
            return (<Option key={index} value={item.id} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
        })
          // 外部代码
          let listExtCodeOption = selectData.listExtCode&&selectData.listExtCode.map((item, index) => {
            return (<Option key={index} value={item.id} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
        })
        
        return (
            <div className="associated">
                <div>
                    {/* <div style={{background: 'rgba(228, 228, 228, 1)', height: '32px', lineHeight: '32px', fontWeight: '700'}}>
                        添加外部代码
                        <span style={{fontSize: '12px', color: '#157EDF', fontWeight: '100', marginLeft: '10px'}}>(说明：)</span>
                    </div> */}
                    <div>
                        <Form>
                            <Row>
                                <Form.Item label="医院：">
                                    {getFieldDecorator('hospID', {
                                        initialValue: rowData.hospID ? rowData.hospID : undefined,
                                        rules: [{ required: true, message: '医院不能为空' }]
                                    })(
                                        <Select showSearch optionFilterProp="seatchprop"  style={{width: '120px', marginRight: '8px'}} placeholder="请选择">
                                            {hospOption}
                                        </Select>
                                    )}
                                </Form.Item>
                                <Form.Item label="科室：">
                                    {getFieldDecorator('locID', {
                                        initialValue: rowData.locID ? rowData.locID : undefined,
                                        rules: [{ required: true, message: '请先选择医院' }]
                                    })(
                                        <Select showSearch optionFilterProp="seatchprop"  style={{width: '120px', marginRight: '8px'}} placeholder="请先选择医院">
                                            {locOption}
                                        </Select>
                                    )}
                                </Form.Item>
                                <Form.Item label="外部代码：">
                                    {getFieldDecorator('extCodeID', {
                                        initialValue: rowData.extCodeID? rowData.extCodeID : undefined,
                                        rules: [{ required: true, message: '请选择外部代码' }]
                                    })(
                                        <Select showSearch optionFilterProp="seatchprop"  style={{width: '120px', marginRight: '8px'}} placeholder="请选择">
                                            {listExtCodeOption}
                                        </Select>
                                    )}
                                </Form.Item>
                            </Row>
                            <Row>
                                <Form.Item label="生效日期：">
                                    {getFieldDecorator('startDate', {
                                        initialValue: rowData.startDate ? Moment(rowData.startDate) : Moment(),
                                        rules: [{ required: true, message: '生效日期不能为空' }]
                                    })(
                                        <DatePicker style={{width: '150px', marginRight: '8px'}} format="YYYY-MM-DD" allowClear />
                                    )}
                                </Form.Item>
                                <Form.Item label="失效日期：">
                                    {getFieldDecorator('stopDate', {
                                        initialValue: rowData.stopDate ? Moment(rowData.stopDate) : undefined,
                                    })(
                                        <DatePicker style={{width: '150px', marginRight: '8px'}} format="YYYY-MM-DD" allowClear />
                                    )}
                                </Form.Item>
                                <span style={{display: 'inline-block', marginTop: '4px'}}>
                                    <Button style={{marginRight: '8px'}} onClick={this.resetFields}>清空</Button>
                                    <Button type="primary" onClick={this.handleSave}>保存</Button>
                                </span>
                            </Row>
                        </Form>
                    </div>
                </div>
                <div>
                    <div style={{background: 'rgba(228, 228, 228, 1)', height: '32px', lineHeight: '32px', fontWeight: '700'}}>
                        已添加外部代码
                        <span style={{float: 'right', fontWeight: '100'}}>
                            <Select value={hosp} onChange={this.handleHospID} onPressEnter={this.handleHospNameEnter} showSearch optionFilterProp="seatchprop" allowClear style={{width: '200px', marginRight: '8px'}} placeholder="根据医院过滤数据">
                                {hospOption}
                            </Select>
                            <Checkbox checked={status} onChange={this.handleCheckbox} style={{fontSize: '12px', color: '#000'}}>仅显示生效</Checkbox>
                        </span>
                    </div>
                    <PubilcTablePagination param={param} handelThis={this} onRef={this.onRef} />
                </div>
            </div>
        )
    }
};
const ExtCodeForm = Form.create()(ExtCode);
export default ExtCodeForm;