//发药窗口维护
import React from 'react';
import { Card, Row, Col, Form, DatePicker, Select, Button, Checkbox, Table, Input, message, Pagination , Switch } from 'antd';
import CommonPagination from 'components/pagination/index';
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: 16 },
};
const formItemSwitch = {    // label 和input宽度
    labelCol: { span:9 },
    wrapperCol: { span: 10 },
};

const DispWin = Form.create()(
    class extends React.Component {
        constructor() {
            super();
            this.state = {
                userInfo: JSON.parse(window.sessionStorage.userData),
                data: [],
                SelectData: {},
                inOpLocDr:'',
                detailsId: '',//配药列表ID
                WaListData: [], //入库单数据
                pageSize: 10,
                page: 1,
                pageSize2: 10,
                page2: 1,
                rowId: '', //行选中高亮id
                rowId2: '', //行选中高亮id
                total:0,
                total2:0,
                dispensingId: '',
                dispensingWin: [],
                assignLocData: [],
                assignLocTableData: [],
                assignLocId: '',
                assignDetailsId: '',
                dataLi: [],
                value: undefined,
            };
            // 配药表头
            this.columns = [
                {
                    key: 1,
                    title: '药房名称',
                    dataIndex: 'locDesc',
                    align: "center",
                    width: '12%'
                },
                {
                    key: 2,
                    title: '序号',
                    dataIndex: 'seqNo',
                    align: "center",
                    width: '11%'
                },
                {
                    key: 3,
                    title: '窗口代码',
                    dataIndex: 'dispWinCode',
                    align: "center",
                    width: '11%'
                },
                {
                    key: 4,
                    title: '窗口名称',
                    dataIndex: 'dispWinDesc',
                    align: "center",
                    width: '11%'
                },
                {
                    key: 5,
                    title: '窗口类型',
                    dataIndex: 'typeDesc',
                    align: "center",
                    width: '11%'
                },
                {
                    key: 6,
                    title: '配药窗口',
                    dataIndex: 'prepWinDesc',
                    align: "center",
                    width: '11%'
                },
                {
                    key: 7,
                    title: '生效日期',
                    dataIndex: 'startDate',
                    align: "center",
                    width: '11%'
                },
                {
                    key: 8,
                    title: '失效日期',
                    dataIndex: 'endDate',
                    align: "center",
                    width: '11%'
                },
                {
                    key: 9,
                    title: '默认窗口',
                    dataIndex: 'default',
                    align: "center",
                    width: '11%'
                }
            ];

            // 配药表头
            this.columns2 = [
                {
                    key: 1,
                    title: '科室名称',
                    dataIndex: 'admLocDesc',
                    align: "center",
                }
            ];
        }

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

        //清空表格内容
        handleReset = () => {
            this.setState({WaListData: [],detailsListData: [],total: 0,total2: 0,rowId: '',assignLocTableData: [], assignDetailsId: '', detailsId: ''});
            this.props.form.resetFields();
        };

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

        // 获取配药窗口列表
        getWarehouseList=()=>{
            this.setState({loading: true});
            let inOpLocDr = this.props.form.getFieldValue('locDr');
            let data = {
                params: [{
                    locID:inOpLocDr ? inOpLocDr : this.state.dispensingId ,
                }],
                pagination: [
                    {
                        pageSize:this.state.pageSize,
                        currentPage:this.state.page,
                        sort:"ID",
                        dir:"asc",
                    }
                ],
            };
            if(inOpLocDr){
                $http.post('urlS', this, {
                    code: "02030009",
                    data: data,
                    success: function (res) {
                        if(res.result.rows.length > 0){
                            for(let i = 0; i < res.result.rows.length; i++){
                                res.result.rows[i].key = i;
                            }
                            this.setState({ WaListData: res.result.rows,total: res.result.total,loading: false});

                        }else {
                            this.setState({detailsListData: [], WaListData: []});
                            message.error("没数据")
                        }
                    },
                    error: function (err) {
                        message.error(err.errorMessage)
                    }
                });
            }else {
                message.error('请选择科室')
            }

        };

        // 发药窗口保存
        approveDetermine=()=>{

            let locDr = this.props.form.getFieldValue('locDr');
            let seqNo = this.props.form.getFieldValue('seqNo');
            let code = this.props.form.getFieldValue('code');
            let desc = this.props.form.getFieldValue('desc');
            let type = this.props.form.getFieldValue('type');
            let prepWin = this.props.form.getFieldValue('prepWin');
            let StartDate = this.props.form.getFieldValue('StartDate');
            let EndDate = this.props.form.getFieldValue('EndDate');
            let defaultState = this.props.form.getFieldValue('default');
            let data = {
                params: [{
                    dispWinID:this.state.detailsId ? this.state.detailsId : '',
                    locID: locDr ? locDr : '',
                    seqNo:seqNo ? seqNo : '',
                    dispWinCode:code ? code : '',
                    dispWinDesc:desc ? desc : '',
                    prepWinID:prepWin ? prepWin : '',
                    typeID: type ? type : '',
                    startDate:StartDate ? Moment(StartDate).format('YYYY-MM-DD') : '',
                    endDate:EndDate ? Moment(EndDate).format('YYYY-MM-DD') : '',
                    default: defaultState  ? "Y" : "N"
                }]
            };
            if(locDr && code && desc && StartDate && type){
                $http.post('urlS', this, {
                    code: "02030008",
                    data: data,
                    success: function (res) {
                        if(+res.errorCode == '0'){
                            this.getWarehouseList();
                            this.props.form.setFieldsValue({
                                ID: '',
                                seqNo: '',
                                code: '',
                                type: '',
                                desc: '',
                                prepWin: '',
                                StartDate:Moment(Moment().format('L'), 'YYYY-MM-DD'),
                                EndDate:undefined,
                                default:false,
                            });
                            this.setState({rowId: ''});
                            message.success(res.errorMessage);
                        }
                    },
                    error: function (err) {
                        message.error('保存失败');
                    }
                });
            }else {
                message.error('必填选项缺漏')
            }

        };

        //获取配药窗口下拉数据
        deScriptsData =(id) => {
            this.props.form.setFieldsValue({prepWin: ''});
            let data = {
                params: [{
                    locID:id,
                }]
            };
            // 获取下拉数据
            $http.post('urlS', this, {
                code: "02030006",
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        this.setState({dispensingWin: res.result})
                    }
                }
            })
        };

        //指定科室列表数据
        assignLocListData(id) {
            this.setState({detailsLoading: true})
            let data = {
                params: [{
                    dispWinID:id ? id : this.state.detailsId,
                }],
                pagination: [
                    {
                        pageSize:this.state.pageSize,
                        currentPage:this.state.page,
                        sort:"ID",
                        dir:"asc",
                    }
                ],
            };
            $http.post('urlS', this, {
                code: "02030011",
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        for(let i = 0; i < res.result.rows.length; i++){
                            res.result.rows[i].key = i;
                        }
                        this.setState({assignLocTableData: res.result.rows,total2: res.result.total, detailsLoading: false})
                    }
                }
            })
        }

        //获取选中列表数据
        getListDate = (id) => {
            let data = {
                params: [{
                    dispWinID:id,
                }]
            };
            $http.post('urlS', this, {
                code: "02030010",
                data: data,
                success: function (res) {
                    if(res.result.length > 0){
                        this.props.form.setFieldsValue({
                            seqNo:res.result[0].seqNo,
                            code:res.result[0].dispWinCode,
                            type: res.result[0].typeID,
                            prepWin: res.result[0].prepWinID,
                            desc:res.result[0].dispWinDesc,
                            StartDate:res.result[0].startDate !=='' ? Moment(res.result[0].startDate, 'YYYY-MM-DD') : Moment(Moment().format('L'), 'YYYY-MM-DD'),
                            EndDate:res.result[0].endDate !=='' ? Moment(res.result[0].endDate, 'YYYY-MM-DD') : undefined,
                            default: res.result[0].default == "N" ? false : true,
                        });

                    }
                },
                error: function (err) {
                    message.error(err.errorMessage)
                }
            });
        };

        //保存指定科室
        setAssignLoc = () => {
            let data = {
                params: [{
                    dispWinLocID:"",
                    dispWinID: this.state.detailsId,
                    admLocID: this.state.assignLocId,

                }]
            };
            if(!this.state.detailsId){
                message.error('请选择左侧列表数据');
                return
            }
            if(!this.state.assignLocId){
                message.error('请选择科室');
                return
            }
            $http.post('urlS', this, {
                code: "02030012",
                data: data,
                success: function (res) {
                    this.assignLocListData();
                },
                error: function (err) {
                    message.error(err.errorMessage)
                }
            });
        };


        //删除
        deleteAssignLoc=()=> {
            let data = {
                params: [{
                    dispWinLocID: this.state.assignDetailsId ? this.state.assignDetailsId : '',
                }]
            };
            if(this.state.assignDetailsId){
                $http.post('urlS', this, {
                    code: "02030013",
                    data: data,
                    success: function (res) {
                        this.assignLocListData();
                        this.setState({assignDetailsId: ''});
                        message.info('删除成功');
                    },
                    error: function (err) {
                        message.error('删除失败')
                    }
                })
            }else {
                message.error('请选择删除科室')
            }

        }

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

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

        // 页码改变的回调，参数是改变后的页码及每页条数 入库单
        onChange2 = (page, pageSize) => {
            this.setState({page2: page, pageSize2: this.state.pageSize2}, () => {
                // 重新调用查询方法
                this.assignLocListData();
            });
        };

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

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

        //添加样式高亮
        setRowClassName=(record)=>{
            return record.dispWinID === this.state.rowId ? 'clickRowStyle' : '';
        };

        //添加样式高亮
        setRowClassName2=(record)=>{
            return record.admLocID === this.state.rowId2 ? 'clickRowStyle' : '';
        };

        handleSearch = (v) => {
            let data = {
                params: [{
                    alias: v,
                }]
            };
            //指定科室下拉
            if(v){
                $http.post('urlS', this, {
                    code: "02030007",
                    data: data,
                    success: function (res) {
                        if (+res.errorCode === 0) {
                            this.setState({assignLocData: res.result})
                        }
                    }
                })
            }
        };

        //获取指定科室ID
        handleChange = (v) => {
            this.setState({
                assignLocId: v
            })
        };

        render() {
            const { getFieldDecorator } = this.props.form;
            let userInfo = this.state.userInfo ? this.state.userInfo: {};
            //科室列表
            let inOpLocDrSelect = [];
            let inOpTypeDrSelect = [];
            let dispensingData = [];
            let assignLocList = [];
            this.state.SelectData.length > 0 && this.state.SelectData[0].loc.map((item, i) => {
                inOpLocDrSelect.push(<Option value={item.id} key={i}>{item.descripts}</Option>)
            });
            this.state.SelectData.length > 0 && this.state.SelectData[0].type.map((item, i) => {
                inOpTypeDrSelect.push(<Option value={item.id} key={i}>{item.descripts}</Option>)
            });
            this.state.dispensingWin.length > 0 && this.state.dispensingWin[0].rows.map((item, i) => {
                dispensingData.push(<Option value={item.id} key={i}>{item.descripts}</Option>)
            });
            this.state.assignLocData.length > 0 && this.state.assignLocData.map((item, i) => {
                assignLocList.push(<Option value={item.id} key={i}>{item.descripts}</Option>)
            });

            return (
                <div className="PrepareWin">
                    <Row>
                        <Card
                            size="small"
                            title={<div className="card-title-left-icon"><div></div>发药窗口维护</div>}
                        >
                            <Col span={20}>
                                <Form>
                                    <Row >
                                        <Row>
                                            <Col span={5}>
                                                <FormItem {...formItemLayout} label="药房科室">
                                                    {getFieldDecorator('locDr',{
                                                        initialValue: undefined,
                                                        rules:[{ required : true, message: '药房不能为空'}]
                                                    })(
                                                        <Select allowClear={true} showSearch onSelect={this.deScriptsData.bind(this)} onChange={(data) => {this.setState({dispensingId: data}, () => {this.getWarehouseList()})}}>
                                                            {inOpLocDrSelect}
                                                        </Select>
                                                    ) }
                                                </FormItem>
                                            </Col>
                                            <Col span={5}>
                                                <FormItem {...formItemLayout} label="序号">
                                                    {getFieldDecorator('seqNo',{
                                                        initialValue: undefined,
                                                        rules:[{required: false,message: '序号不能为空'}]
                                                    })(
                                                        <Input />
                                                    ) }
                                                </FormItem>
                                            </Col>
                                            <Col span={5}>
                                                <FormItem {...formItemLayout} label="窗口代码">
                                                    {getFieldDecorator('code',{
                                                        initialValue: undefined,
                                                        rules:[{required: true,message: '窗口代码不能为空'}]
                                                    })(
                                                        <Input />
                                                    ) }
                                                </FormItem>
                                            </Col>
                                            <Col span={5}>
                                                <FormItem {...formItemLayout} label="窗口名称">
                                                    {getFieldDecorator('desc',{
                                                        initialValue: undefined,
                                                        rules: [{ required: true, message: '窗口名称不能为空' }],
                                                    })(
                                                        <Input />
                                                    ) }
                                                </FormItem>
                                            </Col>
                                        </Row>
                                        <Row>
                                            <Col span={5}>
                                                <FormItem {...formItemLayout} label="窗口类型">
                                                    {getFieldDecorator('type',{
                                                        initialValue: undefined,
                                                        rules:[{required: true,message: '窗口类型不能为空'}]
                                                    })(
                                                        <Select allowClear={true} showSearch>
                                                            {inOpTypeDrSelect}
                                                        </Select>
                                                    ) }
                                                </FormItem>
                                            </Col>
                                            <Col span={5}>
                                                <FormItem {...formItemLayout} label="配药窗口">
                                                    {getFieldDecorator('prepWin',{
                                                        initialValue: undefined,
                                                        rules:[{required: true,message: '配药窗口不能为空'}]
                                                    })(
                                                        <Select allowClear={true} showSearch>
                                                            {dispensingData}
                                                        </Select>
                                                    ) }
                                                </FormItem>
                                            </Col>
                                            <Col span={5}>
                                                <FormItem {...formItemLayout} label="生效日期">
                                                    {getFieldDecorator('StartDate',{
                                                        initialValue: Moment(Moment().format('L'), 'YYYY-MM-DD'),
                                                        rules:[{required: true}]
                                                    })(
                                                        <DatePicker  disabledDate={(curDate) => {
                                                            return curDate && curDate > Moment().endOf('day');
                                                        }} />
                                                    ) }
                                                </FormItem>
                                            </Col>
                                            <Col span={5}>
                                                <FormItem {...formItemLayout} label="失效日期">
                                                    {getFieldDecorator('EndDate',{
                                                        initialValue: undefined,
                                                        rules:[{required: false}]
                                                    })(
                                                        <DatePicker  disabledDate={(curDate) => {
                                                            return curDate && curDate > Moment().endOf('day');
                                                        }} />
                                                    ) }
                                                </FormItem>
                                            </Col>
                                            <Col span={4}>
                                                <FormItem {...formItemSwitch} label="默认窗口">
                                                    {getFieldDecorator('default',{
                                                        valuePropName: 'checked',
                                                        initialValue: false,
                                                        rules:[{required: false}]
                                                    })(
                                                        <Switch checkedChildren="是" unCheckedChildren="否" />
                                                    ) }
                                                </FormItem>
                                            </Col>
                                        </Row>
                                    </Row>
                                </Form>
                            </Col>
                            <Col span={3}>
                                <Row style={{marginBottom: '18px',paddingLeft: '40px',marginTop: '4px'}}>
                                    <Button style={{marginRight: '30px'}} onClick={this.getWarehouseList}>查询</Button>
                                    <Button type="primary" onClick={this.handleReset}>清屏</Button>
                                </Row>
                                <Row style={{paddingLeft: '40px'}}>
                                    <Button type="primary"  style={{marginRight: '30px'}} onClick={this.approveDetermine}>保存</Button>
                                </Row>
                            </Col>

                        </Card>
                    </Row>
                    <Row>
                        <Col style={{width: '70%', float: 'left'}}>
                            <Card
                                size="small"
                                title={<div className="card-title-left-icon"><div></div>发药窗口列表</div>}
                            >
                                <div>
                                    <Table
                                        columns={this.columns}
                                        dataSource={this.state.WaListData}
                                        pagination={false}
                                        bordered
                                        scroll={{ y: store.getState().tableHeight.y - 70  }}
                                        style={{height: store.getState().tableHeight.y - 25 + 'px'}}
                                        rowKey={record => record.key}
                                        rowClassName={this.setRowClassName}
                                        onRow={(record) => {
                                            return {
                                                onClick: () => {
                                                    this.setState({detailsId: record.dispWinID});
                                                    if (this.state.rowId === '') {
                                                        // 保存行数据以及ID
                                                        this.setState({rowId: record.dispWinID});
                                                        this.getListDate(record.dispWinID);
                                                        this.assignLocListData(record.dispWinID);
                                                    } else {
                                                        if (this.state.rowId !== record.dispWinID) {
                                                            this.setState({rowId: record.dispWinID});
                                                            this.getListDate(record.dispWinID);
                                                            this.assignLocListData(record.dispWinID);
                                                        } else {
                                                            this.setState({rowId: '',assignLocTableData: [], detailsId: ''});
                                                            this.props.form.setFieldsValue({
                                                                ID: '',
                                                                seqNo: '',
                                                                code: '',
                                                                type: '',
                                                                desc: '',
                                                                prepWin: '',
                                                                StartDate:Moment(Moment().format('L'), 'YYYY-MM-DD'),
                                                                EndDate:undefined,
                                                            });
                                                        }
                                                    }
                                                },

                                            };
                                        }}
                                    />
                                    <CommonPagination size='small' current={this.state.page} total={this.state.total} search= 'search'
                                                      onShowSizeChange={this.onShowSizeChange.bind(this)} complete={true} dataSource={this.state.WaListData}
                                                      loading={this.state.loading} onChange={this.onChange.bind(this)} />
                                </div>
                            </Card>
                        </Col>
                        <Col  style={{width: '30%', float: 'left'}}>

                            <Card
                                size="small"
                                title={<div className="card-title-left-icon"><div></div>指定科室</div>}
                            >
                                <div>
                                    <Row>
                                        <Col span={15}>
                                            <FormItem {...formItemLayout} label="科室">
                                                {getFieldDecorator('locDr2',{
                                                    initialValue: undefined,
                                                    rules:[{ required : false, message: '药房不能为空'}]
                                                })(

                                                    <Select
                                                    showSearch
                                                    defaultActiveFirstOption={false}
                                                    showArrow={false}
                                                    filterOption={false}
                                                    onSearch={this.handleSearch}
                                                    onChange={this.handleChange}
                                                    notFoundContent={null}
                                                    >
                                                    {assignLocList}
                                                    </Select>
                                                ) }
                                            </FormItem>
                                        </Col>
                                        <Col span={8} style={{ paddingTop: '4px'}}>
                                            <Button style={{marginRight: '20px'}} onClick={this.setAssignLoc}>保存</Button>
                                            <Button type="primary" onClick={this.deleteAssignLoc}>删除</Button>
                                        </Col>
                                    </Row>
                                    <Table
                                        columns={this.columns2}
                                        dataSource={this.state.assignLocTableData}
                                        pagination={false}
                                        bordered
                                        scroll={{ y:  store.getState().tableHeight.y - 70 }}
                                        style={{height:  store.getState().tableHeight.y - 75 + 'px'}}
                                        rowKey={record => record.key}
                                        rowClassName={this.setRowClassName2}
                                        onRow={(record) => {
                                            return {
                                                onClick: () => {
                                                    this.setState({assignDetailsId: record.dispWinLocID});
                                                    if (this.state.rowId2 === '') {
                                                        // 保存行数据以及ID
                                                        this.setState({rowId2: record.admLocID});
                                                    } else {
                                                        if (this.state.rowId2 !== record.admLocID) {
                                                            this.setState({rowId2: record.admLocID});
                                                        } else {
                                                            this.setState({rowId2: '',assignDetailsId: ''});
                                                        }
                                                    }
                                                },

                                            };
                                        }}
                                    />

                                    <CommonPagination size='small' current={this.state.page2} total={this.state.total2} search= 'search'
                                                      onShowSizeChange={this.onShowSizeChange2.bind(this)} complete={true} dataSource={this.state.assignLocTableData}
                                                      loading={this.state.detailsLoading} onChange={this.onChange2.bind(this)} />
                                </div>
                            </Card>
                        </Col>
                    </Row>

                </div>
            )
        }
    }
);
export default DispWin;