//医师权限
import React from 'react';
import { Card, Row, Col, Form, DatePicker, Select, Button, Switch, Table, Input, message, Pagination  } 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:12 },
    wrapperCol: { span: 12 },
};
const PrepareWin = Form.create()(
    class extends React.Component {
        constructor() {
            super();
            this.state = {
                userInfo: JSON.parse(window.sessionStorage.userData),
                data: [],
                SelectData: {},
                inOpLocDr:'',
                vendor: '',
                AuthData: [], //入库单数据
                pageSize: 10,
                page: 1,
                rowId: '', //行选中高亮id
                total:0,
                warehouseListId: '',
                locData: '',
                personnelList:[],
                rowsData:{}
            }
            // 配药表头
            this.columns = [
                {
                    key: 1,
                    title: '药房名称',
                    dataIndex: 'locDesc',
                    align: "center",
                    width: '20%'
                },
                {
                    key: 2,
                    title: '人员',
                    dataIndex: 'userName',
                    align: "center",
                    width: '20%'
                },
                {
                    key: 3,
                    title: '审核权限',
                    dataIndex: 'auditAuth',
                    align: "center",
                    width: '20%'
                },
                {
                    key: 4,
                    title: '配药权限',
                    dataIndex: 'prepAuth',
                    align: "center",
                    width: '20%'
                },
                {
                    key: 5,
                    title: '发药权限',
                    dataIndex: 'dispAuth',
                    align: "center",
                    width: '20%'
                },
            ]
        }

        componentDidMount() {
            // 初始化数据
            this.getTacitlyApproveData();
            this.getPersonnelData();
            let listData = document.querySelectorAll('.PrdetailsHeight  .ant-table-body');
            if(listData.length>0){
                listData[0].style.height = store.getState().tableHeight.y - 55 + 'px';
            }
        }

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

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

            this.setState({personnelList:[]});
            let data = {
                params: [{
                    locID:val ? val : ''
                }]
            };
            $http.post('urlS', this, {
                code: "02030084",
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        this.setState({personnelList: res.user})
                    }
                }
            })
        }

        // 获取配药窗口列表
        getAuthorityData=()=>{
            this.setState({loading: true})
            let locDr = this.props.form.getFieldValue('locDr');
            let userDr = this.props.form.getFieldValue('doctor');
            // let auditAuth = this.props.form.getFieldValue('AuditAuth');
            // let prepAuth = this.props.form.getFieldValue('PrepAuth');
            // let dispAuth = this.props.form.getFieldValue('DispAuth');
            let data = {
                params: [{
                    locID: locDr ? locDr : '',
                    userDr:userDr ? userDr : '',

                }],
              pagination: [
                  {
                      pageSize:this.state.pageSize,
                      currentPage:this.state.page,
                      sort:"ID",
                      dir:"asc",
                  }
              ],
            };
            if(locDr){
                $http.post('urlS', this, {
                    code: "02030080",
                    data: data,
                    success: function (res) {
                        if(res.rows.length > 0){
                            for(let i = 0; i < res.rows.length; i++){
                                res.rows[i].key = i;
                            }
                            this.setState({ AuthData: res.rows,total: res.total, loading : false});

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

        };

        // 保存
        approveDetermine=()=>{

            let locDr = this.props.form.getFieldValue('locDr');
            let userDr = this.props.form.getFieldValue('doctor');
            let auditAuth = this.props.form.getFieldValue('AuditAuth');
            let prepAuth = this.props.form.getFieldValue('PrepAuth');
            let dispAuth = this.props.form.getFieldValue('DispAuth');
            let data = {
                params: [{
                    id:this.state.rowId ? this.state.rowId : '',
                    locID: locDr ? locDr : '',
                    userDr:userDr ? userDr : '',
                    auditAuth:auditAuth ? 'Y'  : 'N',
                    prepAuth:prepAuth ? 'Y' : 'N',
                    dispAuth:dispAuth ? 'Y' : 'N',

                }]
            };
            if(locDr && userDr){
                $http.post('urlS', this, {
                    code: "02030079",
                    data: data,
                    success: function (res) {
                        if(+res.errorCode == '0'){
                            this.getAuthorityData();
                            this.props.form.setFieldsValue({
                                DispAuth: false,
                                locDr: '',
                                doctor: '',
                                AuditAuth: false,
                                PrepAuth: false,
                            });
                            this.setState({rowId: ''});
                            message.success(res.errorMessage);
                        }
                    },
                    error: function (err) {
                        message.error(err.errorMessage);
                    }
                });
            }else {
                message.error('必填选项缺漏')
            }

        };

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

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

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

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

        setDataList=(val)=>{
            this.props.form.setFieldsValue({
                DispAuth: val.dispAuth == 'Y' ? true : false,
                locDr: val.locID,
                doctor: val.userDr,
                AuditAuth: val.auditAuth == 'Y' ? true : false,
                PrepAuth: val.prepAuth == 'Y' ? true : false,
            });
        }

        render() {
            const { getFieldDecorator } = this.props.form;
            let userInfo = this.state.userInfo ? this.state.userInfo: {};
            //科室列表
            let inOpLocDrSelect = [];
            this.state.SelectData.length > 0 && this.state.SelectData.map((item, i) => {
                inOpLocDrSelect.push(<Option value={item.id} key={i}>{item.descripts}</Option>)
            });
            //人员列表
            let doctorSelect = [];
            this.state.personnelList.length > 0 && this.state.personnelList.map((item, i) => {
                doctorSelect.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={18}>
                                <Form>
                                    <Row >
                                        <Row>
                                            <Col span={6}>
                                                <FormItem {...formItemLayout} label="科室">
                                                    {getFieldDecorator('locDr',{
                                                        initialValue:  undefined,
                                                        rules:[{ required : true, message: '科室不能为空'}]
                                                    })(
                                                        <Select allowClear={true} showSearch onChange={(data) => {this.setState({locData: data}, () => {this.getAuthorityData()})}} onSelect={(v)=>{this.getPersonnelData(v)}}>
                                                            {inOpLocDrSelect}
                                                        </Select>
                                                    ) }
                                                </FormItem>
                                            </Col>
                                            <Col span={6}>
                                                <FormItem {...formItemLayout} label="人员">
                                                    {getFieldDecorator('doctor',{
                                                        initialValue:  undefined,
                                                        rules:[{ required : true, message: '人员不能为空'}]
                                                    })(
                                                        <Select allowClear={true} showSearch>
                                                            {doctorSelect}
                                                        </Select>
                                                    ) }
                                                </FormItem>
                                            </Col>
                                            <Col span={4}>
                                                <FormItem {...formItemSwitch} label="审核权限">
                                                    {getFieldDecorator('AuditAuth',{
                                                        valuePropName: 'checked',
                                                        initialValue: false,
                                                    })(
                                                        <Switch checkedChildren="Y" unCheckedChildren="N"  />
                                                    ) }
                                                </FormItem>
                                            </Col>
                                            <Col span={4}>
                                                <FormItem {...formItemSwitch} label="配药权限">
                                                    {getFieldDecorator('PrepAuth',{
                                                        valuePropName: 'checked',
                                                        initialValue: false,
                                                    })(
                                                        <Switch checkedChildren="Y" unCheckedChildren="N"  />
                                                    ) }
                                                </FormItem>
                                            </Col>
                                            <Col span={4}>
                                                <FormItem {...formItemSwitch} label="发药权限">
                                                    {getFieldDecorator('DispAuth',{
                                                        valuePropName: 'checked',
                                                        initialValue:  false,
                                                    })(
                                                        <Switch checkedChildren="Y" unCheckedChildren="N"  />
                                                    ) }
                                                </FormItem>
                                            </Col>
                                        </Row>
                                    </Row>
                                </Form>
                            </Col>
                            <Col span={5}>
                                <Row style={{marginBottom: '18px',paddingLeft: '40px',marginTop: '4px'}}>
                                    <Button onClick={this.getAuthorityData}>查询</Button>
                                    <Button type="primary"  style={{margin: '0 30px'}} onClick={this.approveDetermine}>保存</Button>
                                    <Button type="primary" onClick={this.handleReset}>清屏</Button>
                                </Row>
                            </Col>

                        </Card>
                    </Row>
                    <Row>
                        <Col>
                            <Card
                                size="small"
                                title={<div className="card-title-left-icon"><div></div>医师权限列表</div>}
                            >
                                <div>
                                    <Table
                                        columns={this.columns}
                                        dataSource={this.state.AuthData}
                                        pagination={false}
                                        bordered
                                        scroll={{ y:  store.getState().tableHeight.y - 70 }}
                                        rowKey={record => record.key}
                                        rowClassName={this.setRowClassName}
                                        className="PrdetailsHeight"
                                        onRow={(record) => {
                                            return {
                                                onClick: () => {
                                                    if (this.state.rowId === '') {
                                                        // 保存行数据以及ID
                                                        this.setState({rowId: record.id, rowsData: record});
                                                        // this.getListDate(record.prepWinID);
                                                        this.setDataList(record);
                                                    } else {
                                                        if (this.state.rowId !== record.id) {
                                                            this.setState({rowId: record.id,rowsData: record});
                                                            this.setDataList(record);
                                                        } else {
                                                            this.setState({rowId: '',rowsData: {}});
                                                            this.props.form.setFieldsValue({
                                                                DispAuth: false,
                                                                locDr: '',
                                                                doctor: '',
                                                                AuditAuth: false,
                                                                PrepAuth: false,
                                                            });
                                                        }
                                                    }
                                                },

                                            };
                                        }}
                                    />
                                    <CommonPagination size='small' current={this.state.page} total={this.state.total} search= 'search'
                                                      onShowSizeChange={this.onShowSizeChange.bind(this)} complete={true} dataSource={this.state.AuthData}
                                                      loading={this.state.loading} onChange={this.onChange.bind(this)} />
                                </div>
                            </Card>
                        </Col>
                    </Row>

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