// 关联收费项
import React from 'react';
import { Form, Input, Select, Button, DatePicker, Row, Icon, Checkbox, message } from 'antd';
import { $http } from 'containers/config/https';
import '../style/childStyle.less';
import Moment from 'moment';
import PubilcTablePagination from 'pages/common/PubilcTablePagination.jsx';
import PublicModalTable from 'pages/common/PublicModalTable';

const { Option } = Select;

class OLAssociatedCharges extends React.Component {
    constructor() {
        super();
        var userData = JSON.parse(sessionStorage.getItem('userData'));
        this.state = {
            rowData: {},
            hosp: undefined, // 医院
            status: true, // 是否生效
            total: 0,
            page: 1,
            pageSize: 10,
            tableData: [], // 列表数据
            user: userData,
            selectData: {}, // 下拉框数据
            top: '',
            left: '',
            modalData: [], // 项目及规格列表数据
            modalPageSize: 10,
            modalPage: 1,
            modalTotal: 0,
            ModalRowData: {}, // 项目及规格列表选中行数据
            medID: '',
            loading: false,
            priceSum: ''
        };
        this.columns = [
            {
                key: 1,
                title: '医院',
                dataIndex: 'hospDesc',
                align: "center",
                width: '150px'
            },
            {
                key: 3,
                title: '代码',
                dataIndex: 'itmCode',
                align: "center",
                width: '80px',
            },
            {
                key: 5,
                title: '项目',
                dataIndex: 'itmDesc',
                align: "center",
                width: '150px',
            },
            {
                key: 6,
                title: '数量',
                dataIndex: 'num',
                align: "center",
                width: '100px',
            },
            {
                key: 7,
                title: '计价单位',
                dataIndex: 'unitDesc',
                align: "center",
                width: '80px',
            },
            {
                key: 8,
                title: '单价',
                dataIndex: 'price',
                align: "center",
                width: '80px',
            },
            {
                key: 9,
                title: '状态',
                dataIndex: 'status',
                align: "center",
                width: '80px',
            },
            {
                title: '操作',
                key: 10,
                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>
                ),
            }
        ];
        this.modalColumns = [
            // {
            //     key: 1,
            //     title: '医院名称',
            //     dataIndex: 'hospDesc',
            //     align: "center",
            // },
            {
                key: 2,
                title: '收费项代码',
                dataIndex: 'itmCode',
                align: "center",
            },
            {
                key: 5,
                title: '收费项名称',
                dataIndex: 'itmDesc',
                align: "center",
            },
            {
                key: 3,
                title: '单位',
                dataIndex: 'unitDesc',
                align: "center",
            },
            {
                key: 6,
                title: '价格',
                dataIndex: 'price',
                align: "center",
            },
        ]
    }

    componentDidMount() {
        this.getSelectData();
        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
    }

    modalOnRef = (ref) => {
        this.modalChild = ref
    }

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

    // 请求列表数据
    getTableData() {
        this.setState({ loading: true });
        let { page, pageSize, status, hosp, medID } = this.state;
        let data = {
            params: [{
                medID, // 医嘱项id
                active: status ? 'Y' : 'N', // 状态
                hospID: hosp, // 医院
            }],
            pagination: [{
                pageSize: pageSize,
                currentPage: page,
                sortColumn: "Describe",
                sortOrder: "asc"
            }]
        }
        $http.post('urlS', this, {
            code: "05100170",
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    for (var i = 0; i < res.data.length; i++) {
                        res.data[i].key = i
                    }
                    this.setState({ tableData: res.data, total: res.total, loading: false, priceSum: res.priceSum }, () => {
                        // 数据加载成功关闭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();
        })
    }

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

    // 删除
    handleDelete = record => {
        console.log(record)
    }

    // 保存
    handleSave = () => {
        const { form: { validateFields } } = this.props;
        let { rowData, user, ModalRowData, medID } = this.state;
        validateFields((errors, values) => {
            if (errors === null) {
                let data = {
                    params: []
                };
                let obj = JSON.parse(JSON.stringify(values));
                obj.updateUserID = user.userID;
                obj.medID = medID; // 医嘱项id
                obj.stDate = obj.stDate ? Moment(obj.stDate).format("YYYY-MM-DD") : '';
                obj.endDate = obj.endDate ? Moment(obj.endDate).format("YYYY-MM-DD") : '';
                obj.itmHospID = ModalRowData && ModalRowData.itmHospID ? ModalRowData.itmHospID : (rowData.itmHospID ? rowData.itmHospID : '');
                obj.medLinkItmID = rowData && rowData.medLinkItmID ? rowData.medLinkItmID : '';
                data.params.push(obj);
                $http.post('urlADS', this, {
                    code: rowData && rowData.medLinkItmID ? '05100172' : '05100171',
                    data: data,
                    success: function (res) {
                        if (+res.errorCode === 0) {
                            message.success(rowData && rowData.medLinkItmID ? '编辑成功' : '新增成功');
                            this.handleQuery();
                            this.resetFields();
                        }
                    }
                })
            }
        })
    }

    // 项目及规格回车事件
    itmHospOnPressEnter = (e) => {
        let top = document.getElementById('item-hosp').getBoundingClientRect().top + 40 + 'px';
        let left = document.getElementById('item-hosp').getBoundingClientRect().left + 96 + 'px';
        this.setState({
            top,
            left
        });
        this.getModalListData(e.target.value);
        this.modalChild.showModal();
    }

    handleCompilePage = (page, pageSize) => {
        this.setState({ modalPageSize: pageSize, modalPage: page }, () => {
            let values = this.props.form.getFieldValue("itmHosp")
            this.getModalListData(values);
        })
    }

    // 获取描述列表数据
    getModalListData(alias) {
        let { modalPageSize, modalPage } = this.state;
        let hospID = this.props.form.getFieldValue("hospID")
        let data = {
            params: [
                {
                    desc: alias, // 收费项名称
                    hospID, // 医院
                }
            ],
            pagination: [{
                pageSize: modalPageSize,
                currentPage: modalPage,
                sortColumn: "Describe",
                sortOrder: "asc"
            }]
        }
        $http.post('urlS', this, {
            code: "05100168",
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    for (var i = 0; i < res.data.length; i++) {
                        res.data[i].key = i + 1
                    }
                    this.setState({ modalData: res.data, modalTotal: res.total })
                } else {
                    this.setState({ modalData: [], modalTotal: 0 })
                }
            }
        })
    }

    // 操作弹框
    onClickRowPublic = (record) => {
        return {
            onDoubleClick: () => {
                this.confirmSelection(record);
            }
        }
    }

    // 双击选中行数据的回调
    confirmSelection = (record) => {
        this.setState({ ModalRowData: record }, () => {
            // 关闭弹窗
            this.modalChild.handleCancel();
            this.props.form.setFieldsValue({ itmHosp: record.itmDesc, price: record.price });
        })
    }

    // 当描述失去焦点的时候
    itmHospOnBlure = (e) => {
        if (this.state.ModalRowData && (e.target.value !== this.state.ModalRowData.itmDesc)) {
            this.props.form.setFieldsValue({ itmHosp: undefined, price: undefined });
            this.setState({ ModalRowData: {} })
        }
    }

    // 重置
    resetFields = () => {
        this.props.form.resetFields(); //清空所有
        this.setState({
            rowData: {},
            ModalRowData: {}
        })
    }

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

    // 选中行操作 --- 发药列表
    setRowClassNamePublic = (record) => {
        // 0-正常，1-医院收费项失效，2-主收费项失效
        return +record.stopFlag !== 0 ? 'associated-failure-state' : ''
    }

    render() {
        let { rowData, status, selectData, hosp, modalTotal, modalPage, loading, priceSum } = this.state;
        const { getFieldDecorator } = this.props.form;
        // 组件所需参数
        const param = {
            // 表头配置
            columns: this.columns,
            // 表格数据
            data: this.state.tableData,
            // 数据总条数
            total: this.state.total,
            // 当前页数
            page: this.state.page,
            // 表格的宽度
            x: 900,
            y: 360,
            TableClassName: "otherName",
            height: '400px',
            loading
        };
        const modalParam = {
            width: '600px',
            total: modalTotal,
            page: modalPage,
            top: this.state.top,
            left: this.state.left,
            columns: this.modalColumns,
            data: this.state.modalData,
            isOnRow: true,
            showPagination: true,
        }

        // 医院
        let hospOption = selectData.hosp && selectData.hosp.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>
                        <span style={{ background: 'rgba(228, 228, 228, 1)', height: '32px', lineHeight: '32px', fontWeight: '700', color: '#157EDF' }}>{priceSum}</span>
                    </div>
                    <div>
                        <Form>
                            <Row>
                                <Form.Item label="医院：">
                                    {getFieldDecorator('hospID', {
                                        initialValue: rowData.hospID ? rowData.hospID : undefined,
                                        rules: [{ required: true, message: '医院不能为空' }]
                                    })(
                                        <Select disabled={rowData && rowData.medLinkItmID ? true : false} showSearch optionFilterProp="seatchprop" allowClear style={{ width: '200px', marginRight: '8px' }} placeholder="请选择">
                                            {hospOption}
                                        </Select>
                                    )}
                                </Form.Item>
                                <span id="item-hosp">
                                    <Form.Item label="项目及规格：">
                                        {getFieldDecorator('itmHosp', {
                                            initialValue: rowData.itmDesc ? rowData.itmDesc : undefined,
                                            rules: [{ required: true, message: '项目及规格不能为空' }]
                                        })(
                                            <Input disabled={rowData && rowData.medLinkItmID ? true : false} placeholder="回车检索药品相关信息" onPressEnter={this.itmHospOnPressEnter} style={{ width: '200px', marginRight: '8px' }} />
                                        )}
                                    </Form.Item>
                                </span>
                                <Form.Item label="单价：">
                                    {getFieldDecorator('price', {
                                        initialValue: rowData.price ? rowData.price : undefined,
                                    })(
                                        <Input type="number" className="input-number" style={{ width: '70px' }} placeholder="￥--" disabled />
                                    )}
                                </Form.Item>
                            </Row>
                            <Row>
                                <Form.Item label="数量：">
                                    {getFieldDecorator('num', {
                                        initialValue: rowData.num ? rowData.num : undefined,
                                        // rules: [{ required: true, message: '数量不能为空' },{ pattern: /^[1-9]\d*$/, message: '数量只能为正整数, 如1、2、3、4' }]
                                        rules: [{ required: true, message: '数量不能为空' }]
                                    })(
                                        <Input disabled={rowData && rowData.medLinkItmID ? true : false} type="number" className="input-number" style={{ width: '70px', marginRight: '8px' }} placeholder="请输入" />
                                    )}
                                </Form.Item>
                                <Form.Item label="生效日期：">
                                    {getFieldDecorator('stDate', {
                                        initialValue: rowData.stDate ? Moment(rowData.stDate) : undefined,
                                        rules: [{ required: true, message: '生效日期不能为空' }]
                                    })(
                                        <DatePicker disabled={rowData && rowData.medLinkItmID ? true : false} style={{ width: '150px', marginRight: '8px' }} format="YYYY-MM-DD" allowClear />
                                    )}
                                </Form.Item>
                                <Form.Item label="失效日期：">
                                    {getFieldDecorator('endDate', {
                                        initialValue: rowData.endDate ? Moment(rowData.endDate) : undefined,
                                    })(
                                        <DatePicker
                                            // disabledDate={this.disabledDate} 
                                            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 className="olac-notes">
                            注释：<i></i>
                            医院收费项或主收费项失效
                        </span>
                        <span style={{ float: 'right', fontWeight: '100' }}>
                            <Select value={hosp} onChange={this.handleHospID} 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}
                        setRowClassNamePublic={this.setRowClassNamePublic}
                    />
                </div>
                <PublicModalTable
                    onClickRowPublic={this.onClickRowPublic}
                    param={modalParam}
                    onRef={this.modalOnRef}
                    compilePage={this.handleCompilePage}
                />
            </div>
        )
    }
};
const OLAssociatedChargesForm = Form.create()(OLAssociatedCharges);
export default OLAssociatedChargesForm;