import React, { useEffect, useState, useRef } from 'react';
import { connect } from 'react-redux';
import { Col, Row, Button, Tree, ButtonGroup, RadioGroup, Radio, Checkbox, CheckboxGroup, Popconfirm, Toast } from '@douyinfe/semi-ui';
import EmployeeAuthModal from './employeeAuthModal'
import EmployeeAuthUserModal from './employeeAuthUserModal'
import '../style.less'

const EmployeeAuth = (props) => {
    const form = useRef();
    const { dispatch, actions, roleList, userRoleList, resourceList } = props
    const [dataRange, setDataRange] = useState(1);
    const [checkedList, setCheckedList] = useState([]);
    const [roleId, setRoleId] = useState();
    const [two, setTwo] = useState({});
    const [visible, setVisible] = useState(false);
    const [eidtRole, setEidtRole] = useState(null);
    const [eidtTit, setEidtTit] = useState(null);
    const [visibleUser, setVisibleUser] = useState(false);
    const getRoleList = () => {
        dispatch(actions.humanAffairs.getRoleList())
        dispatch(actions.humanAffairs.getUserRoleList())
    }
    useEffect(() => {
        getRoleList()
        dispatch(actions.humanAffairs.getResource())
    }, [])
    let hrUser = JSON.parse(sessionStorage.getItem('hrUser'))
    const button = (
        <ButtonGroup
            size="small"
            theme="borderless"
        >
            <Button>编辑</Button>
            <Button>删除</Button>
        </ButtonGroup>
    );
    const style = {
        display: 'flex',
        justifyContent: 'space-between',
        alignItems: 'center'
    };
    let roleAndUser = []
    roleList && roleList.rows.forEach(e => {
        let children = []
        userRoleList && userRoleList.rows.forEach(i => {
            if (e.id == i.roleId) {
                let user = hrUser.userListArr.find(s => s.id == i.userId)
                children.push(user)
            }
        })
        roleAndUser.push({
            id: e.id,
            name: e.name,
            children: children
        })
    })
    let roleLists = []
    if (roleAndUser.length) {
        roleAndUser.forEach(e => {
            let children = []
            if (e.children) {
                e.children.forEach(i => {
                    children.push({
                        label: (
                            <div style={style}>
                                <span>{i.name}</span>
                                <ButtonGroup
                                    size="small"
                                    theme="borderless"
                                >
                                    {/* <Button>删除</Button> */}
                                </ButtonGroup>
                            </div>
                        ),
                        value: i.id,
                        key: i.id + new Date(),
                        name: i.name
                    })
                })
            }
            roleLists.push({
                label: (
                    <div style={style} onClick={() => { roleListBtn(e.id) }}>
                        <span>{e.name}</span>
                        <ButtonGroup
                            size="small"
                            theme="borderless"
                        >
                            <Button onClick={() => { showModal(e, '编辑角色') }}>编辑</Button>
                            <Popconfirm
                                title="是否确定删除？"
                                onConfirm={() => { deletRole(e.id) }}
                            >
                                <Button>删除</Button>
                            </Popconfirm>
                        </ButtonGroup>
                    </div>
                ),
                value: e.id,
                key: e.id,
                children: children,
                name: e.name
            })
        })
    }
    const dataRangeChange = (e) => {
        setDataRange(e.target.value);
    };
    const treeList = []
    if (resourceList && resourceList.rows) {
        resourceList.rows.forEach((item) => {
            item.child = resourceList.rows.filter((sec) => {
                return sec.parentId === item.id
            })
            if (item.parentId === null) {
                treeList.push(item)
            }
        })
    }
    const onChangeOne = (value, recod) => {
        let twos = two
        let selList = []
        recod.child.forEach(e => {
            if (value.target.checked) {
                twos[e.id] = true
            } else {
                twos[e.id] = false
            }
            if (e.child.length) {
                e.child.forEach(i => {
                    selList.push(i.id)
                })
            }
        })
        if (value.target.checked) {
            twos[value.target.value] = true
            setTwo(twos)
            setCheckedList([...checkedList, ...selList])
        } else {
            twos[value.target.value] = false
            setCheckedList(getDiffer(checkedList, selList));
            setTwo(twos)
        }
    }
    const onCheckAllChange = (value, recod) => {
        let selList = []
        recod.child.forEach(i => {
            if (i.id == value.target.value) {
                if (i.child.length) {
                    i.child.forEach(s => {
                        selList.push(s.id)
                    })
                }
            }
        })
        let twos = two
        if (value.target.checked) {
            setCheckedList([...checkedList, ...selList])
            twos[value.target.value] = true
            twos[recod.id] = true
            setTwo(two)
        } else {
            setCheckedList(getDiffer(checkedList, selList));
            twos[value.target.value] = false
            setTwo(two)
        }
    };
    const checkItem = (e, recod) => {
        let check = [e.target.value]
        let twos = two
        let twosid
        if (e.target.checked) {
            setCheckedList([...checkedList, ...check])
            resourceList.rows.forEach(e => {
                if (e.id == check[0]) {
                    twosid = e.parentId
                }
            })
            twos[twosid] = true
            twos[recod.id] = true
            setTwo(twos)
        } else {
            setCheckedList(getDiffer(checkedList, check));
        }
    }
    const getDiffer = (arr1, arr2) => {
        let arr = arr1.filter(e => {
            return !arr2.includes(e)
        })
        return arr
    }
    const handleCancel = () => {
        setVisible(false);
    };
    const showModal = (eidtRole, tit) => {
        setEidtRole(eidtRole)
        setEidtTit(tit)
        setVisible(true);
    };
    const deletRole = (id) => {
        let data = { id }
        dispatch(actions.humanAffairs.delRole(data)).then(e => {
            if (e.success) {
                getRoleList()
            }
        })
    }
    const showUserMolad = () => {
        setVisibleUser(true);
    }
    const handleCancelUser = () => {
        setVisibleUser(false);
    };
    const roleListBtn = (id) => {
        setRoleId(id)
        dispatch(actions.humanAffairs.getRoleResource({ id })).then(res => {
            if (res.success) {
                let two = {}
                let checkList = []
                if (res.payload.data && res.payload.data.rows.length) {
                    checkList = res.payload.data.rows.map(e => {
                        two[e.resId] = true
                        return e.resId
                    })
                    setCheckedList(checkList)
                    setTwo(two)
                } else {
                    setCheckedList([])
                    setTwo(two)
                }

            }
        })
    }
    const handlOk = () => {
        let resourceId = [];
        for (let item in two) {
            if (two[item]) {
                resourceId.push(parseInt(item));
            }
        }
        resourceId = [...checkedList, ...resourceId]
        if (roleId == undefined || resourceId.length == 0) {
            Toast.error('请选择角色和权限！')
        } else {
            dispatch(actions.humanAffairs.addRoleResource({ roleId, resourceId }))
        }
    }


    return (
        <>
            <div style={{ padding: '0px 12px' }}>
                <div style={{ display: 'flex' }}>
                    <div style={{ color: 'rgba(0,0,0,0.45)', fontSize: 14 }}>权限中心</div>
                    <div style={{ color: '#033C9A', fontSize: 14, margin: '0px 8px' }}>/</div>
                    <div style={{ color: '#033C9A', fontSize: 14 }}>员工权限</div>
                </div>
                <div style={{ background: '#FFFFFF', boxShadow: '0px 0px 12px 2px rgba(220,222,224,0.2)', borderRadius: 2, padding: '20px 0px 20px 19px ', marginTop: 12 }}>
                    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                        <div style={{ display: 'flex', alignItems: 'baseline' }}>
                            <div style={{ width: 0, height: 20, borderLeft: '3px solid #0F7EFB', borderTop: '3px solid transparent', borderBottom: '3px solid transparent' }}></div>
                            <div style={{ fontFamily: "YouSheBiaoTiHei", fontSize: 24, color: '#033C9A', marginLeft: 8 }}>员工权限</div>
                            <div style={{ marginLeft: 6, fontSize: 12, color: '#969799', fontFamily: "DINExp", }}>EMPLOYEE AUTHORITY</div>
                        </div>
                    </div>


                    <div className='authorityBox'>
                        <div className='authorityTit'>
                            <h2><b></b>管理员设置</h2>
                            <span>平台管理员由项企统一认证平台授权，拥有对本系统所有功能进行设置和管理。</span>
                        </div>
                        <div className='authorityAdminList'>
                            {
                                hrUser && hrUser.adminHr && hrUser.adminHr.map(e => {
                                    return (
                                        <div >
                                            <span>人力资源部</span>
                                            <h2>{e.name}</h2>
                                            <h4>角色说明：拥有全平台的权限</h4>
                                        </div>
                                    )
                                })
                            }
                        </div>
                        <div className='authorityTit'>
                            <h2><b></b>角色授权</h2>
                        </div>
                        <div className='roleAuthori'>
                            <Row>
                                <Col span={4}>
                                    <div>
                                        <Button theme='solid' style={{ marginLeft: 15, background: '#0099FF' }} onClick={() => { showModal(null, '新增角色') }}>新建角色</Button>
                                        <Button theme='solid' onClick={showUserMolad} style={{ marginLeft: 15, background: '#0099FF' }}>添加修改用户绑定</Button>
                                    </div>
                                    <Tree
                                        treeData={roleLists}
                                        style={{ marginTop: 20 }}
                                    />
                                </Col>
                                <Col span={19} style={{ float: 'right' }}>
                                    <div className='dataRange'>
                                        <h2>数据范围:</h2>
                                        <RadioGroup onChange={dataRangeChange} value={dataRange} style={{ float: 'left', marginTop: 17, }}>
                                            <Radio value={1}>本部门</Radio>
                                            <Radio value={2}>全公司</Radio>
                                        </RadioGroup>
                                    </div>
                                    <div className='dataRange'>
                                        <h2>权限范围:</h2>
                                        <Checkbox style={{ float: 'left', marginTop: 17, }} >全部权限</Checkbox>
                                    </div>
                                    {treeList.map(e => {
                                        return <div className='codeList'>
                                            <Checkbox onChange={(value) => { onChangeOne(value, e) }} style={{ borderBottom: '1px solid #f2f2f2', padding: '10px 10px' }} checked={two[e.id]} key={e.id} value={e.id}>{e.name}</Checkbox>
                                            {e.child.map(i => {
                                                return <div>
                                                    <Checkbox value={i.id} style={{ borderBottom: '1px solid #f2f2f2', padding: '10px 10px' }} key={i.id} checked={two[i.id]} onChange={(value) => { onCheckAllChange(value, e) }}>{i.name}</Checkbox>
                                                    <CheckboxGroup style={{ width: '100%', borderBottom: '1px solid #f2f2f2', padding: '10px 10px' }} direction='horizontal' value={checkedList}>
                                                        {
                                                            i.child.map(s => (<Checkbox onChange={(value) => { checkItem(value, e) }} key={s.id} value={s.id} >{s.name}</Checkbox>))
                                                        }
                                                    </CheckboxGroup>
                                                </div>
                                            })}

                                        </div>
                                    })}
                                    <Button onClick={handlOk} theme='solid' style={{ background: '#0099FF', marginTop: 10 }}>保存</Button>
                                </Col>
                            </Row>
                        </div>
                    </div>
                </div>
            </div>
            {
                visible ? <EmployeeAuthModal eidtTit={eidtTit} visible={visible} handleCancel={handleCancel} getRoleList={getRoleList} eidtRole={eidtRole} /> : ''
            }
            {
                visibleUser ? <EmployeeAuthUserModal userRoleList={userRoleList} visibleUser={visibleUser} handleCancelUser={handleCancelUser} getRoleList={getRoleList} roleList={roleList} /> : ''
            }
        </>
    )
}

function mapStateToProps(state) {
    const { auth, global, roleList, userRoleList, resourceList } = state;
    return {
        user: auth.user,
        actions: global.actions,
        roleList: roleList.data,
        userRoleList: userRoleList.data,
        resourceList: resourceList.data
    };
}

export default connect(mapStateToProps)(EmployeeAuth);
