// 发药类别维护
import React from 'react';
import { Card, Row, Col, Form, DatePicker, Select, Button, Modal, Table, Switch, message, Pagination, Input, Radio  } 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 },
};

const DispensingTypeMaintain = 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: [], //子类数据
                leftVisible: false, //显示子类修改弹窗
                subData: {}, //子类当行数据
                stateCode: null,
                value: '',
            };
            // 库存单的数据表头
            this.columns = [
                {
                    key: 1,
                    title: '代码',
                    dataIndex: 'dispCatCode',
                    align: "center",
                    width: '25%',

                },
                {
                    key: 2,
                    title: '名称',
                    dataIndex: 'dispCatDesc',
                    align: "center",
                    width: '25%',
                },
                {
                    key: 3,
                    title: '序号',
                    dataIndex: 'seqNo',
                    align: "center",
                    width: '25%',

                },
                {
                    key: 4,
                    title: '失效日期',
                    dataIndex: 'stopDate',
                    align: "center",
                    width: '25%',
                }
            ];
            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%',
                    render: (text, record,index) => {
                        return(
                            <Radio.Group  onChange={(e) => this.handleFieldSwitch(e, 'checkFlag',record.key)} value={text}>
                                <Radio value={1}>是</Radio>
                                <Radio value={0}>否</Radio>
                            </Radio.Group>
                        )
                    }
                },
                {
                    key: 5,
                    title: '满整支发药',
                    dataIndex: 'stkBinCode',
                    align: "center",
                    width: '20%',
                    render: (text, record,index) => {
                        return(  <Radio.Group  onChange={(e) => this.handleFieldSwitch(e, 'stkBinCode',record.key)} value={text}>
                            <Radio value={1}>是</Radio>
                            <Radio value={0}>否</Radio>
                        </Radio.Group> )
                    }
                }
            ]
        }

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

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

        //获取子类操作行数据对象
        getSubCatKey(key, newData) {
            const { subclassData } = this.state;
            return (newData || subclassData).filter(item => item.key === key)[0];
        }

        //文本框(Switch)数据修改
        handleFieldSwitch=(e, fieldName, key)=>{
            const { subclassData} = this.state;
            const newData = subclassData.map(item => ({ ...item }));
            const target = this.getSubCatKey(key, newData);
            // if (target) {
            //     target[fieldName] = e ? 1 : 0;
            //     this.setState({subclassData: newData, subData: target, stateCode: target.checkFlag});
            // }
            if (target) {
                target[fieldName] = e.target.value;
                this.setState({subclassData: newData, subData: target, stateCode: target.checkFlag});
                }
        };

        saveSubCat=()=>{
            let { subclassData } = this.state;
            subclassData.map((v,k)=>{
                subclassData[k].dispCatID = this.state.stockID ? this.state.stockID : undefined
            });
            let data = {
                params: subclassData ? subclassData : undefined
            };
            $http.post('urlS', this, {
                code: "02040013",
                data: data,
                success: function (res) {
                    if(res.errorCode == 0){
                        message.success(res.errorMessage);
                        this.getStkRepSubCatList();
                    }
                }
            });
        };


        // 关闭修改子类弹窗
        handleCancel = (e) => {
            this.setState({
                leftVisible: false
            });
        };

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


        onRef = (ref) => {
            this.child = ref;
        };


        // 获取界面默认值
        getTacitlyApproveData() {
            let data = {
                params: []
            };
            // 获取下拉数据
            $http.post('urlS', this, {
                code: "02040010",
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        this.setState({SelectData: res})
                    }
                }
            })
        }

        // 获取库存单列表数据
        getLeftDataList=()=>{
            let data = {
                params: []
            };
            $http.post('urlS', this, {
                code: "02040012",
                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=()=>{
            this.props.form.validateFields((errors, values) => {
                let obj = JSON.parse(JSON.stringify(values));
                if (errors == null) {
                    let data = {
                        params:  [{
                            dispCatID:this.state.modalData.dispCatID ? this.state.modalData.dispCatID : undefined,
                            dispCatCode:obj.dispCatCode ? obj.dispCatCode : undefined,
                            dispCatDesc:obj.dispCatDesc ? obj.dispCatDesc : undefined,
                            seqNo: obj.seqNo ? obj.seqNo : undefined,
                            stopDate:obj.stopDate ? Moment(obj.stopDate).format('YYYY-MM-DD'): undefined,
                        }]
                    };
                    $http.post('urlS', this, {
                        code: "02040011",
                        data: data,
                        success: function (res) {
                            if(res.errorCode == 0){
                                message.success(res.errorMessage);
                                this.setState({leftVisible: false})
                                this.getLeftDataList();
                            }
                        },
                        error: function (err) {
                            message.error(err.errorMessage)
                        }
                    });
                }
            });

        };

        // 获取医嘱子类列表数据
        getStkRepSubCatList=()=>{
            let data = {
                params: [{
                 dispCatID: this.state.stockID ? this.state.stockID : undefined
                }],
                pagination: [
                    {
                        pageSize:this.state.pageSize,
                        currentPage: this.state.page ,
                        sort:"ID",
                        dir:"asc",
                    }
                ]
            };
            $http.post('urlS', this, {
                code: "02040015",
                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: []});

                    }
                },
                error: function (err) {
                    message.error(err.errorMessage)
                }
            });
        };
        // 页码改变的回调，参数是改变后的页码及每页条数 库存单
        onChange = (page, pageSize) => {
            this.setState({page: page, pageSize: pageSize}, () => {
                // 重新调用查询方法
                this.getStkRepSubCatList();
            });
        };

        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.dispCatID , modalData: record},()=>{
                            this.getStkRepSubCatList();
                        });
                    } else {
                        if (this.state.rowKey !== record.key) {
                            this.setState({rowKey: record.key, stockID: record.dispCatID,  modalData: record},()=>{
                                this.getStkRepSubCatList();
                            });

                        }
                    }
                },
              onDoubleClick: () => {
                  // 保存行数据以及ID
                  this.setState({leftVisible: true})
              }
            }
        };

        // 表格行的类名
        setRowClassName = (record) => {
            return record.key === this.state.rowKey ? 'clickRowStyle' : '';
        };

        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="DispensingTypeMaintain">
                    <Col  span={8}>
                        <Card
                            size="small"
                            title="发药类别维护-<双击列表修改>"
                        >
                            <Col>
                                <Row >
                                    <Col>
                                        <Row  style={{marginBottom: '5px'}} className="button">
                                            <Button  onClick={()=> { this.setState({ modalData:{}},()=>{this.setState({leftVisible: true})})}}>+ 发药类别</Button>
                                        </Row>
                                    </Col>
                                </Row>
                            </Col>
                            <div  style={{height: store.getState().tableHeight.y +139+ 'px'}}>
                                <Table
                                    columns={this.columns}
                                    dataSource={this.state.WaListData}
                                    pagination={false}
                                    bordered
                                    style={{height: store.getState().tableHeight.y + 20 + 'px'}}
                                    scroll={{ y: store.getState().tableHeight.y - 20 }}
                                    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>
                    </Col>
                    <Col  span={16}>
                        <Card
                            size="small"
                            title='医嘱子类'
                        >
                            <Col>
                                <Row style={{ marginBottom: '5px'}}>
                                    <Col span={11}>
                                    <span>当前设置发药类别：   {this.state.modalData.dispCatCode && <span>【{this.state.modalData.dispCatCode}】【{this.state.modalData.dispCatDesc}】【{this.state.modalData.stopDate}】</span>}</span>
                                    </Col>
                                    <Col  span={13} style={{ textAlign: 'right'}}>
                                        <span>提示：医嘱之类仅能属于一种发药类型，请谨慎设置</span>
                                        <Button disabled={this.state.subclassData.length>0 ? false : true} onClick={this.saveSubCat} style={{ margin: '0 20px', backgroundColor: '#1999db', color: '#fff'}}>保存</Button>
                                    </Col>
                                </Row>
                            </Col>
                            <div  style={{height: store.getState().tableHeight.y +139+ 'px'}}>
                                <Table
                                    columns={this.columnsDetails}
                                    dataSource={this.state.subclassData}
                                    pagination={false}
                                    bordered
                                    style={{height: store.getState().tableHeight.y +95+ 'px'}}
                                    scroll={{ y: store.getState().tableHeight.y +55 }}
                                    rowKey={record => record.key}
                                />
                                {/*<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>
                    </Col>
                    <Modal
                        title="修改发药类别"
                        visible={this.state.leftVisible}
                        onCancel={this.handleCancel}
                        width={400}
                        footer={null}
                    >
                        <div className="SubPopup">
                            <form>
                                <Row>
                                    <Col>
                                        <FormItem {...formItemLayout} label="代码">
                                            {getFieldDecorator('dispCatCode',{
                                                initialValue: this.state.modalData.dispCatCode ? this.state.modalData.dispCatCode : undefined,
                                                rules:[{ required : true, message: '代码不能为空'}]
                                            })(
                                                <Input />
                                            ) }
                                        </FormItem>
                                    </Col>
                                    <Col>
                                        <FormItem {...formItemLayout} label="名称">
                                            {getFieldDecorator('dispCatDesc',{
                                                initialValue: this.state.modalData.dispCatDesc ? this.state.modalData.dispCatDesc : undefined,
                                                rules:[{ required : true, message: '名称不能为空'}]
                                            })(
                                                <Input />
                                            ) }
                                        </FormItem>
                                    </Col>
                                    <Col>
                                        <FormItem {...formItemLayout} label="序号">
                                            {getFieldDecorator('seqNo',{
                                                initialValue: this.state.modalData.seqNo ? this.state.modalData.seqNo : undefined,
                                                rules:[{ required : false, message: '序号不能为空'}]
                                            })(
                                                <Input />
                                            ) }
                                        </FormItem>
                                    </Col>
                                    <Col>
                                        <FormItem {...formItemLayout} label="失效日期">
                                            {getFieldDecorator('stopDate',{
                                                initialValue:this.state.modalData&&this.state.modalData.stopDate ?  Moment(this.state.modalData.stopDate): undefined,
                                                rules:[{required: false, message: '失效日期不能为空'}]
                                            })(
                                                <DatePicker style={{width: '100%'}} format="YYYY-MM-DD"/>
                                            ) }
                                        </FormItem>
                                    </Col>
                                </Row>
                            </form>
                            <Row style={{textAlign: 'center'}}>
                                <Button onClick={this.saveCategory} style={{background: '#1999db',color: '#fff'}}>保存</Button>
                            </Row>
                        </div>
                    </Modal>
                </div>
            )
        }
    }
);
export default DispensingTypeMaintain;