// 用户信息
import React from 'react';
import { Select, Input, Row, Col, Button, Spin, message, Icon, Tabs, Modal, Checkbox } from 'antd';
import { $http } from 'containers/config/https';
import store from 'store';
import PubilcTablePagination from '../common/PubilcTablePagination.jsx'; // 公共table组件
import NewUser from './NewUser'; // 用户信息
import UserListUser from './common/UserListUser'; // 用户列表
import UserListGroup from './common/UserListGroup'; // 用户列表
import UserListLoc from './common/UserListLoc'; // 用户列表
import UserListLocT from './common/UserListLocT'; // 用户列表
import UserListMan from './common/UserListMan'; // 用户列表
import UserListZc from './common/UserListZc'; // 用户列表
import UserListZh from './common/UserListZh'; // 用户列表

// 组件const
const { Option } = Select;
const { TabPane } = Tabs;

export default class UserList extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            code: '',  //用户工号
            descripts: '',  //用户姓名
            credTypeId: '', //证件类型
            credNo: '', //证件号码
            phoneNumber: "",//手机号码
            active: 'Y', //状态
            // 表格数据
            tableData: [],
            // 表格数据总条数
            total: 0,
            showLoading: true,
            page: 1,
            pageSize: 20,
            defaultActiveKey: '1',
            modaltitle: '新增用户',
            modaltitleVis: false,
            paras: {},
            userSearch: {},
            languageData: {}, // 国际化语言包
            language: {},   // 国际化语言
            languageCode: JSON.parse(window.sessionStorage.userData).language, // 国际化语言标识
            columns: [],
            numFlag: false,
            loading: false,
            selectData: {},
            userType: '', // 人员类型
        };
    }

    componentDidMount() {
        // 初始化列表数据
        this.handleQuery()
        // 组件加载完毕关闭loading
        this.setState({ showLoading: false })
        // 初始化证件类型列表数据
        this.credTypeList()
        this.ordList1() //费用类型table
    }

    componentWillUnmount() {
        // 组件销毁前将静止让setState修改state的状态
        this.setState = (state, callback) => { return; }
    }

    // 费用类型table
    ordList1 = () => {
        let data = {
            params: [{
                "reactCode": ["userInformationUserList"],
                "compontName": "userInformationUserList",
                "type": "C"

            }]
        }
        $http.post('urlS', this, {
            code: "01040073",
            data: data,
            success: function (res) {
                let errorCode = res.errorCode;
                if (errorCode === '0') {
                    this.setState({
                        columns: res.result.C || {},  // 国际化Table2
                        languageData: res.result.language || {},  // 国际化语言包
                    }, () => {
                        this.LanCNEN(this.state.languageCode)
                        this.cloumData1(this.state.columns)
                        this.listAdd(this.state.languageCode)
                    })
                }
            }
        });
    }

    LanCNEN = (code) => {
        let { languageData } = this.state
        this.setState({
            language: languageData[code]
        })
    }

    // 数据配置
    cloumData1(resC) {

        let { languageCode } = this.state
        for (var i = 0; i < resC.length; i++) {
            resC[i].key = i;
        }
        if (languageCode === "EN") {
            resC.map((item, i) => {
                item.title = item.enDescripts
            })
        }

        if (languageCode === "CN") {
            resC.map((item, i) => {
                item.title = item.descripts
            })
        }

        this.setState({
            columnsPatChar: resC, // 费用类型table
        });
    }

    //render 自定义项目名称
    listAdd = (languageCode) => {
        let { columns } = this.state
        columns.push({
            title: languageCode === 'CN' ? '操作' : 'operation',
            key: 'operation',
            align: "center",
            width: 100,
            fixed: 'right',
            render: (text, record) => (
                <span>
                    <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.handleDelete(record)} >
                            <span className='span' style={{ color: 'rgba(240,65,52,1)' }}>删除</span>
                        </Popconfirm> */}
                </span>
            ),
        })
        this.setState({})
    }

    // 调用公共组件的连接事件
    onRef = (ref) => {
        this.child = ref
    }

    // 调用公共组件的连接事件
    onRef2 = (ref) => {
        this.child2 = ref
    }

    // 调用公共组件的连接事件
    onRef3 = (ref) => {
        this.child3 = ref
    }

    // 调用公共组件的连接事件
    onRef4 = (ref) => {
        this.child4 = ref
    }

    // 调用公共组件的连接事件
    onRef5 = (ref) => {
        this.child5 = ref
    }

    // 调用公共组件的连接事件
    onRef6 = (ref) => {
        this.child6 = ref
    }

    // 调用公共组件的连接事件
    onRef7 = (ref) => {
        this.child7 = ref
    }

    // 调用公共组件的连接事件
    onRef8 = (ref) => {
        this.child8 = ref
    }

    // 提供修改page和pageSize的回调函数
    compilePage(page, pageSize) {
        // 修改page，或者pageSize
        this.setState({ page: page, pageSize: pageSize }, () => {
            // 重新调用查询方法
            this.handleQuery();
        })
    }

    // 回车查询
    handleKeydown = (e) => {
        if (e.keyCode === 13) {
            this.search() // 查询
        }
    }

    // 查询
    search = (e) => {
        this.setState({ page: 1, pageSize: 20 }, () => {
            // 初始化列表数据
            this.handleQuery()
        })
    }

    // 查询条件 --- 用户工号
    onChangeCode = (e) => {
        this.setState({ code: e.target.value });
    }

    // 查询条件 --- 用户姓名
    onChangeDescripts = (e) => {
        this.setState({ descripts: e.target.value });
    }

    // 查询条件 --- 证件类型
    onChangeCredType = (e) => {
        this.setState({ credTypeId: e });
    }

    // 查询条件 --- 证件号码
    onChangeCredNo = (e) => {
        this.setState({ credNo: e.target.value });
    }

    // 查询条件 --- 手机号码
    onChangePhone = (e) => {
        this.setState({ phoneNumber: e.target.value });
    }

    // 查询条件 --- 状态
    onChangeActive = (e) => {
        this.setState({ active: e }, () => {
            this.handleQuery();
        });
    }

    // 编辑用户
    handleCompile = (record) => {
        this.setState({
            modaltitle: '编辑用户',
            modaltitleVis: true,
            paras: {
                userInfo: record, //用户数据
            }
        })
    }

    handleCancel = () => {
        this.setState({
            modaltitleVis: false,
        })
    }

    // 删除用户
    handleDelete = (record) => {
        let data = {
            params: [{
                userID: record.userID,
                updateUserID: JSON.parse(window.sessionStorage.userData).userID,
            }]
        };
        $http.post('urlADS', this, {
            code: "01040017",
            data: data,
            success: function (res) {
                let errorCode = res.errorCode;
                if (errorCode === '0') {
                    message.success(res.errorMessage);
                    this.handleQuery() // 查询
                }
            }
        });
    }

    // 证件类型加载
    credTypeList = () => {
        let data = {
            "params": [{
                code: '',
            }]
        };

        $http.post('urlS', this, {
            code: "01040036",
            data: data,
            success: function (res) {
                let errorCode = res.errorCode;
                if (errorCode === '0') {
                    this.setState({
                        selectData: res,
                    })
                }
            }
        });
    }

    // 查询
    handleQuery = () => {
        let { defaultActiveKey, numFlag, userType } = this.state;
        let userSearch = {
            hospID: JSON.parse(window.sessionStorage.userData).hospID,
            userCode: this.state.code || '',
            userDesc: this.state.descripts || '',
            userCredTypeID: this.state.credTypeId || '',
            userCredNo: this.state.credNo || '',
            userActive: this.state.active || '',
            userMobile: this.state.phoneNumber || "",
            numFlag: numFlag ? 'Y' : 'N',
            userType, // 人员类型
        }
        this.setState({
            userSearch: userSearch || {}
        }, () => {
            switch (defaultActiveKey) {
                case '1':
                    this.query()  // 本页面查询
                    break;
                case '2':
                    this.child2.table2(this.state.userSearch)  // 医院人员 本页面查询
                    break;
                case '3':
                    this.child3.table2(this.state.userSearch)   //按登录科室 本页面查询
                    break;
                case '4':
                    this.child4.table2(this.state.userSearch)   //按分配科室 本页面查询
                    break;
                case '5':
                    this.child5.table2(this.state.userSearch)   //按角色 本页面查询
                    break;
                case '6':
                    this.child6.table2(this.state.userSearch)  // 按人员类型 本页面查询
                    break;
                case '7':
                    this.child7.table2(this.state.userSearch)   //按职称 本页面查询
                    break;
                case '8':
                    this.child8.table2(this.state.userSearch)  //按专长 本页面查询
                    break;

                default:
                    break;
            }
        })
    }

    // 本页面查询
    query = () => {
        this.setState({ loading: true });
        let { page, pageSize } = this.state;
        let data = {
            params: [this.state.userSearch],
            pagination: [{
                pageSize: pageSize,
                currentPage: page,
                sortColumn: 'code',
                sortOrder: 'asc'
            }]
        };
        $http.post('urlS', this, {
            code: "01040015",
            data: data,
            success: function (res) {
                let errorCode = res.errorCode;
                if (errorCode === '0') {
                    for (var i = 0; i < res.result.Data.length; i++) {
                        res.result.Data[i].key = i;
                    }
                    this.setState({
                        loading: false,
                        tableData: res.result.Data,
                        total: res.result.TotalCount,
                        // page: 1,
                    })
                } else {
                    this.setState({
                        loading: false,
                        tableData: [],
                        total: 0,
                        // page: 1,
                    })
                }
            },
            error: () => {
                this.setState({ loading: false });
            }
        });
        // 数据加载成功关闭loading
        this.child.handleLoading()
    }

    // 新增科室跳转到新增界面
    handleAdd = () => {
        this.setState({
            modaltitle: '新增用户',
            modaltitleVis: true,
            paras: {},
        })
        // // 点击跳转导航栏新加新增角色
        // this.props.openWindowBySubTab({
        //     title: '新增用户',
        //     path: '/6012/001',
        //     Paras: {
        //         targetKey: '新增用户',
        //     },
        //     component: "pages/userInformation/NewUser.jsx"
        // });
    }

    /**
     * @ByLiuDan: 新增导出功能
     * Create 2023-3-30
     */
    exportExcel = () => {
        const params = [{
            hospID: JSON.parse(window.sessionStorage.userData).hospID,
        }];
        this.state.columns.map((v) => {
            if (v.code) {
                params.push({
                    [v.code]: v.exportFlag || '',
                });
            }
        });
        const data = {
            params,
            pagination: [{
                currentPage: 1,
                pageSize: 10000,
                sort: "code",
                dir: "asc"
            }],
        };
        $http.post('urlS', this, {
            code: "01040221",
            data: data,
            success: function (res) {
                if (+res.errorCode === 0 && res.result && res.result.filePath) {
                    const { origin } = window.location;
                    window.open(origin + res.result.filePath);
                } else {
                    message.error(res.errorMessage || '导出失败');
                }
            }
        })
    }

    TabPaneChange = (key) => {
        this.setState({
            defaultActiveKey: key
        })
    }

    handleNumFlagChange = e => {
        this.setState({ numFlag: e.target.checked })
    };

    handleInputChange = (e, dataIndex) => {
        this.state[dataIndex] = e;
        this.setState({}, () => {
            this.handleQuery();
        });
    }

    render() {
        let { language, numFlag, loading, selectData, userType } = this.state
        // 组件所需参数
        const param = {
            // 表头配置
            loading,
            columns: this.state.columns,
            // 表格数据
            data: this.state.tableData,
            // 数据总条数
            total: this.state.total,
            // 数据页数
            page: this.state.page,

            pageSize: this.state.pageSize,
            componentName: 'userInformationUserList',
            // 表格的宽度
            x: 1600,
            y: store.getState().tableHeight.y - 25,
            height: store.getState().tableHeight.y + 20 + 'px'
        }
        return (
            <Spin tip="加载中..." spinning={this.state.showLoading}>
                <div style={{ width: '100%', height: '100%' }}>
                    <div className="table-operations">
                        <Row style={{ minHeight: '80px', padding: '0 24px 24px 24px' }}>
                            <Col span={21}>
                                {language.userInformationUserListUsernumber && language.userInformationUserListUsernumber.descripts || "工号："}：
                                <Input
                                    onKeyUp={(e) => { this.handleKeydown(e); }}
                                    allowClear={true}
                                    value={this.state.code}
                                    onChange={this.onChangeCode}
                                    placeholder={language.userInformationUserListUsernumber && language.userInformationUserListUsernumber.message}
                                    style={{ width: '86px', margin: '23px 12px 0 0' }}
                                />
                                {language.userInformationUserListUsername && language.userInformationUserListUsername.descripts || "姓名："}：
                                <Input
                                    onKeyUp={(e) => { this.handleKeydown(e); }}
                                    allowClear={true}
                                    value={this.state.descripts}
                                    onChange={this.onChangeDescripts}
                                    placeholder={language.userInformationUserListUsername && language.userInformationUserListUsername.message}
                                    style={{ width: '86px', margin: '23px 12px 0 0' }}
                                />
                                {language.userInformationUserListDocumenttype && language.userInformationUserListDocumenttype.descripts || "证件类型："}：
                                <Select
                                    allowClear
                                    value={this.state.credTypeId}
                                    onChange={this.onChangeCredType}
                                    style={{ width: '80px', margin: '23px 12px 0 0' }}
                                    placeholder={language.userInformationUserListDocumenttype && language.userInformationUserListDocumenttype.message}
                                >
                                    <Option value="">全部</Option>
                                    {selectData && 'result' in selectData && Array.isArray(selectData.result) && selectData.result.map(item => <Option key={item.id}>{item.descripts}</Option>)}
                                </Select>
                                {language.userInformationUserListIdentificationNumber && language.userInformationUserListIdentificationNumber.descripts || "证件号码："}：
                                <Input
                                    onKeyUp={(e) => { this.handleKeydown(e); }}
                                    allowClear={true}
                                    value={this.state.credNo}
                                    onChange={this.onChangeCredNo}
                                    placeholder={language.userInformationUserListIdentificationNumber && language.userInformationUserListIdentificationNumber.message}
                                    style={{ width: '100px', margin: '23px 12px 0 0' }}
                                />
                                {language.userInformationUserListUserPhone && language.userInformationUserListUserPhone.descripts || "手机号码"}：
                                <Input
                                    onKeyUp={(e) => { this.handleKeydown(e); }}
                                    allowClear={true}
                                    value={this.state.phoneNumber}
                                    onChange={this.onChangePhone}
                                    placeholder={language.userInformationUserListUserPhone && language.userInformationUserListUserPhone.message || "请输入"}
                                    style={{ width: '100px', margin: '23px 12px 0 0' }}
                                />
                                人员类型：
                                <Select
                                    allowClear
                                    placeholder="请选择"
                                    value={userType}
                                    onChange={(e) => this.handleInputChange(e, 'userType')}
                                    style={{ width: '96px', margin: '23px 12px 0 0' }}
                                >
                                    {React.$SelectOptions(selectData?.userType || [])}
                                </Select>
                                {language.userInformationUserListstate && language.userInformationUserListstate.descripts}：
                                <Select
                                    allowClear
                                    value={this.state.active}
                                    onChange={this.onChangeActive}
                                    style={{ width: '80px', margin: '23px 12px 0 0' }}
                                    placeholder={language.userInformationUserListstate && language.userInformationUserListstate.message}
                                >
                                    <Option value="">全部</Option>
                                    <Option value="Y">有效</Option>
                                    <Option value="N">失效</Option>
                                </Select>
                                <Checkbox checked={numFlag} onChange={this.handleNumFlagChange}>执业证书/医保编码</Checkbox>
                                <Button onClick={this.search} style={{ margin: '23px 0 0 0', background: 'rgba(255,255,255,1)' }}>{language.userInformationUserListQuery && language.userInformationUserListQuery.descripts}</Button>
                            </Col>
                            <Col span={3} style={{ textAlign: 'right' }}>
                                <Button onClick={this.exportExcel} style={{ margin: '23px 12px 0 0' }}>
                                    {language.userInformationUserListExportExcel?.descripts || '导出'}
                                </Button>
                                <Button icon="plus" onClick={this.handleAdd} style={{ background: 'rgba(247,128,93,1)', color: '#fff', margin: '23px 0 0 0' }}>{language.userInformationUserListNewusers && language.userInformationUserListNewusers.descripts}</Button>
                            </Col>
                        </Row>
                    </div>
                    <div style={{ widht: '100%', height: '10px', background: '#f0f2f5' }}></div>
                    <div style={{ padding: 24 }}>
                        <Tabs defaultActiveKey={this.state.defaultActiveKey} onChange={this.TabPaneChange}>
                            <TabPane tab={language.userInformationUserListAllusers && language.userInformationUserListAllusers.descripts} key="1">
                                <PubilcTablePagination param={param} handelThis={this} onRef={this.onRef} getColumns={this.ordList1} />
                            </TabPane>
                            <TabPane tab={language.userInformationUserListHospitalstaff && language.userInformationUserListHospitalstaff.descripts} key="2">
                                <UserListUser
                                    userSearch={this.state.userSearch}
                                    handelThis={this}
                                    onRef={this.onRef2}
                                />
                            </TabPane>
                            <TabPane tab={language.userInformationUserListPressloginDepartment && language.userInformationUserListPressloginDepartment.descripts} key="3">
                                <UserListLoc
                                    userSearch={this.state.userSearch}
                                    handelThis={this}
                                    onRef={this.onRef3}
                                />
                            </TabPane>
                            <TabPane tab={language.userInformationUserListByassignedDepartment && language.userInformationUserListByassignedDepartment.descripts} key="4">
                                <UserListLocT userSearch={this.state.userSearch}
                                    handelThis={this}
                                    onRef={this.onRef4} />
                            </TabPane>
                            <TabPane tab={language.userInformationUserListByrole && language.userInformationUserListByrole.descripts} key="5">
                                <UserListGroup userSearch={this.state.userSearch}
                                    handelThis={this}
                                    onRef={this.onRef5} />
                            </TabPane>
                            <TabPane tab={language.userInformationUserListBytype && language.userInformationUserListBytype.descripts} key="6" disabled >
                                <UserListMan userSearch={this.state.userSearch}
                                    handelThis={this}
                                    onRef={this.onRef6} />
                            </TabPane>
                            <TabPane tab={language.userInformationUserListBytitle && language.userInformationUserListBytitle.descripts} key="7">
                                <UserListZc userSearch={this.state.userSearch}
                                    handelThis={this}
                                    onRef={this.onRef7} />
                            </TabPane>
                            <TabPane tab={language.userInformationUserListAccordingtoexpertise && language.userInformationUserListAccordingtoexpertise.descripts} key="8">
                                <UserListZh userSearch={this.state.userSearch}
                                    handelThis={this}
                                    onRef={this.onRef8} />
                            </TabPane>
                        </Tabs>
                    </div>
                    <Modal
                        visible={this.state.modaltitleVis}
                        title={this.state.modaltitle}
                        width="1300px"
                        onCancel={this.handleCancel}
                        onOk={this.handleCancel}
                        footer={false}
                    >
                        <NewUser paras={this.state.paras} key={this.state.paras.userInfo && this.state.paras.userInfo.userID} handelThis={this}></NewUser>
                    </Modal>
                </div>
            </Spin>
        )
    }
}
