// 角色关联科室
import React from 'react';
import { Card, Row, Col, Form, Table, Select, Input, Button, message,  Switch,  } from 'antd';
import CommonPagination from 'components/pagination/index';
import { $http } from 'containers/config/https';
import './style/index.less';
import store from 'store';

const { Option } = Select;
const formItemInput = {    // label 和input宽度
    labelCol: { span:7 },
    wrapperCol: { span: 17 },
};
const formItemSwitch = {    // label 和input宽度
    labelCol: { span:10 },
    wrapperCol: { span: 14 },
};
const roleRelatedLoc = Form.create()(
    class extends React.Component {
        constructor() {
            super();
            this.state = {
                roleListData: [], //角色列表数据
                locListData: [], //科室列表数据
                pageSize: 10,
                page: 1,
                tableData: [], //角色数据
                total: '', //表格数据总数
                selectData: {}, //下拉数据
                hospDesc: [], //科室下拉
                rowLocKey: '', //点击科室行id
                locDataList: {}, //点击科室行数据
                columns:[],
                modalColumns:[],
                detailWidthTotal: '',
                columnsWidth:'',
                ChineseEnglishSize: [],
                language: JSON.parse(window.sessionStorage.userData),
            }

            this.columns = [
                {
                    key: 1,
                    title: '角色',
                    dataIndex: 'Descripts',
                    align: "center",
                    width: '50%'
                },
                {
                    key: 2,
                    title: '状态',
                    dataIndex: 'states',
                    align: "center",
                    render(states){
                        let config = {
                            '生效': <li style={{listStyle: 'disc', color: 'rgb(66,185,131)'}}>生效</li>,
                            '失效': <li style={{listStyle: 'disc', color: 'rgb(240,65,52)'}}>失效</li>
                        }
                        return config[states];
                    }
                }];
            this.modalColumns = [
                {
                    key: 1,
                    title: '科室',
                    dataIndex: 'locDesc',
                    align: "center",
                },
            ]
        }

        componentDidMount() {
            // 初始化数据
            this.getSelectData();
            this.getTableLeftColumns();
            this.getDetailTableColumns();
        }

        // 获取明系列表头数据
        getDetailTableColumns = () => {
            let {language} = this.state;
            let data = {
                params: [{
                    reactCode: ['RoleRelatedDepartment'],
                    compontName: 'RoleRelatedDepartment',
                    type: 'C',
                }]
            }
            $http.post('urlS', this, {
                code: '01040073',
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        let arr = res.result.C&&res.result.C.length > 0 ? JSON.parse(JSON.stringify(res.result.C)).map((item, index) => {
                            return  {
                                ...item,
                                key: index + 1,
                                title: <div>{language.language== 'EN' ? item.enDescripts : item.title}</div>,
                            }
                        }) : '';
                        let filterArr = arr.filter(function(item){ return item.display === 'Y'});
                        this.setState({columns: filterArr, columnsWidth: res.totalWidth,ChineseEnglishSize:language.language=='EN' ? res.result.language.EN : res.result.language.CN})
                    }
                }
            });
        };

        // 获取右侧列表
        getTableLeftColumns = () => {
            let {language} = this.state;
            let data = {
                params: [{
                    compontName: 'RoleRelatedDepartmentLeft',
                    type: 'C',
                }]
            }
            $http.post('urlS', this, {
                code: '01040073',
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        let arr = res.result.C&&res.result.C.length > 0 ? JSON.parse(JSON.stringify(res.result.C)).map((item, index) => {
                            return  {
                                ...item,
                                key: index + 1,
                                title: <div>{language.language== 'EN' ? item.enDescripts : item.title}</div>,
                            }
                        }) : '';
                        let filterArr = arr.filter(function(item){ return item.display === 'Y'});
                        this.setState({modalColumns: filterArr, detailWidthTotal: res.totalWidth})
                    }
                }
            });
        };

        componentWillUnmount() {
            // 组件销毁前将静止让setState修改state的状态
            this.setState = (state, callback) => { return; }
        }
        // 角色管理下拉框数据
        getSelectData() {
            let data = {
                params: []
            }
            let data2 = {
                params: [{
                    hospID: JSON.parse(window.sessionStorage.userData).hospID
                }]
            }
            $http.post('urlS', this, {
                code: "01040013",
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        this.setState({selectData: res})
                    } else {
                        this.setState({selectData: {}})
                    }
                }
            })
            $http.post('urlS', this, {
                code: "01050029",
                data: data2,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        this.setState({hospDesc: res.result.Data})
                    } else {
                        this.setState({hospDesc: {}})
                    }
                }
            })
        }

        // 查询
        handleQuery = () => {
            this.setState({page: 1, pageSize: 10}, () => {
                this.getTableData();
            })
        }
        // 请求列表数据
        getTableData () {
            this.setState({loading: true});
            let name = this.props.form.getFieldValue('name');
            let PostDr = this.props.form.getFieldValue('PostDr');
            let Status = this.props.form.getFieldValue('Status');
            let { page, pageSize } = this.state;
            let  data = {
                params: [{
                    Descripts: name ? name : undefined,
                    PostDr: PostDr ? PostDr : undefined, // 岗位
                    Status: Status ? Status : undefined, // 记录状态
                }],
                pagination:[{
                    pageSize: pageSize,
                    currentPage: page,
                    sortColumn: "Describe",
                    sortOrder: "asc"
                }]
            }
            $http.post('urlS', this, {
                code: "2101",
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0 && res.result) {
                        for(var i = 0; i < res.result.Data.length; i++) {
                            res.result.Data[i].key = i;
                            if (res.result.Data[i].StopDate === "") {
                                res.result.Data[i].states = "生效";
                            } else {
                                let start = new Date();
                                let end = new Date(res.result.Data[i].StopDate);
                                if (start > end) {
                                    res.result.Data[i].states = "失效";
                                } else {
                                    res.result.Data[i].states = "生效";
                                }
                            }

                        }
                        this.setState({roleListData: res.result.Data, total: res.result.TotalCount, loading: false, locListData: []})
                    } else {
                        this.setState({roleListData: [], total: 0, loading: false})
                    }
                }
            })
        }
        //科室列表
        locDetailData=(id)=>{

            let data = {
                params: [
                    {
                        groupID: id ? id : this.state.rowKey ? this.state.rowKey : undefined
                    }
                ]
            };
            $http.post('urlS', this, {
                code: "3006",
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        this.setState({locListData: res.rows});
                    }
                }
            })
        };

        //保存修改关联科室
        locChangeData=()=>{
                let roleLoc = this.props.form.getFieldValue('roleLoc');
                let checked = this.props.form.getFieldValue('approve');
                let data = {
                    params: [
                        {
                            id: this.state.locDataList.id ? this.state.locDataList.id : undefined,
                            groupID: this.state.rowKey ? this.state.rowKey : undefined,
                            locID: roleLoc ? roleLoc : undefined,
                            defaultFlag: checked ? checked : this.state.locDataList.defaultFlag ? this.state.locDataList.defaultFlag : undefined
                        }
                    ]
                };
                $http.post('urlS', this, {
                    code: "3004",
                    data: data,
                    success: function (res) {
                        if (+res.errorCode === 0) {
                            this.setState({rowLocKey: '', locDataList: {}});
                            // this.props.form.setFieldsValue({'roleLoc': undefined})
                            this.locDetailData();
                        }
                    }
                })
        };
        //删除关联科室
        deleteLocData=()=>{
            let {ChineseEnglishSize} = this.state;
            if(this.state.rowLocKey){
                let data = {
                    params: [
                        {
                            id: this.state.locDataList.id ? this.state.locDataList.id : undefined
                        }
                    ]
                };
                $http.post('urlS', this, {
                    code: "3005",
                    data: data,
                    success: function (res) {
                        if (+res.errorCode === 0) {
                            this.setState({rowLocKey: '',locDataList: {}},()=>{
                                this.locDetailData();
                            });
                        }
                    }
                })
            }else {
                message.error(ChineseEnglishSize.RoleRelatedDepartmentselectDeleteDept ? ChineseEnglishSize.RoleRelatedDepartmentselectDeleteDept.descripts:'请选择删除的科室')
            }

        };

        // 科室表格行的类名
        setLocClassName = (record) => {
            return record.id === this.state.rowLocKey ? 'clickRowStyle' : '';
        };
        // 设置科室行属性
        onClickLoc = (record) => {
            return {
                // 单击行选中
                onClick: (e) => {
                    e.stopPropagation();
                    if (this.state.rowLocKey === '') {
                        // 保存行数据以及ID
                        this.setState({rowLocKey: record.id, locDataList: record});

                    } else {
                        if (this.state.rowLocKey !== record.id) {
                            this.setState({rowLocKey: record.id, locDataList: record});
                        } else {
                            this.setState({rowLocKey: '', locDataList: {}});
                            // this.props.form.setFieldsValue({'approve': undefined})
                        }
                    }
                }
            }
        };
        // 角色表格行的类名
        setRowClassName = (record) => {
            return record.ID === this.state.rowKey ? 'clickRowStyle' : '';
        };
        // 设置角色行属性
        onClickRow = (record) => {
            return {
                // 单击行选中
                onClick: (e) => {
                    e.stopPropagation();
                    if (this.state.rowKey === '') {
                        // 保存行数据以及ID
                        this.setState({rowKey: record.ID},()=>{
                            this.locDetailData(record.ID);
                        });

                    } else {
                        if (this.state.rowKey !== record.ID) {
                            this.setState({rowKey: record.ID},()=>{
                                this.locDetailData(record.ID);
                            });
                        } else {
                            this.setState({rowKey: '', rowLocKey: '', locDataList: {}, locListData: []});
                        }
                    }
                }
            }
        };
        // 页码改变的回调，参数是改变后的页码及每页条数 出库单
        onChange = (page, pageSize) => {
            this.setState({page: page, pageSize: this.state.pageSize}, () => {
                // 重新调用查询方法
                this.getTableData();
            });
        };

        onShowSizeChange = (current, size) => {
            this.setState({page: current, pageSize: size}, () => {
                // 重新调用查询方法
                this.onChange(current,size);
            })
        };
        render() {
            const { getFieldDecorator } = this.props.form;
            let {ChineseEnglishSize,columns,modalColumns,language} = this.state;
            return (
                <div className="roleRelatedLoc">
                    <Col span={14}>
                        <Card
                            size="small"
                            title={<div className="card-title-left-icon"><div></div>{ChineseEnglishSize.RoleRelatedDepartmentSearchTitle ? ChineseEnglishSize.RoleRelatedDepartmentSearchTitle.descripts:'查询条件'}</div>}
                        >
                            <Row>
                                <Col span={19}>
                                    <Form>
                                        <Row>
                                            <Col span={8} >
                                                <Form.Item label={ChineseEnglishSize.RoleRelatedDepartmentroleName ? ChineseEnglishSize.RoleRelatedDepartmentroleName.descripts:'角色名称：'} {...formItemInput}>
                                                    {getFieldDecorator('name', {
                                                        initialValue: undefined,
                                                        rules:[{ required : ChineseEnglishSize.RoleRelatedDepartmentroleName ? ChineseEnglishSize.RoleRelatedDepartmentroleName.required =='Y'? true:false: false, message: ChineseEnglishSize.RoleRelatedDepartmentroleName ? ChineseEnglishSize.RoleRelatedDepartmentroleName.message:'请选择入库科室'}]  
                                                    })(
                                                        <Input placeholder={ChineseEnglishSize.RoleRelatedDepartmententerSearch ? ChineseEnglishSize.RoleRelatedDepartmententerSearch.descripts:'回车可搜索'} onPressEnter={this.handleQuery}/>
                                                    )}
                                                </Form.Item>
                                            </Col>
                                            <Col span={8}>
                                                <Form.Item label={ChineseEnglishSize.RoleRelatedDepartmentPostDr ? ChineseEnglishSize.RoleRelatedDepartmentPostDr.descripts:'岗位：'} {...formItemInput}>
                                                    {getFieldDecorator('PostDr', {
                                                        initialValue: undefined,
                                                        rules:[{ required : ChineseEnglishSize.RoleRelatedDepartmentPostDr ? ChineseEnglishSize.RoleRelatedDepartmentPostDr.required =='Y'? true:false: false, message: ChineseEnglishSize.RoleRelatedDepartmentPostDr ? ChineseEnglishSize.RoleRelatedDepartmentPostDr.message:'请选择岗位'}] 
                                                    })(
                                                        <Select showSearch optionFilterProp="seatchprop" allowClear placeholder={ChineseEnglishSize.RoleRelatedDepartmentPostDrTips ? ChineseEnglishSize.RoleRelatedDepartmentPostDrTips.descripts:'请选择岗位'}>
                                                            {this.state.selectData.post && this.state.selectData.post.map(item => {
                                                                return <Option value={item.id} key={item.id} title={item.descripts} seatchprop={item.descripts}>{item.descripts}</Option>
                                                            })}
                                                        </Select>
                                                    )}
                                                </Form.Item>
                                            </Col>
                                            <Col span={8}>
                                                <Form.Item label={ChineseEnglishSize.RoleRelatedDepartmentStatus ? ChineseEnglishSize.RoleRelatedDepartmentStatus.descripts:'记录状态：'} {...formItemInput}>
                                                    {getFieldDecorator('Status', {
                                                        initialValue: undefined,
                                                    })(
                                                        <Select showSearch allowClear placeholder={ChineseEnglishSize.RoleRelatedDepartmentStatusTips ? ChineseEnglishSize.RoleRelatedDepartmentStatusTips.descripts:'请选择记录状态'} >
                                                            {this.state.selectData.status && this.state.selectData.status.map(item => {
                                                                return <Option value={item.id} key={item.id} title={item.descripts}>{item.descripts}</Option>
                                                            })}
                                                        </Select>
                                                    )}
                                                </Form.Item>
                                            </Col>
                                        </Row>
                                    </Form>
                                </Col>
                                <Col span={5} style={{marginTop: '4px'}}>
                                    <Row >
                                        <Button style={{marginLeft: '20px'}} onClick={this.handleQuery}>{ChineseEnglishSize.RoleRelatedDepartmentsearch ? ChineseEnglishSize.RoleRelatedDepartmentsearch.descripts:'查询'}</Button>
                                    </Row>
                                </Col>
                            </Row>
                        </Card>
                            <Card
                                size="small"
                                title={<div className="card-title-left-icon"><div></div>{ChineseEnglishSize.RoleRelatedDepartmentroleList ? ChineseEnglishSize.RoleRelatedDepartmentroleList.descripts:'角色列表'}</div>}
                            >
                                <div>
                                    <Table
                                        columns={columns.length>0?columns:this.columns}
                                        dataSource={this.state.roleListData}
                                        pagination={false}
                                        bordered
                                        scroll={{ y: store.getState().tableHeight.y - 13 }}
                                        style={{height: (store.getState().tableHeight.y + 27)}}
                                        rowKey={record => record.key}
                                        className="tableDetailHeight"
                                        onRow={this.onClickRow}
                                        rowClassName={this.setRowClassName}
                                    />
                                    <CommonPagination size='small' current={this.state.page} total={this.state.total} search= 'search'
                                    onShowSizeChange={this.onShowSizeChange.bind(this)} complete={true} dataSource={this.state.roleListData}
                                    loading={this.state.loading} onChange={this.onChange.bind(this)} />
                                </div>
                            </Card>
                    </Col>
                    <Col span={10}>
                            <Row>
                                <Card
                                    size="small"
                                    title={<div className="card-title-left-icon"><div></div>{ChineseEnglishSize.RoleRelatedDepartmentmodifyDept ? ChineseEnglishSize.RoleRelatedDepartmentmodifyDept.descripts:'修改科室'}</div>}
                                >
                                    <Col span={10}>
                                        <Form.Item label={ChineseEnglishSize.RoleRelatedDepartmentloc ? ChineseEnglishSize.RoleRelatedDepartmentloc.descripts:'科室'} {...formItemInput}>
                                            {getFieldDecorator('roleLoc', {
                                                initialValue: this.state.locDataList.locID ? this.state.locDataList.locID  : undefined,
                                                rules:[{ required : ChineseEnglishSize.RoleRelatedDepartmentloc ? ChineseEnglishSize.RoleRelatedDepartmentloc.required =='Y'? true:false: false, message: ChineseEnglishSize.RoleRelatedDepartmentloc ? ChineseEnglishSize.RoleRelatedDepartmentloc.message:'请选择岗位'}]  
                                            })(
                                                <Select showSearch optionFilterProp="seatchprop" allowClear style={{width: '100%'}}>
                                                    {this.state.hospDesc.length>0 && this.state.hospDesc.map(item => {
                                                        return <Option value={item.id} key={item.id} title={item.descripts} seatchprop={item.descripts+ '^'+item.descriptsSPCode}>{item.descripts}</Option>
                                                    })}
                                                </Select>
                                            )}
                                        </Form.Item>
                                    </Col>
                                    <Col span={5}>
                                        <Form.Item {...formItemSwitch} label={ChineseEnglishSize.RoleRelatedDepartmentCheck ? ChineseEnglishSize.RoleRelatedDepartmentCheck.descripts:'审核'}>
                                            {getFieldDecorator('approve',{
                                                valuePropName: 'checked',
                                                initialValue: this.state.locDataList.defaultFlag ? this.state.locDataList.defaultFlag : undefined,
                                                rules:[{required: false}]
                                            })(
                                                language.language == 'EN' ?  <Switch checkedChildren="Yes" unCheckedChildren="No" /> : <Switch checkedChildren="是" unCheckedChildren="否" />
                                            ) }
                                        </Form.Item>
                                    </Col>
                                    <Col span={7} style={{marginTop: '4px'}}>
                                        <Button style={{margin: '0 20px'}} onClick={ this.locChangeData}>{ChineseEnglishSize.RoleRelatedDepartmentsave ? ChineseEnglishSize.RoleRelatedDepartmentsave.descripts:'保存'}</Button>
                                        <Button onClick={this.deleteLocData}>{ChineseEnglishSize.RoleRelatedDepartmentdelete ? ChineseEnglishSize.RoleRelatedDepartmentdelete.descripts:'删除'}</Button>
                                    </Col>
                                </Card>
                            </Row>
                            <Row >
                                <Card
                                    size="small"
                                    title={<div className="card-title-left-icon"><div></div>{ChineseEnglishSize.RoleRelatedDepartmentrelatedDept ? ChineseEnglishSize.RoleRelatedDepartmentrelatedDept.descripts:'关联科室'}</div>}
                                >
                                    <div>
                                        <Table
                                            columns={modalColumns.length>0?modalColumns:this.modalColumns}
                                            dataSource={this.state.locListData}
                                            pagination={false}
                                            bordered
                                            scroll={{ y: store.getState().tableHeight.y  - 13 }}
                                            style={{height: (store.getState().tableHeight.y + 65)}}
                                            rowKey={record => record.key}
                                            className="tableDetailHeight"
                                            onRow={this.onClickLoc}
                                            rowClassName={this.setLocClassName}
                                        />
                                        {/*<CommonPagination size='small' current={this.state.page2} total={this.state.detailTotal} search= 'search'*/}
                                        {/*onShowSizeChange={this.onShowSizeChange2.bind(this)} complete={true} dataSource={this.state.detailsListData}*/}
                                        {/*loading={this.state.detailsLoading} onChange={this.onChange2.bind(this)} />*/}
                                    </div>
                                </Card>
                            </Row>
                    </Col>
                </div>
            )
        }
    }
);
export default roleRelatedLoc;