/*
 * Creator:     ML
 * CreatDate:   2020-02-28
 * descripts：  抗菌药物 tabs  抗菌药物用量维护
 * */
import React from 'react';
import {Form, message, Select, Button, DatePicker, Row, Switch, Checkbox, Icon, Divider, Popconfirm,Input} from 'antd';
import { $http } from 'containers/config/https';
import Moment from 'moment';
import store from 'store';
import PubilcTablePagination from 'pages/common/PubilcTablePagination.jsx';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';
import PublicModalTable from 'pages/common/PublicModalTable';
import '../style/childStyle.less';
const { Option } = Select;

class AntibacterialTabDosages extends React.Component {
    constructor() {
        super();
        var userData = JSON.parse(sessionStorage.getItem('userData'))
        this.state = {
            userData: userData,
            selectData: {}, // 下拉框数据
            hosp: undefined, // 医院
            status: true, // 仅显示生效
            tableData: [], // 列表数据
            total: 0,
            page: 1,
            pageSize: 10,
            rowData: {}, // 编辑回显数据
            user: userData,
            medID: '',
            locData: [], // 科室下拉数据
            loading: false
        };
        this.modalColumns = [
            {
                key: 1,
                title: '医嘱项代码',
                dataIndex: 'code',
                align: "center",
            },
            {
                key: 2,
                title: '医嘱项名称',
                dataIndex: 'descripts',
                align: "center",
            },
        ]
    }

    componentDidMount() {
        this.getSelectData();
        this.getAllSelectData();
        this.getMainTableColumns();
        if ((this.props.medData && this.props.medData.medItemID ? this.props.medData.medItemID : '') !== this.state.medID) {
            this.setState({ medID: this.props.medData.medItemID }, () => {
                this.handleQuery();
            })
        } else {
            this.child.handleLoading();
        }
    }

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


    // 调用子组件的连接事件
    onRef = (ref) => {
        this.child = ref
    }
    //动态表头
    onColumnRef = (ref) => {
        this.columnRef = ref;
    }
    // 获取主列表columns
    getMainTableColumns = () => {
        let data = {
            params: [{
                compontName: "AntibactDoseQty",
                reactCode: ['AntibactDoseQty'],
                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 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)
                    this.setState({ columns: filterArr, widthTotal: res.totalWidth })
                    // console.log("res.totalWidth",res.totalWidth)
                }
            }
        })
    }

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

    // 获取方式下拉框数据
    getAllSelectData = () => {
        let { user, medID } = this.state;
        let data = {
            params: [{
                patCatFlag: "Y",
                unitFlag:"Y",
            }]
        }
        $http.post('urlS', this, {
            code: "03050212",
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    this.setState({ unitData: res.result.unit,patCatData: res.result.patCat })
                }
            }
        })
    }

    // 请求列表数据
    getTableData() {
        this.setState({ loading: true });
        let { page, pageSize, status, hosp, user, medID } = this.state;
        let data = {
            params: [{
                medItemID: medID || "", // 医嘱项id
            }],
            pagination: [{
                pageSize: pageSize,
                currentPage: page,
                sortColumn: "Describe",
                sortOrder: "asc"
            }]
        }
        $http.post('urlS', this, {
            code: "03050208",
            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, exclMedItemID } = this.state;
        if(!this.state.medID){
            message.warning("请先选中左侧抗菌药物")
            return
        }
        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.note = obj.note;
                obj.medItemID = medID; // 医嘱项id
                obj.doseQtyFrom = obj.doseQtyFrom;
                obj.doseQtyTo = obj.doseQtyTo;
                obj.freqTimesFrom = obj.freqTimesFrom;
                obj.freqTimesTo = obj.freqTimesTo;
                
                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: '03050209',
                    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: {},
            rowID:""
        })
    }

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

    // 删除
    handleDelete = record => {
        let { user } = this.state;
        let data = {
            params: [{
                ID: record.ID,
                updateUserID: user.userID,
            }]
        }
        $http.post('urlADS', this, {
            code: '03050210',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    message.success('删除成功');
                    // 刷新列表数据
                    this.getTableData();
                }
            }
        })
    }
    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 })
                }
            }
        })
    }
    setRowClassNamePublic=(record)=>{
        //点击行，渲染当前行样式 
       return record.ID === this.state.rowID ? 'clickRowStyle' : '';

   }

   // 编辑  行选中
   onClickRowPublic = (record) => {
       return {
           onClick: () => {
               // console.log("record---",record)
               // this.confirmSelection(record);
                   this.setState({
                       rowData: record,
                   })
                   if (this.state.rowID === "") {
                       this.setState({
                           rowID: record.ID,
                       });
                   } else {
                       if (this.state.rowID !== record.ID) {
                           this.setState({
                               rowID: record.ID,
                           });
                       } else {
                           this.setState({
                               rowID: "",
                               rowData: {},
                           });
                       }
                   }

           },
           onDoubleClick: () => {
               // console.log("record------",record)
               // this.confirmSelection(record);
               this.setState({
                   rowData: record,
               })
               if (this.state.rowID === "") {
                   this.setState({
                       rowID: record.ID,
                   });
               } else {
                   if (this.state.rowID !== record.ID) {
                       this.setState({
                           rowID: record.ID,
                       });
                   } else {
                       this.setState({
                           rowID: "",
                           rowData: {},
                       });
                   }
               }
           }
       }
   }
    // 双击选中行数据的回调
    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() {
        let { selectData, hosp, status, tableData, total, page, rowData, unitData, loading, modalTotal, modalPage } = this.state;
        const { getFieldDecorator } = this.props.form;
        // 组件所需参数
        const param = {
            // 表头配置
            columns: this.state.columns,
            // 表格数据
            data: tableData,
            // 数据总条数
            total: total,
            // 当前页数
            page: page,
            // 表格的宽度
            x: 900,
            y: store.getState().tableHeight.y - 180 + 'px',
            rowClassName:true,
            isOnRow: true,
            TableClassName: "AntimicrobialUse",
            height: store.getState().tableHeight.y - 167 + 'px',
            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,
        }
        const formLayoutItem = {
            labelCol: { span: 9 },
            wrapperCol: { span: 13 },
        }
        // 病人分类
        let patCatOp = this.state.patCatData && this.state.patCatData.map((item, index) => {
            return (<Option key={index} value={item.id} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
        })
        // 单位
        let usageOp = this.state.unitData && this.state.unitData.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' }}>
                        {rowData.ID&&rowData.ID?"编辑抗菌药物用量维护":"添加抗菌药物用量维护"}
                        {/* <span style={{ fontSize: '12px', color: '#157EDF', fontWeight: '100', marginLeft: '10px' }}>(说明：未选择医院时，别名适用全部医院）</span> */}
                    </div>
                    <div>
                        <Form>
                            <Row>
                            <Form.Item label="病人分类：" {...formLayoutItem}>
                                    {getFieldDecorator('patientCatID', {
                                        initialValue: rowData.patientCatID ? rowData.patientCatID : undefined,
                                        rules: [{ required: true, message: '请选择病人分类' }]
                                    })(
                                        <Select showSearch optionFilterProp="seatchprop"  style={{ width: '150px', marginRight: '8px' }} placeholder="请选择">
                                            {patCatOp}
                                        </Select>
                                    )}
                                </Form.Item>
                            <Form.Item label="开始剂量" {...formLayoutItem}>
                                    {getFieldDecorator('doseQtyFrom', {
                                        initialValue: rowData.doseQtyFrom? rowData.doseQtyFrom: undefined,
                                        rules: [{ required: false, message: '' }]
                                    })(
                                        <Input allowClear type="number" min={0} style={{ width: '150px', marginRight: '8px' }} />
                                    )}
                                </Form.Item>
                                <Form.Item label="结束剂量" {...formLayoutItem}>
                                    {getFieldDecorator('doseQtyTo', {
                                        initialValue: rowData.doseQtyTo? rowData.doseQtyTo: undefined,
                                        rules: [{ required: false, message: '' }]
                                    })(
                                        <Input allowClear type="number" min={0} style={{ width: '150px', marginRight: '8px' }} />
                                    )}
                                </Form.Item>
                                <Form.Item label="单位：" {...formLayoutItem}>
                                    {getFieldDecorator('doseUnitID', {
                                        initialValue: rowData.doseUnitID ? rowData.doseUnitID : undefined,
                                        rules: [{ required: false, message: '请选择单位' }]
                                    })(
                                        <Select showSearch optionFilterProp="seatchprop" allowClear style={{ width: '150px', marginRight: '8px' }} placeholder="请选择">
                                            {usageOp}
                                        </Select>
                                    )}
                                </Form.Item>
                            </Row>
                            <Row>
                            <Form.Item label="生效日期：" {...formLayoutItem}>
                                    {getFieldDecorator('startDate', {
                                        initialValue: rowData.startDate ? Moment(rowData.startDate) : Moment(),
                                        rules: [{ required: true, message: '生效日期不能为空' }]
                                    })(
                                        <DatePicker style={{ width: '150px', marginRight: '8px' }} format="YYYY-MM-DD"  />
                                    )}
                                </Form.Item>
                               
                            <Form.Item label="开始次数" {...formLayoutItem}>
                                    {getFieldDecorator('freqTimesFrom', {
                                        initialValue: rowData.freqTimesFrom? rowData.freqTimesFrom: undefined,
                                        rules: [{ required: false, message: '' }]
                                    })(
                                        <Input allowClear type="number" min={0} style={{ width: '150px', marginRight: '8px' }} />
                                    )}
                                </Form.Item>
                                <Form.Item label="结束次数" {...formLayoutItem}>
                                    {getFieldDecorator('freqTimesTo', {
                                        initialValue: rowData.freqTimesTo? rowData.freqTimesTo: undefined,
                                        rules: [{ required: false, message: '' }]
                                    })(
                                        <Input allowClear type="number" min={0} style={{ width: '150px', marginRight: '8px' }} />
                                    )}
                                </Form.Item>
                            
                                <Form.Item label="备注" {...formLayoutItem}>
                                    {getFieldDecorator('note', {
                                        initialValue: rowData.note ? rowData.note : undefined,
                                        rules: [{ required: false, message: '' }]
                                    })(
                                        <Input allowClear  style={{ width: '150px', marginRight: '8px' }} />
                                    )}
                                </Form.Item>
                               
                            </Row>
                            <Row>
                                <Form.Item label="失效日期：" {...formLayoutItem} style={{paddingLeft:"4px"}}>
                                    {getFieldDecorator('stopDate', {
                                        initialValue: rowData.stopDate ? Moment(rowData.stopDate) : undefined,
                                    })(
                                        <DatePicker style={{ width: '150px', marginRight: '8px' }} format="YYYY-MM-DD"  />
                                    )}
                                </Form.Item>
                                <span style={{ display: 'inline-block', marginTop: '4px' }}>
                                    <Button style={{ margin: '0 8px 0 20px' }} 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 cls="AntibactDoseQty" wrapperHeight={-135} tableBodyHeight={70} onClickRowPublic={this.onClickRowPublic} setRowClassNamePublic={this.setRowClassNamePublic} param={param} handelThis={this} onRef={this.onRef} />
                </div>
                <PublicModalTable
                    // onClickRowPublic={this.onClickRowPublic}
                    param={modalParam}
                    onRef={this.modalOnRef}
                    compilePage={this.handleCompilePage}
                />
                <ColumnAuthoritysModel
                    clientWidth='800px'
                    compontName='AntibactDoseQty'
                    configType="C"
                    onRef={this.onColumnRef}
                    reloadData={this.getMainTableColumns}
                />
            </div>
        )
    }
};
const AntibacterialTabDosage = Form.create()(AntibacterialTabDosages);
export default AntibacterialTabDosage;