// 登陆科室
import React from 'react';
import { Form, Row, Col, Select, Table, DatePicker, Switch, Tooltip, Button, Icon, message, Popconfirm, Divider, } from 'antd';
import { $http } from '../../../containers/config/https';
import { Util } from '../../../tools';
import Moment from 'moment';
import '.././style/index.less';
import store from '../../../store';
import DatePickerFormat from '../../../components/datePicker/DatePickerFormat';

const { Option } = Select;

const formItemLayout = {    // label 和input宽度
    labelCol: { span: 4 },
    wrapperCol: { span: 19 },
};


const formItemLayout2 = {    // label 和input宽度
    labelCol: { span: 10 },
    wrapperCol: { span: 14 },
};

const formItemLayout3 = {    // label 和input宽度
    labelCol: { span: 8 },
    wrapperCol: { span: 14 },
};

class LandingDepartment extends React.Component {
    constructor(props) {
        super(props)

        //登陆科室table
        this.columnsDep = [{
            title: '允许登陆医院',
            dataIndex: 'logonHospDesc',
            align: "center",
            key: '1',
            width: 200,
        }, {
            title: '允许登陆科室',
            dataIndex: 'logonLocDesc',
            align: "center",
            key: '2',
            width: 200,
        }, {
            title: '允许登陆角色',
            dataIndex: 'logonGroupDesc',
            align: "center",
            key: '3',
            width: 150,
        }, {
            title: '截止日期',
            dataIndex: 'endDate',
            align: "center",
            key: '4',
            width: 150,
        }, {
            title: '是否默认',
            dataIndex: 'isDefault',
            align: "center",
            key: '5',
            width: 100,
            render(isDefault) {
                let config = {
                    'Y': '是',
                    'N': '否'
                }
                return config[isDefault];
            }
        }, {
            title: '操作',
            dataIndex: 'name',
            align: "center",
            key: '6',
            width: 150,
            render: (text, record) => (
                <span>
                    {parseInt(record.safeRank) >= parseInt(this.state.userSafeRank) ? '' :
                        <div>
                            <Icon type="edit" style={{ color: '#108EE9' }}></Icon>
                            <span className='span' onClick={() => this.handleCompile(record)}>编辑</span>
                            {/* 分割线 */}
                            <Divider type="vertical" />
                            <Icon type="delete" style={{ color: 'rgba(240,65,52,1)' }}></Icon>
                            <Popconfirm title="删除不可恢复，你确定要删除吗?" onConfirm={() => this.dataDepDel(record)} >
                                <span className='span' style={{ color: 'rgba(240,65,52,1)' }}>删除</span>
                            </Popconfirm>
                        </div>}


                </span>
            ),
        }]

        this.state = {
            hospitalData: [], // 医院集合
            groupData: [], // 角色集合
            deptDrData: [], // 科室集合
            dataDep: [], // 科室table数据
            logonLocId: '',   // 人员登录科室主键
            isDefault: 'N',   // 默认
            defaultHos: JSON.parse(window.sessionStorage.userData).hospID,   // 医院
            userID: '',// 用户主键
            userSafeRank: '',   // 角色级别
        }
    }

    componentDidMount() {
        this.props.onRef(this)
        // 医院列表加载
        this.searachHospDr()

        // 角色列表加载
        this.searachGroup()

        // 科室加载
        this.hospDrChange(this.state.defaultHos)


        this.callback()

    }

    callback = () => {

        if (this.props.userID) {
            this.setState({
                userID: this.props.userID, //  用户主键
            }, () => {
                // 科室table数据回显示
                this.deptAry()
            })
        }

        if (store.getState().userRedux.userID && store.getState().userRedux.userID !== '') {

            this.setState({
                userID: store.getState().userRedux.userID, //  用户主键
            }, () => {
                // 科室table数据回显示
                this.deptAry()
            })
        }
    }

    // 医院列表加载
    searachHospDr = () => {
        let user = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
        var data = {
            params: [{
                hospID: '', // 医院id
                logonGroupID: user.groupID, //登录角色id
                logonHospID: user.hospID, // 登录医院id
            }]
        }

        $http.post('urlS', this, {
            code: "01040001",
            data: data,
            success: function (res) {
                let errorCode = res.errorCode;
                if (errorCode === '0') {
                    this.setState({
                        hospitalData: res.depDoctor, //  医院列表
                    })
                }
            }
        });
    }

    // 角色列表加载
    searachGroup = () => {
        let data = {
            "params": [
                {
                    code: '',
                }
            ]
        };
        $http.post('urlS', this, {
            code: "01040038",
            data: data,
            success: function (res) {
                let errorCode = res.errorCode;
                if (errorCode === '0') {
                    this.setState({
                        groupData: res.result, // 角色列表
                    })
                }
            }
        });
    }

    // 医院切换
    hospDrChange = (value) => {
        this.props.form.setFieldsValue({
            locId: '',
        });

        this.setState({
            deptDrData: [], //清空下拉框
        })

        if (!value) {
            return false
        }

        let data = {
            "params": [{
                hospID: value,
            }]
        };
        $http.post('urlDeault', this, {
            code: "04020008",
            data: data,
            success: function (res) {
                let errorCode = res.errorCode;
                if (errorCode === '0') {
                    this.setState({
                        deptDrData: res.result.Data, // 科室集合
                    })
                }
            }
        });
    }

    deptAry = () => {   // 回显科室
        // 回显科室

        if (this.state.userID && this.state.userID !== '') {
            let data = {
                "params": [{
                    userID: this.state.userID,
                    groupID: JSON.parse(window.sessionStorage.userData).groupID,
                    power:"getGroup"
                }],
                "session":[{
                    "loginIp": window.location && window.location.protocol && window.location.host ? (window.location.host.split(":")[0]) : (window.location && window.location.origin ?
                        (window.location.origin.split(":")[0]+window.location.origin.split(":")[1]).split("//")[1] : "")
                }]
            };

            $http.post('urlS', this, {
                code: "01040043",
                data: data,
                success: function (res) {
                    let errorCode = res.errorCode;
                    if (errorCode === '0') {
                        let dataDep = []
                        res.result.logonLocAry.map((item, i) => { //回显科室数组
                            const newData = {
                                key: i,
                                logonLocId: item.logonLocLogID,
                                logonHospDr: item.logonHospID,
                                logonHospDesc: item.logonHospDesc,
                                logonLocDr: item.logonLocID,
                                logonLocDesc: item.logonLocDesc,
                                logonGroupDr: item.logonGroupID,
                                logonGroupDesc: item.logonGroupDesc,
                                isDefault: item.logLocIsDefault,
                                sTDate: item.logLocStartDate,
                                endDate: item.logLocEndDate,
                                safeRank: item.userSafeRank,
                            };
                            dataDep.push(newData)
                        })
                        this.setState({
                            dataDep: dataDep,   // 回显科室数组table数据
                            userSafeRank: res.userSafeRank,   // 角色级别
                        });
                    }
                }
            });
        }


    }


    // 编辑
    handleCompile = (record) => {
        if (parseInt(record.safeRank) >= parseInt(this.state.userSafeRank)) {
            return false;
        }
        this.hospDrChange(record.logonHospDr)
        this.props.form.setFieldsValue({
            hospId: record.logonHospDr,
            locId: record.logonLocDr,
            groupId: record.logonGroupDr.toString(),
            isDefault: record.isDefault === 'Y' ? true : false,
            sTDate: record.sTDate !== '' ? Moment(record.sTDate, 'YYYY-MM-DD') : undefined,
            endDate: record.endDate !== '' ? Moment(record.endDate, 'YYYY-MM-DD') : undefined,
        });



        this.setState({
            logonLocId: record.logonLocId,
        });



    }

    // 清空表单
    handleClone = () => {
        this.props.form.resetFields();

        this.setState({
            logonLocId: '',
        });


    }

    // 删除科室
    dataDepDel = (record) => {
        if (parseInt(record.safeRank) >= parseInt(this.state.userSafeRank)) {
            return false;
        }

        let data = {
            "params": [{
                updateUserID: JSON.parse(window.sessionStorage.userData).userID,
                logonLocDeletion: [{
                    logonLocLogID: record.logonLocId,
                    logonLocHospID: record.logonHospDr,
                    logonLocID: record.logonLocDr.toString(),
                    logonLocGroupID: record.logonGroupDr
                }]
            }]
        };
        $http.post('urlADS', this, {
            code: "01040040",
            data: data,
            success: function (res) {
                let errorCode = res.errorCode;
                if (errorCode === '0') {
                    message.success(res.errorMessage);
                    this.deptAry() // 回显列表
                }
            }
        });
    }

    // table行样式
    setRowClassName = (record) => {
        return parseInt(record.safeRank) >= parseInt(this.state.userSafeRank) ? 'disabledTable' : '';
    }

    // 保存用户信息表单提交
    handleSubmit = (e) => {
        e.preventDefault();

        this.props.form.validateFields((err, values) => {
            if (!err) {  //!err

                let data = {
                    "params": [{
                        "interObj": {
                            "userID": this.state.userID || "",
                            "updateUserID": JSON.parse(window.sessionStorage.userData).userID || "",
                        },
                        "logonLocAry": [{
                            "logonLocLogID": this.state.logonLocId || "",
                            "logonLocHospID": values.hospId || '',
                            "logonLocID": values.locId || '',
                            "logonLocGroupID": values.groupId || '',
                            "logonLocStartDate": values.sTDate ? Moment(values.sTDate).utcOffset(480).format('YYYY-MM-DD') : '',
                            "logonLocEndDate": values.endDate ? Moment(values.endDate).utcOffset(480).format('YYYY-MM-DD') : '',
                            'logonLocIsDefault': Util.replaceTrueFalse(values.isDefault) || '',
                        }],
                        "defaultLogLoc": Util.replaceTrueFalse(values.isDefault) || '',

                    }]
                };
                $http.post('urlADS', this, {
                    code: "01040037",
                    data: data,
                    success: function (res) {
                        let errorCode = res.errorCode;
                        if (errorCode === '0') {
                            message.success(res.errorMessage);
                            this.deptAry() // 回显列表
                            this.handleClone() // 清空表单
                        }
                    }
                });
            }

        });
    }

    render() {
        const { getFieldDecorator } = this.props.form;
        return (
            <div style={{ padding: 24,paddingBottom:'0' }}>
                <Form layout="vertical" className="userForm" onSubmit={this.handleSubmit}  >
                    <Row>
                        <Col span={16}>
                            <Form.Item label="允许登陆医院" {...formItemLayout} >
                                {getFieldDecorator('hospId', {
                                    initialValue: this.state.defaultHos,
                                    rules: [{ required: true, message: '请输入允许登陆医院' }],
                                })(
                                    <Select showSearch allowClear optionFilterProp="title1" onChange={(event) => { this.hospDrChange(event) }} placeholder="允许登陆医院" >
                                        {this.state.hospitalData.map(item => <Option title={item.descripts} title1={item.descripts + '^' + item.descriptsSPCode} key={item.id} value={item.id}  >{item.descripts}</Option>)}
                                    </Select>
                                )}
                            </Form.Item>
                        </Col>
                    </Row>
                    <Row>
                        <Col span={16}>
                            <Form.Item label="允许登录科室" {...formItemLayout} >
                                {getFieldDecorator('locId', {
                                    initialValue: '',
                                    rules: [{ required: true, message: '请输入允许登录科室' }],
                                })(
                                    <Select showSearch allowClear placeholder="允许登录科室" optionFilterProp="title1" >
                                        {this.state.deptDrData.map(item => <Option title={item.descripts} title1={item.descripts + '^' + item.descriptsSPCode} key={item.id} value={item.id}  >{item.descripts}</Option>)}
                                    </Select>
                                )}
                            </Form.Item>
                        </Col>
                    </Row>
                    <Row>
                        <Col span={16}>
                            <Form.Item label="允许登录角色" {...formItemLayout} >
                                {getFieldDecorator('groupId', {
                                    initialValue: '',
                                    rules: [{ required: true, message: '请输入允许登录角色' }],
                                })(
                                    <Select showSearch allowClear placeholder="允许登录角色" optionFilterProp="title1" >
                                        {this.state.groupData.map(item => <Option title={item.descripts} title1={item.descripts + '^' + item.descriptsSPCode} key={item.id} value={item.id}  >{item.descripts}</Option>)}
                                    </Select>
                                )}
                            </Form.Item>
                        </Col>
                    </Row>
                    <Row>
                        <Col span={8}>
                            <Form.Item className="dpW100" label="生效日期"  {...formItemLayout3} >
                                {getFieldDecorator('sTDate', {
                                    rules: [{ required: true, message: '请输入生效日期' }],
                                    initialValue: Moment(Moment().format('L'), 'YYYY-MM-DD'),
                                })(
                                    <DatePickerFormat />
                                )}
                            </Form.Item>
                        </Col>
                        <Col span={6}>
                            <Form.Item className="dpW100" label="失效日期"  {...formItemLayout3}  >
                                {getFieldDecorator('endDate', {
                                    initialValue: undefined,
                                })(
                                    <DatePickerFormat />
                                )}
                            </Form.Item>
                        </Col>
                    </Row>
                    <Row>
                        <Col span={16} >
                            <Col offset={4} >
                                <Tooltip placement="right" title="默认科室是唯一的" trigger='hover'>
                                    <div style={{ width: '200px', height: '30px' }} >
                                        <Form.Item label="设为默认" style={{ width: '200px', padding: '0', height: '30px' }} {...formItemLayout2}>
                                            {getFieldDecorator('isDefault', {
                                                valuePropName: 'checked',
                                                initialValue: this.state.isDefault === "Y" ? true : false,
                                            })(
                                                <Switch checkedChildren="是" unCheckedChildren="否" />
                                            )}
                                        </Form.Item>

                                    </div>
                                </Tooltip>
                            </Col>
                        </Col>

                    </Row>
                    <Row >
                        <Col span={16}>
                            <Row style={{ width: '100%', textAlign: 'center', marginBottom: '10px' }}>
                                <Button onClick={this.handleSubmit} style={{ marginRight: '30px', background: 'rgba(66,185,131,1)', color: '#fff' }}>保存</Button>
                                <Button onClick={this.handleClone} style={{ color: '#000' }}>清空</Button>
                            </Row>
                        </Col>

                    </Row>
                </Form>
                <Row>
                    <Col span={24}>
                        <Table
                            bordered
                            dataSource={this.state.dataDep}
                            columns={this.columnsDep}
                            pagination={false}
                            onRow={(record) => {
                                return {
                                    onDoubleClick: (event) => {
                                        this.handleCompile(record)
                                    },
                                };
                            }}
                            scroll={{ x: 950, y: 310 }}
                            rowClassName={this.setRowClassName}
                        />
                    </Col>
                </Row>
            </div >
        );
    }
}

const LandingDepartmentFrom = Form.create()(LandingDepartment);

export default LandingDepartmentFrom
