/**
 * 检查部位
 */
import React from 'react';
import {
    Card, Table, Input, Select, Pagination, DatePicker, Button, Popconfirm, Icon, message, Checkbox,
} from 'antd';
import { Util, dayFormat } from 'tools/index';
import { $http } from 'containers/config/https';
import store from 'store';
import moment from 'moment';
import '../style/index.less';

const Option = Select.Option;
class CheckBodyPartsTabPane extends React.Component {
    constructor(props) {
        super(props)
        var userData = JSON.parse(sessionStorage.getItem('userData'))
        this.state = {
            dataSource: [],
            total: 0,
            page: 1,
            pageSize: 10,
            userData: userData,
            tabPageSize: 10,
            bodyID: undefined
        }
    }

    componentWillReceiveProps(nextProp) {
        if (!Util.isEmpty(nextProp.medData)) {
            this.setState({
                medID: nextProp.medData.medID,
                partID: '',
                saveID: '',
                partDesc: '',
                dataSource: [],
                totalCount: 0,
                bodyID: undefined
            }, () => {
                this.loadBodyParts(1);
                this.loadSelectData();
            })
        }
    }

    componentDidMount() {
        this.props.onRef(this)
        this.initData()
        this.loadSelectData()
        this.loadBodyParts()
    }

    reloadSource() {
        this.setState({
            dataSource: [],
            medID: undefined
        })
    }

    //查询部位信息
    loadBodyParts(page, id) {
        var params = {
            params: [{
                userID: this.state.userData.userID,
                hospID: this.state.userData.hospID,
                logonHospID: this.state.userData.hospID,
                groupID: this.state.userData.groupID,
                medID: !Util.isEmpty(this.props.medData) ? this.props.medData.medID : '',
                searchCode: this.state.bodyInput
            }]
        }
        $http.post('urlDeault', this, {
            code: "03010036",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    this.setState({
                        leftData: res.result.data,
                        checked: false,
                    })
                }
            }
        });
    }

    onKeySelectBodyData(e) {
        if (e.keyCode == '13') {
            this.loadBodyParts()
        }
    }

    loadSelectData() {
        var params = {
            params: [{
                logonHospID: this.state.userData.hospID,
                logonGroupID: this.state.userData.groupID,
                medItemID: !Util.isEmpty(this.props.medData) ? this.props.medData.medID : '',
                bodyFlag: 'Y',
                hospFlag: 'Y'
            }]
        }
        $http.post('urlDeault', this, {
            code: "03010037",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    this.setState({
                        body: res.result.body,
                        hosp: res.result.hosp,
                    })
                }
            }
        });
    }

    initData() {
        this.columns = [
            {
                title: '医院',
                dataIndex: 'hospDesc',
                width: 150,
                align: 'center',
            },
            {
                title: '代码',
                dataIndex: 'itmCode',
                width: 100,
                align: 'center',
            },
            {
                title: '项目',
                dataIndex: 'itmDesc',
                width: 350,
                align: 'center',
            },
            {
                title: '数量',
                dataIndex: 'num',
                width: 80,
                align: 'center',
            },
            {
                title: '单位',
                dataIndex: 'unitDesc',
                width: 120,
                align: 'center',
            },
            {
                title: '单价',
                dataIndex: 'price',
                width: 120,
                align: 'center',
            },
            {
                title: '状态',
                dataIndex: 'status',
                width: 120,
                align: 'center',
            },
            {
                title: '操作',
                dataIndex: '5',
                width: 80,
                align: 'center',
                fixed: 'right',
                render: (text, data) => {
                    return (
                        <span>
                            <Icon type="edit" style={{ color: '#108EE9' }}></Icon>
                            <span className='span' onClick={this.editData.bind(this, data)}>编辑</span>
                        </span >
                    )
                }
            },
        ],
            this.leftColumn = [
                {
                    title: '部位',
                    dataIndex: 'partDesc',
                    width: 80,
                    align: 'center',
                }, {
                    title: '互斥标识',
                    dataIndex: 'mutexFlag',
                    width: 80,
                    align: 'center',
                },
                {
                    title: '操作',
                    dataIndex: 'opertion',
                    width: 80,
                    align: 'center',
                    render: (text, data) => {
                        return <Popconfirm title="删除不可恢复，你确定要删除吗?" onConfirm={this.handleDel.bind(this, data)} >
                            <span className='span' style={{ color: 'rgba(240,65,52,1)' }}>删除</span>
                        </Popconfirm>
                    }
                }
            ],
            this.sunColumns = [
                {
                    title: '医院',
                    dataIndex: 'hospDesc',
                    width: 100,
                    align: 'center',
                },
                {
                    title: '代码',
                    dataIndex: 'itmCode',
                    width: 70,
                    align: 'center',
                },
                {
                    title: '项目及规格',
                    dataIndex: 'itmDesc',
                    width: 120,
                    align: 'center',
                },
                {
                    title: '单价',
                    dataIndex: 'price',
                    width: 50,
                    align: 'center',
                },
            ]
    }

    editData(data) {
        this.setState({
            editStatus: true,
            editData: data,
            endDate: data.endDate ? moment(data.endDate, dayFormat) : ''
        })
    }

    handleDelProject(data) {
        var params = {
            params: [{

            }]
        }
        $http.post('urlDeault', this, {
            code: "03010035",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    message.success('删除成功！')
                    this.loadBodyParts()
                }
            }
        });
    }

    handleDel(data) {
        var params = {
            params: [{
                userID: this.state.userData.userID,
                hospID: this.state.userData.hospID,
                logonHospID: this.state.userData.hospID,
                groupID: this.state.userData.groupID,
                id: data.id
            }]
        }
        $http.post('urlDeault', this, {
            code: "03010035",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    message.success('删除成功！')
                    this.loadBodyParts()
                }
            }
        });
    }

    loadData(page, pageSize, e) {
        var params = {
            params: [{
                medID: !Util.isEmpty(this.props.medData) ? this.props.medData.medID : '',
                partID: this.state.saveID,
                hospID: this.state.hospTabID,
                active: this.state.active
            }],
            pagination: [{
                pageSize: this.state.tabPageSize,
                currentPage: page
            }]

        }
        $http.post('urlDeault', this, {
            code: "05100174",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    this.setState({
                        dataSource: res.data.data,
                        totalCount: res.data.totalCount,
                    })
                }
            }
        });
    }

    //点击行，渲染当前行样式
    onClickRow = (record) => {
        return {
            onClick: () => {
                this.setState({
                    medID: record.medID,
                })
                //将行数据传给父，供其他组件使用
                var { loadCommonMedId } = this.props;
                loadCommonMedId && loadCommonMedId(record)
            },
            onDoubleClick: () => {
                this.loadDetailData(record.medID)
            }
        };
    }

    //点击行，渲染当前行样式 
    setRowClassName = (record) => {
        return record.medID === this.state.medID ? 'clickRowStyle' : '';
    }

    loadDetailData(id) {
        var params = {
            params: [{ medID: id }]
        }
        $http.post('urlDeault', this, {
            code: "02020012",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    var { loadDetailMsg } = this.props;
                    loadDetailMsg && loadDetailMsg(res.result)
                }
            }
        });
    }

    //添加部位
    addBodyParts() {
        var params = {
            params: [{
                partID: this.state.bodyID,
                userID: this.state.userData.userID,
                hospID: this.state.userData.hospID,
                id: this.state.partID,
                logonHospID: this.state.userData.hospID,
                groupID: this.state.userData.groupID,
                medID: this.props.medData ? this.props.medData.medID : '',
                mutexFlag: this.state.checked ? 'Y' : 'N'
            }]
        }
        $http.post('urlDeault', this, {
            code: "03010034",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    message.success('添加成功！')
                    this.setState({
                        partID: undefined
                    }, () => {
                        this.loadBodyParts(1)
                    })
                }
            }
        });
    }

    //点击行，渲染当前行样式
    onClickLeftRow = (record) => {
        return {
            onClick: () => {
                if (record.id == this.state.partID) {
                    this.setState({
                        partID: '',
                        saveID: '',
                        partDesc: ''
                    }, () => {
                        this.loadData(1)
                    })
                } else {
                    this.setState({
                        partID: record.id,
                        saveID: record.partID,
                        partDesc: record.partDesc
                    }, () => {
                        this.loadData(1)
                    })
                }
            },
        };
    }

    //点击行，渲染当前行样式 
    setRowClassName = (record) => {
        return record.id === this.state.partID ? 'clickRowStyle' : '';
    }

    //分页切换
    onChange(e) {
        this.setState({ page: e }, () => {
            this.loadProjectMsg('', e, '');
        });
    }

    //分页切换
    changePageSize(current, pageSize) {
        this.setState({ pageSize: pageSize, page: current }, () => {
            this.loadProjectMsg('', current, pageSize);
        });
    }

    onChangeTable(e) {
        this.setState({ curPage: e }, () => {
            this.loadData('', e, '');
        });
    }

    changeTablePageSize(current, pageSize) {
        this.setState({ tabPageSize: pageSize, curPage: current }, () => {
            this.loadData('', current, pageSize);
        });
    }

    handleSearchClear(value) {
        this.state.dataSource[index] = {}
        this.setState({
            changeValue: value,
        })
    }

    handleSearch(value) {
        if (!Util.isEmpty(this.state.changeValue) && Util.isEmpty(value)) {
            return;
        }
        // if (Util.isEmpty(this.state.hospID)) {
        //     message.error('医院不能为空')
        //     return
        // }
        this.setState({
            changeValue: value,
        }, () => {
            this.loadProjectMsg(value, 1, '')
        })
    }

    //onfocus名称规格展示下拉table
    handleFocusInput(e) {
        this.setState({
            visible: e
        })
    }

    loadProjectMsg(value, page, pageSize) {
        var params = {
            params: [{
                hospID: this.state.hospID || this.state.userData.hospID,
                desc: value ? value : this.state.changeValue
            }],
            pagination: [{
                pageSize: this.state.pageSize,
                currentPage: page
            }]

        }
        $http.post('urlDeault', this, {
            code: "05100168",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    this.setState({
                        selectData: res.data,
                        total: res.total
                    })
                }
            }
        });
    }

    setRowElement = (record, index) => {
        return {
            onDoubleClick: () => {
                this.setState({
                    projectDesc: record.itmDesc,
                    itmHospID: record.itmHospID,
                    itmID: record.itmID,
                    price: record.price,
                    visStatus: false,
                    visible: false
                })
            }
        }
    }

    changeCommonDate(name, e) {
        this.setState({
            [name]: e
        })
    }

    //清空
    clearInput() {
        var date = new Date()
        this.setState({
            hospID: this.state.userData.hospID,
            projectDesc: undefined,
            price: 0,
            itemNum: undefined,
            startDate: moment(date).format(dayFormat),
            endDate: '',
            editData: {},
            editStatus: false
        })
    }

    //保存对应收费项目
    saveProjectList() {
        var { editData } = this.state;
        var date = new Date()
        // if (Util.isEmpty(this.state.hospID) || (this.state.editStatus && Util.isEmpty(editData))) {
        //     message.error('医院不能为空')
        //     return
        // }
        // if (Util.isEmpty(this.state.projectDesc) || (this.state.editStatus && Util.isEmpty(editData))) {
        //     message.error('项目及规格不能为空')
        //     return
        // }
        // if (Util.isEmpty(this.state.startDate) || (this.state.editStatus && Util.isEmpty(editData))) {
        //     message.error('生效日期不能为空')
        //     return
        // }
        var params = {
            params: [{
                medID: !Util.isEmpty(this.props.medData) ? this.props.medData.medID : '',
                itmHospID: this.state.itmHospID ? this.state.itmHospID : (editData ? editData.itmHospID : ''),
                partID: this.state.saveID,
                medPartLinkItmID: editData ? editData.medPartLinkItmID : '',
                num: this.state.itemNum ? this.state.itemNum : (editData ? editData.num : ''),
                stDate: this.state.startDate ? moment(this.state.startDate).format(dayFormat) :
                    (editData ? moment(editData.stDate).format(dayFormat) : moment(date).format(dayFormat)),
                endDate: this.state.endDate ? moment(this.state.endDate).format(dayFormat) : '',
                updateUserID: this.state.userData.userID,
            }]
        }
        $http.post('urlDeault', this, {
            code: this.state.editStatus ? '05100176' : "05100175",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    message.success('保存成功！')
                    this.loadData(1)
                    this.clearInput()
                }
            }
        });
    }

    handleSelectChange(name, e) {
        this.setState({
            [name]: e
        }, () => {
            this.loadData(1)
        })
    }

    changeCheckBox(name, e) {
        this.setState({
            [name]: e.target.checked ? 'Y' : 'N'
        }, () => {
            this.loadData(1)
        })
    }

    changeCommonChcekBox(name, e) {
        this.setState({
            [name]: e.target.checked
        })
    }

    disabledDate(current) {
        return current && current < moment().startOf('day');
    }

    render() {
        var { subCat, status, bodyID } = this.state;
        var date = new Date()
        //医嘱子类
        var subCatOption = [];
        subCat && subCat.map((item, index) => {
            subCatOption.push(<Option key={index} value={item.id}>{item.descripts}</Option>)
        })

        var statusOption = [];
        status && status.map((item, index) => {
            statusOption.push(<Option key={index} value={item.id}>{item.descripts}</Option>)
        })

        //部位
        var bodyOption = []
        this.state.body && this.state.body.map((item, index) => {
            bodyOption.push(<Option key={index} value={item.id} code={item.descriptsSPCode} name={item.descripts}>{item.descripts}</Option>)
        })

        //医院
        var hospOption = []
        this.state.hosp && this.state.hosp.map((item, index) => {
            hospOption.push(<Option key={index} value={item.id} code={item.descriptsSPCode}>{item.descripts}</Option>)
        })

        return <div className='common-order-list-body'>
            <Card style={{ float: 'left', width: '30%', minHeight: 500 }} title='添加部位'>
                {/* <div> */}
                <div style={{ display: 'flex' }}>
                    <div>
                        <Select
                            style={{ width: 180 }}
                            placeholder='请选择部位'
                            allowClear
                            showSearch
                            filterOption={(input, option) =>
                                option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                || option.props.code.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                || option.props.name.toLowerCase().indexOf(input.toLowerCase()) >= 0
                            }
                            value={bodyID}
                            onChange={Util.handleSelectChange.bind(this, 'bodyID')}
                        >
                            {bodyOption}
                        </Select>
                    </div>
                    <Button type='primary' style={{ marginLeft: 5 }} onClick={this.addBodyParts.bind(this)}>{!Util.isEmpty(this.state.partID) ? '修改' : '加入'}</Button>
                </div>
                <Input placeholder='输入部位名称enter查询' style={{ width: 180, marginTop: 5 }}
                    onKeyDown={this.onKeySelectBodyData.bind(this)}
                    onChange={Util.commonInputChange.bind(this, 'bodyInput')} /><br />
                互斥：<Checkbox style={{ marginTop: 5 }} checked={this.state.checked} onChange={this.changeCommonChcekBox.bind(this, 'checked')} />
                <Table
                    columns={this.leftColumn}
                    dataSource={this.state.leftData}
                    loadData={this.loadBodyParts.bind(this)}
                    onRow={this.onClickLeftRow}
                    rowClassName={this.setRowClassName}
                    rowKey={(data) => {
                        return data.id
                    }}
                    pagination={false}
                />
            </Card>
            <Card style={{ float: 'right', width: '69.8%', height: store.getState().tableHeight.y + 70 + 'px', }} title={<span>设置当前部位对应费用（已选部位：{this.state.partDesc || '--'})</span>}>
                <span>
                    <span>添加收费项目</span>
                    <span>（说明：如果部位设置了关联费用，则按照部位收取费用）</span>
                </span>
                <div style={{ marginTop: 5 }}>
                    <span><span style={{ color: '#f5222d', fontFamily: 'SimSun' }}>*</span>
                        医院：</span><Select placeholder='请选择医院' showSearch allowClear style={{ width: 180 }}
                            disabled={this.state.editStatus ? true : false}
                            value={this.state.hospID ? this.state.hospID : (this.state.editData ? this.state.editData.hospID : this.state.userData.hospID)}
                            onChange={Util.handleSelectChange.bind(this, 'hospID')}
                            filterOption={(input, option) =>
                                option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                || option.props.code.toLowerCase().indexOf(input.toLowerCase()) >= 0
                            }>{hospOption}</Select>

                    <span style={{ marginLeft: 10 }}><span style={{ color: '#f5222d', fontFamily: 'SimSun' }}>*</span>
                        项目及规格：</span><Select style={{ width: 220 }}
                            disabled={this.state.editStatus ? true : false}
                            getPopupContainer={triggerNode => triggerNode.parentNode}
                            showSearch={true} allowClear={true} defaultActiveFirstOption={false}
                            showArrow={false}
                            value={this.state.projectDesc ? this.state.projectDesc : (this.state.editData ? this.state.editData.itmDesc : undefined)}
                            filterOption={false} autoFocus
                            onSearch={this.handleSearch.bind(this)}
                            onChange={this.handleSearchClear.bind(this)}
                            onDropdownVisibleChange={this.handleFocusInput.bind(this)}
                            dropdownRender={(menuNode, props) => {
                                return (
                                    <div
                                        onMouseLeave={() => {
                                            this.setState({
                                                visStatus: false,
                                            })
                                        }}
                                        onMouseEnter={() => { this.setState({ visStatus: true }) }}
                                    >
                                        <Table
                                            dataSource={this.state.selectData}
                                            rowKey={(record) => record.itmID}
                                            columns={this.sunColumns}
                                            bordered
                                            pagination={false}
                                            rowClassName={(data, index) => {
                                                return index == this.state.newIndex ? 'rowClass' : ''
                                            }}
                                            onRow={this.setRowElement}></Table>
                                        <Pagination
                                            size="small"
                                            showQuickJumper
                                            showSizeChanger
                                            defaultCurrent={1}
                                            current={this.state.page}
                                            total={this.state.total}
                                            onShowSizeChange={this.changePageSize.bind(this)}
                                            onChange={this.onChange.bind(this)}
                                            style={{ textAlign: "right", marginTop: '13px' }}
                                        />
                                    </div>
                                );
                            }}
                            dropdownMatchSelectWidth={false}
                            dropdownStyle={{ width: '330px', height: 300, overflow: 'auto' }}
                            open={((this.state.visible || this.state.visStatus)) ? true : false}></Select><br />

                    <div style={{ marginTop: 5 }}>
                        <span style={{ marginLeft: 10 }}> 单价：</span><Input prefix='¥' style={{ width: 80 }} disabled={true}
                            value={this.state.price ? this.state.price : (this.state.editData ? this.state.editData.price : 0)} />
                        <span style={{ marginLeft: 10 }}>数量：</span> <Input style={{ width: 80 }}
                            value={this.state.itemNum ? this.state.itemNum : (this.state.editData ? this.state.editData.num : undefined)}
                            disabled={this.state.editStatus ? true : false}
                            onChange={Util.commonInputChange.bind(this, 'itemNum')} />
                        <span style={{ marginLeft: 10 }}><span style={{ color: '#f5222d', fontFamily: 'SimSun' }}>*</span>
                            生效日期：</span><DatePicker onChange={this.changeCommonDate.bind(this, 'startDate')}
                                value={this.state.startDate ? moment(this.state.startDate, dayFormat) :
                                    (this.state.editData ? moment(this.state.editData.stDate, dayFormat) : (moment(date, dayFormat)))}
                                disabled={this.state.editStatus ? true : false} /></div>
                    <div style={{ marginTop: 5 }}>
                        <span style={{ marginLeft: 10 }}>失效日期：</span>
                        <DatePicker onChange={this.changeCommonDate.bind(this, 'endDate')}
                            // disabledDate={this.disabledDate}
                            // value={this.state.endDate ? this.state.endDate : (this.state.editData ?
                            //     (this.state.editData.endDate ? moment(this.state.editData.endDate, dayFormat) : '') : '')} 
                            value={this.state.endDate}
                        />
                        <Button style={{ marginLeft: 10 }} onClick={this.clearInput.bind(this)}>清空</Button>
                        <Button type='primary' style={{ marginLeft: 10 }} onClick={this.saveProjectList.bind(this)}>保存</Button></div>
                </div>
                <div style={{ background: 'rgba(228, 228, 228, 1)', height: '32px', lineHeight: '32px', fontWeight: '700', marginTop: 5 }}>
                    已对应收费项目列表
                    <span style={{ float: 'right', fontWeight: '100' }}>
                        <Select placeholder='请选择医院' showSearch allowClear style={{ width: 180 }}
                            onChange={this.handleSelectChange.bind(this, 'hospTabID')}
                            filterOption={(input, option) =>
                                option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                || option.props.code.toLowerCase().indexOf(input.toLowerCase()) >= 0
                            }>{hospOption}</Select>
                        <Checkbox style={{ fontSize: '12px', color: '#000' }} onChange={this.changeCheckBox.bind(this, 'active')}>仅显示生效</Checkbox>
                    </span>
                    <Table
                        columns={this.columns}
                        dataSource={this.state.dataSource}
                        style={{ marginTop: 10 }}
                        loadData={this.loadData.bind(this)}
                        onRow={this.onClickRow}
                        scroll={{ y: 300, x: 800 }}
                        rowClassName={this.setRowClassName}
                        bordered
                        rowKey={(data) => {
                            return data.medID
                        }}
                        pagination={false}>
                    </Table>
                    <Pagination
                        size="small"
                        showQuickJumper
                        showSizeChanger
                        defaultCurrent={1}
                        current={this.state.curPage}
                        total={this.state.totalCount}
                        onShowSizeChange={this.changeTablePageSize.bind(this)}
                        onChange={this.onChangeTable.bind(this)}
                        style={{ textAlign: "right", marginTop: '13px' }}
                    />
                </div>
            </Card>
        </div>
    }
}

export default CheckBodyPartsTabPane;