// 执行科室  ML 最后修改时间 2019-12-24
import React from 'react';
import {Form, message, Select, Button, DatePicker, Row, Switch, Checkbox, Icon, Divider, Popconfirm,Col} from 'antd';
import { $http } from 'containers/config/https';
// import '../style/childStyle.less';
import Moment from 'moment';
import PubilcTablePagination from 'pages/common/PubilcTablePagination.jsx';

const { Option } = Select;
const formItemLayoutType = {
    labelCol: { span: 9 },
    wrapperCol: { span: 15 }
}
const paddingRight = {
    paddingRight:"0"
}
class OLExecutiveDepartments 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
            },
            {
                align: "center",
                title: '执行医院',
                dataIndex: 'recHospDesc',
                key: 8,
                width: 150
            }, 
            {
                key: 4,
                title: '执行科室',
                dataIndex: 'recLocDesc',
                align: "center",
                width: 150
            },
            {
                key: 5,
                title: '状态',
                dataIndex: 'status',
                align: "center",
                width: 80
            },
            {
                key: 6,
                title: '默认',
                dataIndex: 'defaultFlag',
                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() {
        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
    }
    compilePage=(page,pageSize)=>{
        this.setState({
            page,
            pageSize,
        },()=>{
            this.getTableData()
        })
        
    }

    // 获取下拉框数据
    getSelectData = () => {
        let {user} = this.state;
        let data = {
			params: [{
                logonHospID: user.hospID,
                logonGroupID: user.groupID,
                hospFlag: 'Y',
                locTypeFlag: 'Y',
			}]
		}
		$http.post('urlS', this, {
			code: "03010037",
			data: data,
			success: function (res) { 
				if (+res.errorCode === 0 && res.result) {
					this.setState({selectData: res.result})
				}
			}
		})
    }

    // 获取科室下拉框数据
    getLocSelectData = () => {
        let {user} = this.state;
        let data = {
			params: [{
                hospID: user.hospID
			}]
		}
		$http.post('urlS', this, {
			code: "04020008",
			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,
                groupID: user.groupID,
				medID, // 医嘱项id
                active: status ? 'Y' : 'N', // 状态
			}],
			pagination:[{
				pageSize: pageSize,
				currentPage: page,
				sortColumn: "Describe",
				sortOrder: "asc"
			}]
		}
		$http.post('urlS', this, {
			code: "03010030",
			data: data,
			success: function (res) { 
				if (+res.errorCode === 0 && res.result) {
                    for(var  i = 0; i < res.result.data.length; i++) {
                        res.result.data[i].key = i + 1
                    }
                    this.setState({tableData: res.result.data, total: res.result.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.userID = user.userID;
                obj.logonHospID = user.hospID;
                obj.recHospID = values.recHospID;
                obj.groupID = user.groupID;
                obj.medID = medID; // 医嘱项id
                obj.startDate = obj.startDate ? Moment(obj.startDate).format("YYYY-MM-DD") : '';
                obj.stopDate = obj.stopDate ? Moment(obj.stopDate).format("YYYY-MM-DD") : '';
                obj.defaultFlag = obj.defaultFlag ? "Y" : "N";
                data.params.push(obj);
                $http.post('urlADS', this, {
                    code: '03010028',
                    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 => {
        // console.log(record)
        this.props.form.resetFields()
        this.setState({rowData: record})
        this.setState({
            hosID:record.hospID,
            locID:record.locTypeID,
        },()=>{
            this.getPublicBaseLocSelect()
            this.getPublicLocSelect(record.recHospID)//接收科室
        })
    }

    // 删除
    handleDelete = record => {
        let {user} = this.state;
        let data = {
			params: [{
                id: record.id,
                userID: user.userID,
                logonHospID: user.hospID,
                groupID: user.groupID,
			}]
		}
		$http.post('urlADS', this, {
			code: '03010029',
			data: data,
			success: function (res) { 
				if (+res.errorCode === 0) {
					message.success('删除成功');
					// 刷新列表数据
					this.getTableData();
				}
			}
		})
    }
    //医院
    handleBaseHosp=(id)=>{
        this.props.form.setFieldsValue({locID:undefined})
        if(id){
            this.setState({
                hosID:id
            },()=>{
                 this.getPublicBaseLocSelect()
            })
        }else{
            this.setState({
                hosID:"",
                publicBaseLocArr:[]
            },()=>{
                this.getPublicBaseLocSelect()
            })
        }
       
    }
    //科室类型
    handleBaseLoc=(id)=>{
        this.props.form.setFieldsValue({locID:undefined})
        if(id){
            this.setState({
                locID:id
            },()=>{
                this.getPublicBaseLocSelect()
            })
        }else{
            this.setState({
                locID:"",
                publicBaseLocArr:[]
            },()=>{
                this.getPublicBaseLocSelect()
            })
        }
    }
 //获取开单科室下拉框
 getPublicBaseLocSelect = () => {
    let data = {}
    data = {
        params: [{
            hospID:this.state.hosID || "",
            locTypeID:this.state.locID || ""
        }],
    }
    $http.post('urlS', this, {
        code: '01050029',
        data: data,
        success: function (res) {
            if (+res.errorCode === 0 && res.result.Data) {
                let arr = res.result.Data && res.result.Data.map((item, index) => {
                    res.result.Data[index].key = Number(index)
                })
                this.setState({
                    publicBaseLocArr: res.result.Data,
                })
            } else {

            }
        }
    })
}
//点击右侧医院选项过滤执行科室
handleHosp=(e,id)=>{
    this.props.form.setFieldsValue({recLocID:undefined ,})
    this.getPublicLocSelect(id)
}
 //获取公共科室下拉框 执行科室
 getPublicLocSelect = (hospID) => {
    let data = {}
    data = {
        params: [{
            hospID:hospID&&hospID?hospID:"",
        }],
    }
    $http.post('urlS', this, {
        code: '01050029',
        data: data,
        success: function (res) {
            if (+res.errorCode === 0 && res.result.Data) {
                let arr = res.result.Data && res.result.Data.map((item, index) => {
                    res.result.Data[index].key = Number(index)
                })
                this.setState({
                    publicLocArr: res.result.Data,
                })
            } else {

            }
        }
    })
}
    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:"otherName",
            height: '400px',
            loading
        };

        // 医院
        let hospOption =[] 
        let BaseHosOp = []
          selectData.hosp&&selectData.hosp.map((item, index) => {
            hospOption.push(<Option key={index} onClick={(e,)=>this.handleHosp(e,item.id)} value={item.id} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
            BaseHosOp.push(<Option key={item.id} onClick={()=>this.handleBaseHosp(item.id)} value={String(item.id)}>{item.descripts}</Option>)
        })
        // 科室类型
        let locTypeOption = selectData.locType&&selectData.locType.map((item, index) => {
            return (<Option key={index} onClick={()=>this.handleBaseLoc(item.id)} value={item.id} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
        })
        // 科室
        let locOption = []
        this.state.publicBaseLocArr && this.state.publicBaseLocArr.map((item,index) => {
            locOption.push(<Option key={index} value={item.id} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
        })
         //接收类型
         let getLocOp = []
         this.state.publicLocArr && this.state.publicLocArr.map((item) => {
             getLocOp.push(<Option key={item.id} seatchprop={item.descripts + '^' + item.descriptsSPCode} title={item.descripts} value={String(item.id)}>{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  gutter={60} >
                                <Col span={5} style={paddingRight}>
                                <Form.Item style={{width:"100%"}} label="医院：" {...formItemLayoutType}>
                                    {getFieldDecorator('hospID', {
                                        initialValue: rowData.hospID ? rowData.hospID : undefined,
                                        rules: [{ required: true, message: '请选择医院' }],
                                    })(
                                        <Select onChange={this.handleBaseHosp} showSearch optionFilterProp="seatchprop" allowClear  placeholder="请选择">
                                            {BaseHosOp}
                                        </Select>
                                    )}
                                </Form.Item>
                                </Col>
                                <Col span={5}  style={paddingRight}>
                                <Form.Item style={{width:"100%"}} label="科室类型" {...formItemLayoutType}>
                                    {getFieldDecorator('locTypeID', {
                                        initialValue: rowData.locTypeID ? rowData.locTypeID : undefined,
                                        rules: [{ required: false, message: '' }]
                                    })(
                                        <Select  onChange={this.handleBaseLoc} showSearch optionFilterProp="seatchprop" allowClear  placeholder="请选择">
                                            {locTypeOption}
                                        </Select>
                                    )}
                                </Form.Item>
                                </Col>
                                <Col span={5}  style={paddingRight}>
                                <Form.Item style={{width:"100%"}} label="开单科室：" {...formItemLayoutType}>
                                    {getFieldDecorator('locID', {
                                        initialValue: rowData.locID ? rowData.locID : undefined,
                                    })(
                                        <Select showSearch optionFilterProp="seatchprop" allowClear  placeholder="请选择">
                                            {locOption}
                                        </Select>
                                    )}
                                </Form.Item>
                                </Col>
                            <Col span={5} style={paddingRight}>
                                <Form.Item style={{width:"100%"}} label="设为默认：" {...formItemLayoutType}>
                                    {getFieldDecorator('defaultFlag', {
                                        initialValue: rowData.defaultFlag ? (rowData.defaultFlag === 'Y' ? true : false) : undefined,
                                    })(
                                        <Switch style={{marginRight: '8px'}} />
                                    )}
                                </Form.Item>
                                </Col>
                             <Col span={2}>
                             <Button style={{marginRight: '8px'}} onClick={this.resetFields}>清空</Button>
                             </Col>   
                            </Row>
                            <Row  gutter={60} >
                            <Col span={5} style={paddingRight}>
                            <Form.Item style={{width:"100%"}} label="执行医院：" {...formItemLayoutType}>
                                    {getFieldDecorator('recHospID', {
                                        initialValue: rowData.recHospID ? rowData.recHospID : undefined,
                                        rules: [{ required: true, message: '请选择执行医院' }]
                                    })(
                                        <Select showSearch optionFilterProp="seatchprop"  placeholder="请选择">
                                            {hospOption}
                                        </Select>
                                    )}
                                </Form.Item>
                                </Col>
                            <Col span={5} style={paddingRight}>
                            <Form.Item style={{width:"100%"}} label="执行科室：" {...formItemLayoutType}>
                                    {getFieldDecorator('recLocID', {
                                        initialValue: rowData.recLocID ? rowData.recLocID : undefined,
                                        rules: [{ required: true, message: '执行科室不能为空' }]
                                    })(
                                        <Select showSearch optionFilterProp="seatchprop" placeholder="请选择">
                                            {getLocOp}
                                        </Select>
                                    )}
                                </Form.Item>
                                </Col>
                                <Col span={5} style={paddingRight}>
                                <Form.Item style={{width:"100%"}} label="生效日期：" {...formItemLayoutType}>
                                    {getFieldDecorator('startDate', {
                                        initialValue: rowData.startDate ? Moment(rowData.startDate) : Moment(),
                                        rules: [{ required: true, message: '生效日期不能为空' }]
                                    })(
                                        <DatePicker  format="YYYY-MM-DD" allowClear />
                                    )}
                                </Form.Item>
                                </Col>
                                <Col span={5} style={paddingRight}>
                                <Form.Item style={{width:"100%"}} label="失效日期：" {...formItemLayoutType}>
                                    {getFieldDecorator('stopDate', {
                                        initialValue: rowData.stopDate ? Moment(rowData.stopDate) : undefined,
                                    })(
                                        <DatePicker  format="YYYY-MM-DD" allowClear />
                                    )}
                                </Form.Item>
                                </Col >
                                <Col span={2}>
                                <Button type="primary" onClick={this.handleSave}>保存</Button>
                                </Col>
                            </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 OLExecutiveDepartmentsForm = Form.create()(OLExecutiveDepartments);
export default OLExecutiveDepartmentsForm;