/*
 * Creator:     ML
 * CreatDate:   2020-02-25
 * descripts：  互斥医嘱
 * */
import React from 'react';
import { Form, Input, Select, Button, message, Row, Icon, Divider, Popconfirm, DatePicker, Col } from 'antd';
import { $http } from 'containers/config/https';
import moment from 'moment';
import '../style/childStyle.less';
import PubilcTablePagination from 'pages/common/PubilcTablePagination.jsx';
import PublicModalTable from 'pages/common/PublicModalTable';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';

const { Option } = Select;

class MutuallyExclusiveOrdersForm extends React.Component {
    constructor() {
        super();
        var userData = JSON.parse(sessionStorage.getItem('userData'));
        this.state = {
            allergens: [],
            selectData: {}, // 下拉框数据
            tableData: [], // 列表数据
            total: 0,
            page: 1,
            pageSize: 10,
            modalPageSize: 10,
            modalPage: 1,
            rowData: {}, // 编辑回显数据
            user: userData,
            medID: '',
        };
        this.modalColumns = [
            {
                key: 1,
                title: '医嘱项代码',
                dataIndex: 'code',
                align: "center",
            },
            {
                key: 2,
                title: '医嘱项名称',
                dataIndex: 'descripts',
                align: "center",
            },
        ]
    }

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

    componentWillReceiveProps(nextProps) {
        if ((nextProps.medData && nextProps.medData.medID ? nextProps.medData.medID : '') !== this.state.medID) {
            this.setState({ medID: nextProps.medData.medID }, () => {
                this.handleQuery();
                this.resetFields();
            })
        }
    }
     //动态表头
     onColumnRef = (ref) => {
        this.columnRef = ref;
    }
    // 获取主列表columns
    getMainTableColumns = () => {
        let data = {
            params: [{
                compontName: "MutualDoctorOrderDataMaintenan",
                reactCode: ['MutualDoctorOrderDataMaintenan'],
                type: 'C',
            }]
        }
        $http.post('urlS', this, {
            code: '01040073',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    let arr = res.result && res.result.C.length > 0 ? JSON.parse(JSON.stringify(res.result.C)).map(item => {
                        return {
                            align: item.align,
                            widthNum: parseInt(item.width),
                            width: item.width,
                            dataIndex: item.dataIndex,
                            title: <div onDoubleClick={() => this.columnRef.onOpenModel()}>{item.title}</div>,
                            display: item.display,
                            key: item.seqNo,
                        }
                    }) : '';
                    let filterArr = arr.filter(function (item) { return item.display === 'Y' });
                    let seq = {
                        key: 1,
                        title: '序号',
                        dataIndex: 'key',
                        align: "center",
                        width: 50,
                        render: (text, record, index) => {
                            return this.state.tableData.findIndex((value, index) => {
                                return value === record;
                            }) + 1;
                        }
                    }
                    let seqArr = {
                        title: '操作',
                        key: 7,
                        align: "center",
                        width: 130,
                        display: "Y",
                        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>
                        ),
                    }
                    filterArr.push(seqArr)
                    filterArr.unshift(seq)
                    this.setState({ columns: filterArr, widthTotal: res.totalWidth })
                    // console.log("res.totalWidth",res.totalWidth)
                }
            }
        })
    }

    // 调用子组件的连接事件
    onRef = (ref) => {
        this.child = ref
    }
    // 请求列表数据
    getTableData() {
        let { page, pageSize, medID } = this.state;
        let data = {
            params: [{
                medItemID: medID // 医嘱项id
            }],
            pagination: [{
                pageSize: pageSize,
                currentPage: page,
                sortColumn: "Describe",
                sortOrder: "asc"
            }]
        }
        $http.post('urlS', this, {
            code: "03050260",
            data: data,
            success: function (res) {
                if (+res.errorCode == 0 && res.result) {
                    this.setState({ tableData: res.result.data, total: res.result.TotalCount }, () => {
                        // 数据加载成功关闭loading
                        this.child.handleLoading();
                    })
                } else {
                    this.setState({ tableData: [], total: 0 }, () => {
                        // 数据加载成功关闭loading
                        this.child.handleLoading();
                    })
                }
            },
            error: function () {
                this.setState({ tableData: [], total: 0 }, () => {
                    // 数据加载成功关闭loading
                    this.child.handleLoading();
                })
            }
        })
    }

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


    // 保存
    handleSave = () => {
        const { rowData, user, exclMedItemID, medID } = this.state;
        this.props.form.validateFields((errors, values) => {
            if (errors) {
                return;
            }
            if (exclMedItemID == "") {
                message.warning("请回车检索医嘱项")
                return
            }
            if (exclMedItemID == medID) {
                message.warning("互斥医嘱项不能相同")
                return
            }
            let data = {
                params: []
            };

            let obj = {};
            obj.ID = rowData.ID || "";
            obj.medItemID = medID;
            obj.exclMedItemID = exclMedItemID; // 医嘱项id
            obj.note = values.note || '';;
            obj.startDate = values.startDate ? moment(values.startDate).format("YYYY-MM-DD") : '';
            obj.stopDate = values.stopDate ? moment(values.stopDate).format("YYYY-MM-DD") : '';
            obj.updateUserID = user.userID ? user.userID : '';
            obj.createUserID = user.userID ? user.userID : '';
            data.params.push(obj);
            $http.post('urlADS', this, {
                code: '03050191',
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        if (rowData.ID) {
                            message.success('编辑成功');
                            this.handleQuery();
                            this.resetFields();
                        } else {
                            message.success('新增成功');
                            this.handleQuery();
                            this.resetFields();
                        }
                    }
                }
            })
        })
    }

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

    // 编辑
    handleCompile = record => {
        this.resetFields();
        this.setState({ rowData: record, exclMedItemID: record.exclMedItemID,excTitle:record.exclMedItem,noteTitle:record.note });
    }

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

    }
    modalOnRef = (ref) => {
        this.modalChild = ref
    }
    // 相斥医嘱回车事件
    itmOnPressEnter = (e) => {
        let top = document.getElementById('item-id').getBoundingClientRect().top + 40 + 'px';
        let left = document.getElementById('item-id').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("medItemID")
            this.getModalListData(values);
        })
    }

    // 获取描述列表数据
    getModalListData(alias) {
        let { modalPageSize, modalPage, pageSize, page } = this.state;
        let medItemID = this.props.form.getFieldValue("medItemID")
        let data = {
            params: [
                {
                    inputValue: medItemID, // 医嘱
                }
            ],
            pagination: [{
                pageSize: modalPageSize,
                currentPage: modalPage,
                sortColumn: "Describe",
                sortOrder: "asc"
            }]
        }
        $http.post('urlS', this, {
            code: "04150017",
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    for (var i = 0; i < res.result.Data.length; i++) {
                        res.result.Data[i].key = i + 1
                    }
                    this.setState({ modalData: res.result.Data, modalTotal: res.result.TotalCount })
                } 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({ medItemID: record.descripts, });
            this.setState({
                exclMedItemID: record.id,
                excTitle:record.descripts,
            })
        })
    }

    // 当描述失去焦点的时候
    itmHospOnBlure = (e) => {
        // console.log(e.target.value,"----",this.state.ModalRowData )
        if (this.state.ModalRowData && (e.target.value !== this.state.ModalRowData.descripts)) {
            this.props.form.setFieldsValue({ medItemID: undefined, });
            this.setState({ ModalRowData: {} })
        }
    }
    changeValue = (e) => {
        if (e.target.value == "") {
            this.setState({
                exclMedItemID: "",
                excTitle:"",
                noteTitle:""
            })
        }
    }
    render() {
        const { tableData, total, page, rowData, modalTotal, modalPage, excTitle,noteTitle} = this.state;

        const { getFieldDecorator } = this.props.form;
        // 组件所需参数
        const param = {
            // 表头配置
            columns: this.state.columns,
            // 表格数据
            data: tableData,
            // 数据总条数
            total: total,
            // 当前页数
            page: page,
            // 表格的宽度
            x: 900,
            y: 360,
            TableClassName: "medAll",
            height: '400px'
        };
        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,
        }
        const formLayout = {
            labelCol: { span: 10 },
            wrapperCol: { span: 14 },
        }
        const formLayoutItem = {
            labelCol: { span: 9 },
            wrapperCol: { span: 13 },
        }
        return (
            <div>
                <Form layout={'horizontal'}>
                    <Row>
                        <Col span={5}>
                            <span id="item-id">
                                <Form.Item label="相斥医嘱" {...formLayoutItem}>
                                    {getFieldDecorator('medItemID', {
                                        initialValue: rowData.exclMedItem ? rowData.exclMedItem : undefined,
                                        rules: [{ required: true, message: '相斥医嘱不能为空' }]
                                    })(
                                        <Input title={excTitle||""} disabled={rowData && rowData.ID ? true : false} placeholder="回车检索医嘱相关信息" onChange={(e, ) => this.changeValue(e)} onPressEnter={this.itmOnPressEnter} style={{ width: "170px" }} />
                                    )}
                                </Form.Item>
                            </span>
                        </Col>
                        <Col span={5}>
                            <Form.Item label="备注" {...formLayout}>
                                {getFieldDecorator('note', {
                                    initialValue: rowData.note ? rowData.note : undefined,
                                    rules: [{ required: false, message: '' }]
                                })(
                                    <Input title={noteTitle||""}></Input>
                                )}
                            </Form.Item>
                        </Col>
                        <Col span={5}>
                            <Form.Item label='生效日期' {...formLayout}>
                                {getFieldDecorator('startDate', {
                                    initialValue: rowData && rowData.startDate ? moment(rowData.startDate, "YYYY-MM-DD") : moment(),
                                    rules: [{ required: true, message: '请选择生效日期' }],
                                })(
                                    <DatePicker style={{ width: '100%' }} placeholder={'请选择生效日期'} disabledDate={(curDate) => {
                                        return curDate && curDate > moment().endOf('day');
                                    }} />
                                )}
                            </Form.Item>
                        </Col>
                        <Col span={5}>
                            <Form.Item label='失效日期' {...formLayout}>
                                {getFieldDecorator('stopDate', {
                                    initialValue: rowData && rowData.stopDate ? moment(rowData.stopDate, "YYYY-MM-DD") : undefined,
                                    rules: [{ required: false, message: '' }],
                                })(
                                    <DatePicker style={{ width: '100%' }} disabledDate={(curDate) => {
                                        return curDate && curDate < moment().startOf('day');
                                    }} />
                                )}
                            </Form.Item>
                        </Col>
                        <Col span={4}>
                            <Button style={{ margin: '3px 10px 0 10px' }} type="primary" onClick={this.handleSave}>{rowData.linkID ? '修改' : '保存'}</Button>
                            <span style={{ display: 'inline-block', marginTop: '4px' }}>
                                <Button onClick={this.resetFields}>清空</Button>
                            </span>
                        </Col>
                    </Row>
                </Form>
                <div>
                    <PubilcTablePagination param={param} handelThis={this} onRef={this.onRef} />
                </div>
                <PublicModalTable
                    onClickRowPublic={this.onClickRowPublic}
                    param={modalParam}
                    onRef={this.modalOnRef}
                    compilePage={this.handleCompilePage}
                />
                <ColumnAuthoritysModel
                    clientWidth='800px'
                    compontName='MutualDoctorOrderDataMaintenan'
                    configType="C"
                    onRef={this.onColumnRef}
                    reloadData={this.getMainTableColumns}
                />
            </div>
        )
    }
};
const MutuallyExclusiveOrders = Form.create()(MutuallyExclusiveOrdersForm);
export default MutuallyExclusiveOrders;