/**
 * 排班权限设置
 */
import React from 'react';
import { Card, Table, Input, Select, Row, Col, Checkbox, Button, Icon, message } from 'antd';
import { $http } from 'containers/config/https';
import ShowRoleModal from './component/ShowRoleModal';
import store from 'store';
import './style/index.less';
import { Util } from 'tools/index';

const Option = Select.Option;

class RoleSettingPage extends React.Component {
    constructor(props) {
        super(props)
        var userData = JSON.parse(sessionStorage.getItem('userData'))
        this.state = {
            dataSource: [],
            total: 0,
            page: 1,
            pageSize: 10,
            userData: userData,
            otherLocList: [],
            locList: [],
            ids: [],
            code: []
        }
    }

    componentDidMount() {
        this.setState({
            otherLocList: [],
            locList: [],
        })
        this.initData()
        this.loadSchedulingTitleType()
    }

    loadSchedulingTitleType() {
        var params = {
            params: [{
                // hospitalId:this.state.userData.hospDr,
                hospID: this.state.userData.hospID,
                active: 'Y'
            }]
        }
        $http.post('urlDeault', this, {
            code: "01040160",
            data: params,
            success: function (res) {
                if (res.errorCode === '0') {
                    var data = res.result.data;
                    var resourceTypeID = ''
                    if (!Util.isEmpty(data)) {
                        resourceTypeID = data[0].id
                    }
                    this.setState({
                        resourceType: res.result.data,
                        resourceTypeID: resourceTypeID
                    })
                }
            }
        });
    }

    initData() {
        this.columns = [
            {
                title: '科室代码',
                dataIndex: 'code',
                width: 100,
                align: 'center',
            }, {
                title: '科室名称',
                dataIndex: 'descripts',
                width: 250,
                align: 'center',
            }, {
                title: '编辑排班权限',
                dataIndex: 'modelFlag',
                width: 100,
                align: 'center',
                render: (text, data, index) => {
                    return <Checkbox checked={data.modelFlag == 'Y' ? true : false}
                        onChange={this.checkLeftModelFlag.bind(this, 'modelFlag', index)} />
                }
            }, {
                title: '生成排班权限',
                dataIndex: 'examineFlag',
                width: 100,
                align: 'center',
                render: (text, data, index) => {
                    return <Checkbox checked={data.examineFlag == 'Y' ? true : false}
                        onChange={this.checkLeftModelFlag.bind(this, 'examineFlag', index)} />
                }
            }
        ];
        this.rightColumn = [
            {
                title: '科室代码',
                dataIndex: 'locCode',
                width: 200,
                align: 'center',
            }, {
                title: '科室名称',
                dataIndex: 'locDesc',
                width: 200,
                align: 'center',
            }, , {
                title: '编辑排班权限',
                dataIndex: 'modelFlag',
                width: 120,
                align: 'center',
                render: (text, data, index) => {
                    return <Checkbox checked={data.modelFlag == 'Y' ? true : false}
                        onChange={this.checkRightModelFlag.bind(this, 'modelFlag', index)} />
                }
            }, {
                title: '生成排班权限',
                dataIndex: 'examineFlag',
                width: 120,
                align: 'center',
                render: (text, data, index) => {
                    return <Checkbox checked={data.examineFlag == 'Y' ? true : false}
                        onChange={this.checkRightModelFlag.bind(this, 'examineFlag', index)} />
                }
            }, {
                title: '设置',
                dataIndex: 'num2',
                width: 120,
                align: 'center',
                render: (text, data) => {
                    return <span onClick={this.handleShowRoleModal.bind(this, data.id)}
                        style={{ cursor: 'pointer', color: '#1890ff' }}>设置</span>
                }
            }
        ]
    }

    checkLeftModelFlag(name, index, e) {
        this.state.otherLocList[index][name] = e.target.checked ? 'Y' : 'N'
        this.state.otherLocList[index]['checkStatus'] = '1'
        this.setState({})
    }

    checkRightModelFlag(name, index, e) {
        this.state.locList[index][name] = e.target.checked ? 'Y' : 'N'
        this.state.locList[index]['checkStatus'] = '1'
        this.setState({})
    }

    loadData() {
        var params = {
            params: [{
                userID: this.state.selectID,
                logonGroupID: this.state.userData.groupID,
                logonHospID: this.state.userData.hospID,
                searchCodeL: this.state.searchCodeL,
                searchCodeR: this.state.searchCodeR,
                resourceTypeID: this.state.resourceTypeID
            }]
        }
        $http.post('urlDeault', this, {
            code: "03010011",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    this.setState({
                        locList: res.data.locList,
                        otherLocList: res.data.otherLocList,
                    })
                }
            }
        });
    }

    loadScheduling(value) {
        var params = {
            params: [{
                // userID: '60',//this.state.userData.userID,
                // logonGroupID: this.state.userData.groupID,
                // logonHospID: this.state.userData.hospID,
                userActive: 'Y',
                searchCode: value,
                resourceTypeID: this.state.resourceTypeID
            }]
        }
        $http.post('urlDeault', this, {
            code: "01040015",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    this.setState({
                        selectData: res.result.Data
                    })
                }
            }
        });
    }

    changeScheduling(e) {
        this.setState({
            selectID: e
        }, () => {
            this.loadData()
        })
    }

    handleShowRoleModal(data) {
        this.setState({
            isShowRoleModal: true,
            modalId: data
        })
    }

    handleSearch(value) {
        if (value.length >= 2) {
            this.loadScheduling(value)
        }
    }

    handleKeyDown(name, e) {
        if (e.keyCode == '13') {
            this.loadData()
        }
    }

    onSelectChange(ids) {
        this.setState({
            ids
        })
    }

    onSelectRightChange(code) {
        this.setState({
            code
        })
    }

    addSchedulingMsg() {
        var { ids, otherLocList } = this.state;
        if (Util.isEmpty(ids)) {
            message.error('请选择您需要添加的数据！')
            return
        }
        var dataSource = []
        for (var i = 0; i < ids.length; i++) {
            for (var j = 0; j < otherLocList.length; j++) {
                /**
                 * @ByShizi: 排班权限设置右移后默认勾选全部的编辑和生成排版权限且自动保存
                 * Create: 2023-04-18
                 * 需求: 1221
                 * */
                if (ids[i] == otherLocList[j].id) {
                    dataSource.push({
                        locID: ids[i],
                        modelFlag: 'Y',
                        examineFlag: 'Y',
                        // modelFlag: otherLocList[j].modelFlag,
                        // examineFlag: otherLocList[j].examineFlag,
                    })
                }
            }
        }
        var params = {
            params: [{
                userID: this.state.selectID,
                logonUserID: this.state.userData.userID,
                logonHospID: this.state.userData.hospID,
                // locID: this.state.ids
                addData: dataSource,
                resourceTypeID: this.state.resourceTypeID
            }]
        }
        $http.post('urlDeault', this, {
            code: "03010012",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    message.success('添加成功')
                    this.loadData()
                    this.setState({
                        ids: []
                    })
                }
            }
        });
    }

    deleteLocMsg() {
        var params = {
            params: [{
                logonUserID: this.state.userData.userID,
                id: this.state.code,
                resourceTypeID: this.state.resourceTypeID
            }]
        }
        $http.post('urlDeault', this, {
            code: "03010013",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    message.success('删除成功')
                    this.loadData()
                    this.setState({
                        code: []
                    })
                }
            }
        });
    }

    saveRightData() {
        var { code, locList } = this.state;
        if (Util.isEmpty(code)) {
            message.error('请选择您需要添加的数据！')
            return
        }
        var dataSource = []
        for (var i = 0; i < code.length; i++) {
            for (var j = 0; j < locList.length; j++) {
                // && !Util.isEmpty(locList[j].checkStatus)
                if (code[i] == locList[j].id) {
                    dataSource.push({
                        id: code[i],
                        modelFlag: locList[j].modelFlag,
                        examineFlag: locList[j].examineFlag,
                    })
                }
            }
        }
        var params = {
            params: [{
                logonUserID: this.state.userData.userID,
                // id: this.state.code
                updateData: dataSource,
                resourceTypeID: this.state.resourceTypeID
            }]
        }
        $http.post('urlDeault', this, {
            code: "03010017",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    message.success('修改成功')
                    this.loadData()
                    this.setState({
                        code: []
                    })
                }
            }
        });
    }

    //隐藏弹出框
    hideModal(name) {
        this.setState({
            [name]: false,//将所有参数置为false
        });
    }

    changeRecorceType(data) {
        this.setState({
            resourceTypeID: data.id
        })
    }

    render() {
        var { selectData, ids, code } = this.state;
        const rowSelection = {
            ids,
            onChange: this.onSelectChange.bind(this),
            selectedRowKeys: ids,
        }
        const rightRowSelection = {
            code,
            onChange: this.onSelectRightChange.bind(this),
            selectedRowKeys: code,
        }
        var selectDataOption = []
        selectData && selectData.map((item, index) => {
            selectDataOption.push(<Option key={index} value={item.userID}>{item.userDesc}</Option>)
        })
        var resourceTypeOption = []
        this.state.resourceType && this.state.resourceType.map((item, index) => {
            resourceTypeOption.push(<Button key={index} value={item.id} size="large" style={{ marginRight: 5 }}
                className={item.id == this.state.resourceTypeID ? 'resource-btn-bgd' : ''}
                onClick={this.changeRecorceType.bind(this, item)}>{item.descripts}</Button>)
        })
        return <div className='role-manager-body'>
            {/**科室弹框 */}
            <ShowRoleModal isShow={this.state.isShowRoleModal}
                modalId={this.state.modalId}
                resourceType={this.state.resourceType}
                resourceTypeID={this.state.resourceTypeID}
                onHide={this.hideModal.bind(this, 'isShowRoleModal')}>
            </ShowRoleModal>
            <div className='scheduling-broad-title'>
                <Card>
                    {resourceTypeOption}
                </Card>
            </div>
            <Card style={{ height: '10%' }}>
                <Row gutter={40}>
                    <Col span={6}>
                        排班人员：<Select placeholder='请输入工号/姓名/拼音查询' style={{ width: 260 }} showSearch
                            onSearch={this.handleSearch.bind(this)}
                            defaultActiveFirstOption={false}
                            showArrow={false}
                            filterOption={false}
                            onChange={this.changeScheduling.bind(this)}>{selectDataOption}</Select>
                    </Col>
                </Row>
            </Card>

            <Card style={{ marginTop: 5, height: '89%' }}>
                <div style={{ display: 'flex', height: '100%' }}>
                    <div style={{ width: '48%' }}>
                        <Table columns={this.columns} dataSource={this.state.otherLocList}
                            scroll={{ x: 550, y: store.getState().tableHeight.y - 50 }}
                            rowSelection={rowSelection}
                            rowKey={(data) => {
                                return data.id
                            }}
                            title={() => {
                                return <div>
                                    <Input placeholder='输入科室代码/名称回车键查询' style={{ width: 220 }}
                                        onChange={Util.commonInputChange.bind(this, 'searchCodeL')}
                                        onKeyDown={this.handleKeyDown.bind(this, 'searchCodeL')} />
                                </div>
                            }}
                            bordered pagination={false}></Table>
                    </div>
                    <div><Icon type='right-circle' theme="filled" style={{ marginLeft: 10, fontSize: 30, cursor: 'pointer', marginTop: 75 }}
                        onClick={this.addSchedulingMsg.bind(this)} /></div>
                    <div style={{ width: '48%', marginLeft: 10 }}>
                        <Table columns={this.rightColumn} dataSource={this.state.locList}
                            rowSelection={rightRowSelection}
                            rowKey={(data) => {
                                return data.id
                            }}
                            scroll={{ x: 860, y: store.getState().tableHeight.y - 50 }}
                            title={() => {
                                return <div style={{ display: 'flex' }}>
                                    <Input placeholder='输入科室代码/名称回车键查询' style={{ width: 220 }}
                                        onChange={Util.commonInputChange.bind(this, 'searchCodeR')}
                                        onKeyDown={this.handleKeyDown.bind(this, 'searchCodeR')} />
                                    <Button style={{ marginLeft: '40%' }} onClick={this.deleteLocMsg.bind(this)}>删除</Button>
                                    <Button style={{ marginLeft: 10 }} onClick={this.saveRightData.bind(this)}>保存</Button>
                                </div>
                            }}
                            bordered pagination={false}></Table>
                    </div>
                </div>
            </Card>
        </div>
    }
}

export default RoleSettingPage;