// 住院发药科室维护
import React from 'react';
import { Card, Row, Col, Form, DatePicker, Select, Button, Modal, Table, Switch, message, Popconfirm, Input  } from 'antd';
import { $http } from 'containers/config/https';
import Moment from 'moment';
import store from 'store';
import './style/index.less';

const { Option } = Select;
const FormItem = Form.Item;
const formItemLayout = {    // label 和input宽度
    labelCol: { span:7 },
    wrapperCol: { span: 17 },
};
var obj ={};
var objNew ={};
const HospitalizedDispensingLoc = Form.create()(
    class extends React.Component {
        constructor() {
            super();
            this.state = {
                userInfo: JSON.parse(window.sessionStorage.userData),
                data: [],
                queryCondition: {},
                SelectData: {},
                inOpLocDr:'',
                vendor: '',
                WaListData: [], //库存单数据
                pageSize: 10,
                page: 1,
                total:0,
                stateID: '',
                modalData:{},//主列表行数据
                ModalRowData: {}, // 弹框双击选中行数据
                stockID: '', //行ID
                subclassData: [], //发药类别数据
                visible: false, //显示发药类别修改弹窗
                BottomVisible: false, //显示发药类别修改弹窗
                TopVisible: false,//显示科室维护弹窗
                subData: {}, //发药类别当行数据
                stateCode: null,
                modalColumns: [],//上表头
                columnsDetails: [],//下表头
                DispensingData: {},
                locShow: false,  //新增科室维护
                CatColsDataData: [],
                CatColsID: '',
                CatColsKey: '',
                CatColsList: {}
            };
            // 库存单的数据表头
            this.columns = [
                {
                    key: 1,
                    title: '发药科室',
                    dataIndex: 'dispCatCode',
                    align: "center",
                    width: '10%',

                },
                {
                    key: 2,
                    title: '领药审核',
                    dataIndex: 'dispCatDesc',
                    align: "center",
                    width: '6%',
                },
                {
                    key: 3,
                    title: '药师审核',
                    dataIndex: 'seqNo',
                    align: "center",
                    width: '6%',

                },
                {
                    key: 4,
                    title: '医嘱处理',
                    dataIndex: 'stopDate',
                    align: "center",
                    width: '6%',
                },
                {
                    key: 5,
                    title: '冲减退药',
                    dataIndex: 'dispCatCode',
                    align: "center",
                    width: '6%',

                },
                {
                    key: 6,
                    title: '包药机',
                    dataIndex: 'dispCatDesc',
                    align: "center",
                    width: '6%',
                },
                {
                    key: 7,
                    title: '默认发药开始日期',
                    dataIndex: 'seqNo',
                    align: "center",
                    width: '6%',

                },
                {
                    key: 8,
                    title: '默认发药开始时间',
                    dataIndex: 'stopDate',
                    align: "center",
                    width: '6%',
                },
                {
                    key: 9,
                    title: '默认发药截止日期',
                    dataIndex: '',
                    align: "center",
                    width: '6%',

                },
                {
                    key: 10,
                    title: '默认发药截止时间',
                    dataIndex: '',
                    align: "center",
                    width: '6%',
                },
                {
                    key: 11,
                    title: '默认统计开始日期',
                    dataIndex: 'seqNo',
                    align: "center",
                    width: '6%',

                },
                {
                    key: 12,
                    title: '默认统计开始时间',
                    dataIndex: 'stopDate',
                    align: "center",
                    width: '6%',
                },
                {
                    key: 13,
                    title: '默认统计截止日期',
                    dataIndex: 'dispCatCode',
                    align: "center",
                    width: '6%',

                },
                {
                    key: 14,
                    title: '默认统计截止时间',
                    dataIndex: 'dispCatDesc',
                    align: "center",
                    width: '6%',
                },
                {
                    key: 15,
                    title: '默认冲退开始日期',
                    dataIndex: 'seqNo',
                    align: "center",
                    width: '6%',

                },
                {
                    key: 16,
                    title: '默认冲退开始时间',
                    dataIndex: 'stopDate',
                    align: "center",
                    width: '6%',
                }
            ];
            this.columnsDetails = [
                {
                    key: 1,
                    title: '发药类型',
                    dataIndex: 'ordSubCatCode',
                    align: "center",
                    width: '20%',
                },
                {
                    key: 2,
                    title: '默认',
                    dataIndex: 'ordSubCatDesc',
                    align: "center",
                    width: '20%',
                },
                {
                    key: 3,
                    title: '禁止申请退药',
                    dataIndex: 'dispCatDesc',
                    align: "center",
                    width: '20%',
                },
                {
                    key: 4,
                    title: '选择',
                    dataIndex: 'checkFlag',
                    align: "center",
                    width: '20%'
                },
                {
                    key: 5,
                    title: '满整支发药',
                    dataIndex: 'stkBinCode',
                    align: "center",
                    width: '15%'
                },
                {
                    title: '操作',
                    key: 6,
                    fixed: 'right',
                    align: "center",
                    width: '100px',
                    render: (text, record) => (
                        <span>
                        <Popconfirm title="删除不可恢复，你确定要删除吗?" onConfirm={(e) => this.handleDelete(record, e)}>
                            <span className='span' style={{color: 'rgba(240,65,52,1)'}}>删除</span>
                        </Popconfirm>
                      </span>
                    ),
                }
            ]
        }

        componentDidMount() {
            // 初始化数据
            this.getTacitlyApproveData();
            this.getTopDataList();
        }

        componentWillUnmount() {
            // 组件销毁前将静止让setState修改state的状态，防止内存泄漏
            this.setState = (state,callback)=>{ return; }
        }

        //保存发药类别修改数据
        saveSubCat=()=>{
            let g = this.state.SelectData.dispCatCols && this.state.SelectData.dispCatCols.rows ? this.state.SelectData.dispCatCols.rows : undefined;
            if(g){
                for(let i=0; i< g.length; i++){
                    objNew[g[i].id] = this.state.DispensingData[g[i].id]
                }
            }
            this.props.form.validateFields((errors, values) => {
                objNew.linkID = this.state.DispensingData.linkID ? this.state.DispensingData.linkID : undefined
                let data = {
                    params:[objNew]
                };
                $http.post('urlS', this, {
                    code: "02040019",
                    data: data,
                    success: function (res) {
                        if(res.errorCode == 0){
                            message.success(res.errorMessage);
                            this.setState({
                                visible: false,
                                DispensingData: {},
                                CatColsKey:'',
                                CatColsID: '' ,
                                CatColsList: {},
                                subclassData: []
                            },()=>{
                                objNew={}
                                this.getStkRepSubCatList();
                            });

                        }
                    }
                });
            });
        };

        // 关闭修改发药类别弹窗
        handleCancel = (e) => {
            this.setState({
                visible: false,
                BottomVisible: false,
                TopVisible: false,
                locShow: false,
            },()=>{    this.getStkRepSubCatList();this.getTopDataList()});
        };

        //清空表格内容
        handleReset = () => {
            this.setState({WaListData: [],total: 0, subclassData: []});
            this.props.form.resetFields();
        };

        // 获取界面默认值
        getTacitlyApproveData() {
            let data = {
                params: []
            };
            // 获取下拉数据
            $http.post('urlS', this, {
                code: "02040016",
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                     for(var i=0; i< res.dispCatCols.rows.length; i++){
                         res.dispCatCols.rows[i].key =  i;
                     }

                        this.setState({SelectData: res, CatColsDataData:  res.dispCatCols.rows});
                        //获取科室维护表头
                       let arr = res.locCols&&res.locCols.length > 0 ? JSON.parse(JSON.stringify(res.locCols)).map((item, index) => {
                           return  {
                               ...item,
                               key: index + 1,
                               title: item.desc,
                               dataIndex: item.id,
                               align: "center",
                               width: '100px',
                               render: (text, record,index) => {
                                   return( <Switch checkedChildren="是" unCheckedChildren="否" checked={text == 1 ? true : false} disabled /> )
                               }
                           }
                       }) : '';
                       let loc = {fieldType: "text", seqNo: 2, width: '100px', key: 100, title: "发药科室", dataIndex: "loc", align: "center",};
                       arr.push(loc);
                       //获取发药类别表头
                        let list =
                            {
                                title: '发药类别',
                                key: 101,
                                align: "center",
                                width: '100px',
                                dataIndex: 'dispCatDesc',
                                seqNo: 0
                            };
                        let arrBottom = res.dispCatCols&&res.dispCatCols.rows.length > 0 ? JSON.parse(JSON.stringify(res.dispCatCols.rows)).map((item, index) => {
                            return  {
                                ...item,
                                key: index + 1,
                                title: item.desc,
                                dataIndex: item.id,
                                align: "center",
                                width: '100px',
                                render: (text, record,index) => {
                                    return( <Switch checkedChildren="是" unCheckedChildren="否" checked={text == 1 ? true : false}  disabled /> )
                                }
                            }
                        }) : '';
                       arrBottom.push(list);
                       arrBottom.sort((a, b)=>  a.seqNo - b.seqNo);
                       arr.sort((a,b)=> a.seqNo-b.seqNo);
                       this.setState({modalColumns: arr, columnsDetails: arrBottom})

                    }
                }
            })
        }

        //获取操作行数据对象
        setLocCols=(e, fieldName, key) =>{
            const { modalData} = this.state;
            modalData[fieldName] = e ? '1' : '0';
            this.setState({modalData});
        }

        //文本框数据修改
        handleFieldChange=(e, fieldName, key)=>{
            const { DispensingData } = this.state;
            DispensingData[fieldName] = e ? '1' : '0';
            this.setState({DispensingData});
        };

        // 获取库存单列表数据
        getTopDataList=()=>{
            let data = {
                params: []
            };
            $http.post('urlS', this, {
                code: "02040017",
                data: data,
                success: function (res) {
                    if(res.errorCode == 0){
                        for(let i = 0; i < res.rows.length; i++){
                            res.rows[i].key = i;
                        }
                        this.setState({ WaListData: res.rows, total: res.total});
                    }else {
                        this.setState({ WaListData: []});
                    }
                },
                error: function (err) {
                    message.error(err.errorMessage)
                }
            });
        };

        // 保存新增发药类别数据
        saveCategory=()=>{
            let formData = this.props.form.getFieldValue('dispCatDesc');
            if(formData){
                let data = {
                    params:  [{
                        locID: this.state.stockID ? this.state.stockID : undefined,
                        dispCatID:formData ? formData : undefined,
                    }]
                };
                $http.post('urlS', this, {
                    code: "02040018",
                    data: data,
                    success: function (res) {
                        if(res.errorCode == 0){
                            message.success(res.errorMessage);
                            this.setState({BottomVisible: false})
                            this.getStkRepSubCatList();
                        }
                    },
                    error: function (err) {
                        message.error(err.errorMessage)
                    }
                });
            }else {
                message.error('请选择发药类别')
            }
        };


        // 保存科室维护数据
        saveMaintain=()=>{
            let g = this.state.SelectData.locCols ? this.state.SelectData.locCols : undefined;
            if(g){
                for(let i=0; i< g.length; i++){
                    obj[g[i].id] = this.state.modalData[g[i].id]
                }
            }
            this.props.form.validateFields((errors, values) => {
                if(this.state.stockID){
                    obj.locId = this.state.stockID ? this.state.stockID : undefined;
                }
                if(this.state.locShow){
                    obj.locId = this.props.form.getFieldValue('LocDesc') ? this.props.form.getFieldValue('LocDesc') : undefined;
                }
                let data = {
                    params:[obj]
                };
                $http.post('urlS', this, {
                    code: "02040025",
                    data: data,
                    success: function (res) {
                        if(res.errorCode == 0){
                            message.success(res.errorMessage);
                            this.setState({
                                TopVisible: false,
                                locShow: false,
                                rowKey:'',
                                stockID: '' ,
                                modalData: {}
                            });
                            obj={};
                            this.getTopDataList();
                        }
                    }
                });
            });
        };

        // 获取发药类别列表数据
        getStkRepSubCatList=()=>{
            let data = {
                params: [{
                    locID: this.state.stockID ? this.state.stockID : undefined
                }]
            };
            $http.post('urlS', this, {
                code: "02040020",
                data: data,
                success: function (res) {
                    if(res.errorCode == 0){
                        for(let i = 0; i < res.rows.length; i++){
                            res.rows[i].key = i;
                        }
                        this.setState({ subclassData: res.rows, total: res.total});
                    }else {
                        this.setState({ subclassData: [],CatColsID: '',CatColsList: {}});
                    }
                },
                error: function (err) {
                    message.error(err.errorMessage)
                }
            });
        };
        // 页码改变的回调，参数是改变后的页码及每页条数 库存单
        onChange = (page, pageSize) => {
            this.setState({page: page, pageSize: pageSize}, () => {
                // 重新调用查询方法
            });
        };

        onShowSizeChange = (current, size) => {
            this.setState({page: current, pageSize: size}, () => {
                // 重新调用查询方法
                this.onChange(current,size);
            })
        };

        // 显示分页总条数
        showTotal(total) {
            return `共 ${total} 条`;
        };

        // 设置科室维护行属性
        onClickRow = (record) => {
            return {
                // 单击行选中
                onClick: (e) => {
                    e.stopPropagation();
                    // this.resetFields();
                    if (this.state.rowKey === '') {
                        // 保存行数据以及ID
                        this.setState({rowKey: record.key, stockID: record.locId , modalData: record},()=>{
                            this.getStkRepSubCatList();
                        });
                    } else {
                        if (this.state.rowKey !== record.key) {
                            this.setState({rowKey: record.key, stockID: record.locId,  modalData: record},()=>{
                                this.getStkRepSubCatList();
                            });
                        }
                    }
                },
                onDoubleClick: () => {
                    // 保存行数据以及ID
                    this.setState({TopVisible: true})
                }
            }
        };

        // 设置发药类别属性
        onClickDispensing = (record) => {
            return {
                // 单击行选中
                onClick: (e) => {
                    e.stopPropagation();
                    // this.resetFields();
                    if (this.state.CatColsKey === '') {
                        // 保存行数据以及ID
                        this.setState({CatColsKey: record.key, CatColsID: record.linkID , CatColsList: record});
                    } else {
                        if (this.state.CatColsKey !== record.key) {
                            this.setState({CatColsKey: record.key, CatColsID: record.linkID,  CatColsList: record});
                        }
                    }
                },
                // 双击行选中
                onDoubleClick: () => {
                    // 保存行数据以及ID
                    this.setState({DispensingData: record},()=> {   this.setState({visible: true})})
                }
            }
        };
        // 表格行的类名
        setRowClassName = (record) => {
            return record.key === this.state.rowKey ? 'clickRowStyle' : '';
        };
        setCatClassName = (record) => {
            return record.key === this.state.CatColsKey ? 'clickRowStyle' : '';
        };


        // 删除
        handleDelete = () => {
            if(this.state.CatColsID){
                let data = {
                    params:[{
                        linkID:this.state.CatColsID ? this.state.CatColsID : undefined,
                    }]
                };
                $http.post('urlS', this, {
                    code: "02040026",
                    data: data,
                    success: function (res) {
                        if (+res.errorCode === 0) {
                            message.success(res.errorMessage);
                            this.setState({
                                CatColsKey:'',
                                CatColsID: '' ,
                                CatColsList: {}
                            })
                            this.getStkRepSubCatList();
                        }
                    }
                })
            }else {
                message.error('请选择删除对象')
            }

        };

        render() {
            //库存科室列表
            let inOpLocDrSelect = [];
            this.state.SelectData.loc && this.state.SelectData.loc.map((item, i) => {
                inOpLocDrSelect.push(<Option value={item.id} key={i}>{item.descripts}</Option>)
            });
            const { getFieldDecorator} = this.props.form;
            return (
                <div className="HospitalizedDispensingLoc">
                    <Row>
                        <Card
                            size="small"
                            title='住院发药科室维护 -《双击列表修改》'
                        >
                            <Col>
                                <Row >
                                    <Col>
                                        <Row  style={{marginBottom: '12px'}} className="button">
                                            <Button onClick={()=>{this.setState({ modalData: {}},()=>{this.setState({TopVisible: true, locShow: true})})}}>+ 新增</Button>
                                            <Button type="primary" style={{marginLeft: '20px'}} onClick={()=>{
                                                if(this.state.stockID){
                                                    this.setState({TopVisible: true});
                                                }else {
                                                    message.error('请选择修改对象')

                                                }
                                            }}>修改</Button>
                                        </Row>
                                    </Col>
                                </Row>
                            </Col>
                            <div  style={{height: '320px'}}>
                                <Table
                                    columns={this.state.modalColumns ? this.state.modalColumns : this.columns}
                                    dataSource={this.state.WaListData}
                                    pagination={false}
                                    bordered
                                    style={{height: '350px'}}
                                    scroll={{ y:300 }}
                                    rowKey={record => record.key}
                                    onRow={this.onClickRow}
                                    rowClassName={this.setRowClassName}
                                />
                                {/*<Pagination*/}
                                {/*showTotal={() => this.showTotal(this.state.total)}*/}
                                {/*size="small"*/}
                                {/*showQuickJumper*/}
                                {/*showSizeChanger*/}
                                {/*defaultCurrent={1}*/}
                                {/*total={this.state.total ? this.state.total : 0}*/}
                                {/*onChange={this.onChange}*/}
                                {/*onShowSizeChange={this.onShowSizeChange}*/}
                                {/*style={{textAlign: "right", marginTop: '13px'}}*/}
                                {/*/>*/}
                            </div>
                        </Card>
                    </Row>
                    <Row>
                        <Card
                            size="small"
                            title='科室发药类别'
                        >
                            <Col>
                                <Row >
                                    <Col>
                                        <Row  style={{marginBottom: '12px'}} className="button">
                                            <Button onClick={()=>{
                                                    if(this.state.stockID){
                                                        this.setState({BottomVisible: true});
                                                    }else {
                                                        message.error('请选择住院发药科室维护')
                                                    }}}>+ 发药类别</Button>
                                            <Button type="primary" style={{margin: '0 20px'}} onClick={this.handleDelete}>删除</Button>
                                            <Button type="primary" onClick={()=>{
                                                this.setState({DispensingData: this.state.CatColsList},()=> {
                                                    if(this.state.CatColsID){
                                                        this.setState({visible: true});
                                                    }else {
                                                        message.error('请选择修改对象')
                                                    }
                                                })
                                            }}>修改</Button>
                                        </Row>
                                    </Col>
                                </Row>
                            </Col>
                            <div>
                                <Table
                                    columns={this.state.columnsDetails ? this.state.columnsDetails: this.columnsDetails}
                                    dataSource={this.state.subclassData}
                                    pagination={false}
                                    bordered
                                    style={{height: store.getState().tableHeight.y - 300 + 'px'}}
                                    scroll={{ y: store.getState().tableHeight.y -250 }}
                                    rowKey={record => record.key}
                                    onRow={this.onClickDispensing}
                                    rowClassName={this.setCatClassName}
                                />
                                {/*<Pagination*/}
                                    {/*showTotal={() => this.showTotal(this.state.total)}*/}
                                    {/*size="small"*/}
                                    {/*showQuickJumper*/}
                                    {/*showSizeChanger*/}
                                    {/*defaultCurrent={1}*/}
                                    {/*total={this.state.total ? this.state.total : 0}*/}
                                    {/*onChange={this.onChange}*/}
                                    {/*onShowSizeChange={this.onShowSizeChange}*/}
                                    {/*style={{textAlign: "right", marginTop: '13px'}}*/}
                                {/*/>*/}
                            </div>
                        </Card>
                    </Row>
                    <Modal
                        title="修改发药类别"
                        visible={this.state.visible}
                        onCancel={this.handleCancel}
                        width={400}
                        footer={null}
                    >
                        <div  className="SubPopup">
                            <Row style={{textAlign: 'center'}}>
                                <form>
                                    {this.state.CatColsDataData && this.state.CatColsDataData.map((v, k)=>{
                                        return <Col key={k}>
                                            <FormItem {...formItemLayout} label={v.desc}>
                                                {getFieldDecorator(v.id ,{
                                                    initialValue:  v.fieldType == 'Checkbox' ? this.state.DispensingData[v.id] == 1 ? true : false : undefined,
                                                })(
                                                   v.fieldType == 'Checkbox' ?
                                                       <Switch checkedChildren="是" unCheckedChildren="否"
                                                               checked ={this.state.DispensingData[v.id] == 1 ? true : false }
                                                               onChange={(e)=>{this.handleFieldChange(e,v.id,v.key)}} />
                                                        : <Input/>
                                                ) }
                                            </FormItem>
                                        </Col>
                                    })}
                                </form>
                            </Row>
                            <Row style={{textAlign: 'center'}}>
                                <Button onClick={this.saveSubCat}  style={{background: '#1999db',color: '#fff'}}>保存</Button>
                            </Row>
                        </div>
                    </Modal>
                    <Modal
                        title="新增发药类别"
                        visible={this.state.BottomVisible}
                        onCancel={this.handleCancel}
                        width={400}
                        footer={null}
                    >
                        <div className="SubPopup">
                            <form>
                                <Row>
                                    <Col>
                                        <FormItem {...formItemLayout} label="发药类别">
                                            {getFieldDecorator('dispCatDesc',{
                                                initialValue: this.state.modalData.dispCatCode ? this.state.modalData.dispCatCode : undefined,
                                                rules:[{ required : false, message: '发药类别不能为空'}]
                                            })(
                                                <Select showSearch allowClear>
                                                    {this.state.SelectData.dispCat && this.state.SelectData.dispCat.map(item => {
                                                        return <Option key={item.id} value={item.dispCatID}>{item.dispCatDesc}</Option>
                                                    })}
                                                </Select>
                                            ) }
                                        </FormItem>
                                    </Col>
                                </Row>
                            </form>
                            <Row style={{textAlign: 'center'}}>
                                <Button onClick={this.saveCategory}  style={{background: '#1999db',color: '#fff'}}>保存</Button>
                            </Row>
                        </div>
                    </Modal>
                    <Modal
                        title="发药科室维护修改"
                        visible={this.state.TopVisible}
                        onCancel={this.handleCancel}
                        width={400}
                        footer={null}
                    >
                        <div className="SubPopup">
                            <Row style={{textAlign: 'center'}}>
                                <form>
                                    {this.state.locShow &&  <Col>
                                        <FormItem {...formItemLayout} label="发药科室">
                                            {getFieldDecorator('LocDesc',{
                                                initialValue: this.state.modalData.dispCatCode ? this.state.modalData.dispCatCode : undefined,
                                                rules:[{ required : false, message: '发药科室不能为空'}]
                                            })(
                                                <Select showSearch allowClear>
                                                    {this.state.SelectData.loc && this.state.SelectData.loc.map(item => {
                                                        return <Option key={item.id} value={item.id}>{item.descripts}</Option>
                                                    })}
                                                </Select>
                                            ) }
                                        </FormItem>
                                    </Col>
                                    }
                                    {this.state.SelectData.locCols && this.state.SelectData.locCols.map((v, k)=>{
                                        return <Col key={k}>
                                            <FormItem {...formItemLayout} label={v.desc}>
                                                {getFieldDecorator(v.id ,{
                                                    initialValue:v.fieldType == 'Checkbox' ? this.state.modalData[v.id] == 1 ? true : false : undefined,
                                                })(
                                                    v.fieldType == 'Checkbox' ?
                                                        <Switch checkedChildren="是" unCheckedChildren="否"
                                                                checked ={this.state.modalData[v.id] == 1 ? true : false }
                                                                onChange={(e)=>{this.setLocCols(e,v.id,v.key)}}/>
                                                         : <Input/>
                                                ) }
                                            </FormItem>
                                        </Col>
                                    })}

                                </form>
                            </Row>
                            <Row style={{textAlign: 'center'}}>
                                <Button onClick={this.saveMaintain}  style={{background: '#1999db',color: '#fff'}}>保存</Button>
                            </Row>
                        </div>
                    </Modal>
                </div>
            )
        }
    }
);
export default HospitalizedDispensingLoc;