import React, { useEffect, useState, useRef } from 'react';
import { connect } from 'react-redux';
import { Skeleton, Table, RadioGroup, Radio, Button, Pagination, Popconfirm, Tooltip } from '@douyinfe/semi-ui';
import { SkeletonScreen, } from "$components";
import AdminModal from '../components/adminModal';
import MemberModal from '../components/memberModal';

import '../style.less'

const Roles = (props) => {
    const { dispatch, actions, user, loading, socket } = props
    const { install } = actions;
    const [roleAssignment, setRoleAssignment] = useState([])//角色分配
    const [roleChoose, setRoleChoose] = useState('')//角色选择
    const [query, setQuery] = useState({ limit: 10, page: 0 }); //页码信息
    const [adminModal, setAdminModal] = useState(false);//管理员弹框
    const [adminEdit, setAdminEdit] = useState(false);//管理员弹框是否修改
    const [editObj, setEditObj] = useState({});//管理员弹框修改内容
    const [memberModal, setMemberModal] = useState(false);//成员弹框
    const [memberEdit, setMemberEdit] = useState(false);//成员弹框是否修改

    const [columns, setColumns] = useState([//表格属性
        {
            title: '成员',
            render: (_, row) => {
                let departmentsArr = []
                for (let i = 0; i < row.departments.length; i++) {
                    departmentsArr.push(row.departments[i].name)
                }
                return (
                    <div style={{ display: 'flex', alignItems: 'center' }}>
                        <div>
                            {row.name}
                        </div>
                        <div style={{ padding: '2px 4px', background: '#E8F3FF', borderRadius: 2, fontSize: 12, color: '#005ABD', marginLeft: 4 }}>
                            {row.departments[0].name}
                        </div>
                        {
                            row.departments.length > 1 ? (
                                <Tooltip content={departmentsArr.join(',')} trigger="click">
                                    <div style={{ fontSize: 14, color: '#005ABD', marginLeft: 8, cursor: "pointer", }}>
                                        +{row.departments.length - 1}
                                    </div>
                                </Tooltip>
                            ) : ('')
                        }
                    </div>
                )
            }
        },
        {
            title: '项目名称',
            render: (_, row) => {
                return (
                    <div>
                        {
                            row.correlationProject.map((item, index) => {
                                return (
                                    <div key={index}>
                                        {item}
                                    </div>
                                )
                            })
                        }
                    </div>
                )
            }
        },
        {
            title: (
                <div style={{ display: 'flex', alignItems: 'center' }}>
                    数据分析师
                    <Tooltip content={'拥有分析、工单、资料的权限'}>
                        <img src="/assets/images/install/table_question.png" alt="" style={{ height: 14, width: 14, marginLeft: 4 }} />
                    </Tooltip>
                </div>
            ),
            render: (_, row) => {
                let rolearr = row.role
                return (
                    <div>
                        {
                            rolearr.indexOf('data_analyst') != -1 ? (
                                <div style={{ display: 'flex' }}>
                                    <div>
                                        <img src="/assets/images/install/icon_haveAuthority.png" alt="" style={{ height: 18, width: 18 }} />
                                    </div>
                                    <div>有权限</div>
                                </div>
                            ) : (
                                <div style={{ display: 'flex' }}>
                                    <div>
                                        <img src="/assets/images/install/icon_noPermission.png" alt="" style={{ height: 18, width: 18 }} />
                                    </div>
                                    <div style={{ color: '#969799' }}>无权限</div>
                                </div>
                            )
                        }
                    </div>
                );
            }
        }, {
            title: (
                <div style={{ display: 'flex', alignItems: 'center' }}>
                    售后运维
                    <Tooltip content={'拥有问题、设备、工单、资料、一期控制台的权限'}>
                        <img src="/assets/images/install/table_question.png" alt="" style={{ height: 14, width: 14, marginLeft: 4 }} />
                    </Tooltip>
                </div>
            ),
            render: (_, row) => {
                let rolearr = row.role
                return (
                    <div>
                        {
                            rolearr.indexOf('after_sale') != -1 ? (
                                <div style={{ display: 'flex' }}>
                                    <div>
                                        <img src="/assets/images/install/icon_haveAuthority.png" alt="" style={{ height: 18, width: 18 }} />
                                    </div>
                                    <div>有权限</div>
                                </div>
                            ) : (
                                <div style={{ display: 'flex' }}>
                                    <div>
                                        <img src="/assets/images/install/icon_noPermission.png" alt="" style={{ height: 18, width: 18 }} />
                                    </div>
                                    <div style={{ color: '#969799' }}>无权限</div>
                                </div>
                            )
                        }
                    </div>
                );
            }
        }, {
            title: (
                <div style={{ display: 'flex', alignItems: 'center' }}>
                    资源管理员
                    <Tooltip content={'拥有资料、工单的权限'}>
                        <img src="/assets/images/install/table_question.png" alt="" style={{ height: 14, width: 14, marginLeft: 4 }} />
                    </Tooltip>
                </div>
            ),
            render: (_, row) => {
                let rolearr = row.role
                return (
                    <div>
                        {
                            rolearr.indexOf('resource_manage') != -1 ? (
                                <div style={{ display: 'flex' }}>
                                    <div>
                                        <img src="/assets/images/install/icon_haveAuthority.png" alt="" style={{ height: 18, width: 18 }} />
                                    </div>
                                    <div>有权限</div>
                                </div>
                            ) : (
                                <div style={{ display: 'flex' }}>
                                    <div>
                                        <img src="/assets/images/install/icon_noPermission.png" alt="" style={{ height: 18, width: 18 }} />
                                    </div>
                                    <div style={{ color: '#969799' }}>无权限</div>
                                </div>
                            )
                        }
                    </div>
                );
            }
        }, {
            title: (
                <div style={{ display: 'flex', alignItems: 'center' }}>
                    客户服务
                    <Tooltip content={'拥有服务、工单的权限'}>
                        <img src="/assets/images/install/table_question.png" alt="" style={{ height: 14, width: 14, marginLeft: 4 }} />
                    </Tooltip>
                </div>
            ),
            render: (_, row) => {
                let rolearr = row.role
                return (
                    <div>
                        {
                            rolearr.indexOf('customer_service') != -1 ? (
                                <div style={{ display: 'flex' }}>
                                    <div>
                                        <img src="/assets/images/install/icon_haveAuthority.png" alt="" style={{ height: 18, width: 18 }} />
                                    </div>
                                    <div>有权限</div>
                                </div>
                            ) : (
                                <div style={{ display: 'flex' }}>
                                    <div>
                                        <img src="/assets/images/install/icon_noPermission.png" alt="" style={{ height: 18, width: 18 }} />
                                    </div>
                                    <div style={{ color: '#969799' }}>无权限</div>
                                </div>
                            )
                        }
                    </div>
                );
            }
        },
        {
            title: "管理",
            width: "20%",
            dataIndex: "",
            render: (_, row) => {
                return (
                    <div style={{ display: "flex" }}>
                        {row?.disabled ? (
                            <Button
                                theme="borderless"
                                onClick={() => {
                                    dispatch(install.putOrganizationUser({ pomsUserId: row?.id, disabled: !row?.disabled })).then(() => getUserList())
                                }}
                            >
                                启用
                            </Button>
                        ) : (
                            <Popconfirm
                                title="禁用后，成员暂时将无法登录。"
                                arrowPointAtCenter={false}
                                showArrow={true}
                                position="topRight"
                                onConfirm={() => {
                                    dispatch(install.putOrganizationUser({ pomsUserId: row?.id, disabled: !row?.disabled })).then(() => {
                                        getUserList();
                                    })
                                }}
                            >
                                <Button theme="borderless">禁用</Button>
                            </Popconfirm>
                        )}
                        <Button
                            theme="borderless"
                            onClick={() => {
                                setMemberModal(true);
                                setEditObj(row)
                                setMemberEdit(true)
                            }}
                        >
                            编辑
                        </Button>
                        <Popconfirm
                            title="删除后，成员将无法登录。"
                            arrowPointAtCenter={false}
                            showArrow={true}
                            position="topRight"
                            onConfirm={() => {
                                dispatch(install.putOrganizationUser({ pomsUserId: row?.id, deleted: true })).then(() => {
                                    if (page.current > 0 && limits.current < 2) {
                                        setQuery({ limit: 10, page: page.current - 1 })
                                    } else {
                                        setQuery({ limit: 10, page: page.current })
                                    }
                                })
                            }}
                        >
                            <Button theme="borderless">删除</Button>
                        </Popconfirm>
                    </div>
                );
            },
        },
    ])
    // const [data, setdata] = useState([])//表格数据
    const tableData = useRef([]); //每页实际条数
    const page = useRef(query.page);//哪一页
    const limits = useRef(); //每页实际条数
    const [pepList, setPepList] = useState([])//角色分配
    useEffect(() => {
        getUserList();
    }, [query, roleChoose]);
    useEffect(() => {
        dispatch(install.getOrganizationDeps()).then((res) => {//获取项企(PEP)全部部门及其下用户
            setPepList(res.payload.data)
        })
        getUserList()
    }, [])
    function getUserList () {
        let searchData = { ...query, role: roleChoose }
        dispatch(install.getOrganizationUser(searchData)).then((res) => {//获取成员列表
            tableData.current = res.payload.data.users.rows;
            let notCreatedArr = []
            let notCreatedNum = 5 - res.payload.data.admin.length
            for (let i = 0; i < notCreatedNum; i++) {
                notCreatedArr.push('')
            }
            setRoleAssignment(res.payload.data.admin.concat(notCreatedArr))
            limits.current = res.payload.data.users.count
        })
    }
    function handleRow (record, index) {//斑马条纹
        // 给偶数行设置斑马纹
        if (index % 2 === 0) {
            return {
                style: {
                    background: '#FAFCFF',
                }
            };
        } else {
            return {};
        }
    }
    function roleOnChange (e) {//角色选择
        setRoleChoose(e.target.value);
    }
    return (
        <>
            <div style={{ background: '#FFFFFF', margin: '8px 12px', padding: '20px 20px 0px 20px' }}>
                <div style={{ display: 'flex', alignItems: 'center' }}>
                    <div style={{ width: 0, height: 20, borderLeft: '3px solid #005ABD', borderTop: '3px solid transparent', borderBottom: '3px solid transparent' }}></div>
                    <div style={{ fontFamily: "YouSheBiaoTiHei", fontSize: 24, color: '#101531', marginLeft: 8 }}>管理员设置</div>
                    <div style={{ marginLeft: 6, fontSize: 12, color: '#969799', fontFamily: "DINExp", }}>ADMINISTRATOR SETTING</div>
                </div>
                <div style={{ margintop: 15, overflow: 'auto' }}>
                    <div style={{ display: 'inline-flex' }}>
                        {
                            roleAssignment.map((item, index) => {
                                return (
                                    <div key={index} style={{
                                        width: 312, height: 127, boxShadow: '0px 0px 12px 2px rgba(220,222,224,0.2)',
                                        borderRadius: 2, background: "url(/assets/images/install/cardBackground0" + (index + 1) + '.png)',
                                        backgroundSize: "100% 100%", marginRight: 20, marginBottom: 20,
                                    }}>
                                        {
                                            item.id ? (
                                                <div style={{ display: 'flex', marginLeft: 21, }}>
                                                    {
                                                        item.departments?.map((itm, idx) => {
                                                            let mydepartmentsArr=[]
                                                            for (let index = 0; index < item.departments.length; index++) {
                                                                mydepartmentsArr.push(item.departments[index].name)
                                                            }
                                                            return (
                                                                <div key={idx} style={{
                                                                    background: '#52A4F6', borderRadius: 2, height: 18, padding: '2px 4px',
                                                                    fontSize: 10, marginTop: 17, width: 'max-content', color: '#FFFFFF',
                                                                    display: 'flex', alignItems: 'center', marginRight: 4,
                                                                }}>
                                                                    {
                                                                        idx > 2 ? (
                                                                            <Tooltip content={mydepartmentsArr.join(',')}>
                                                                                <div style={{ fontSize: 14, cursor: "pointer", }}>
                                                                                    ...
                                                                                </div>
                                                                            </Tooltip>

                                                                        ) : (
                                                                            itm.name
                                                                        )
                                                                    }
                                                                </div>
                                                            )
                                                        })
                                                    }
                                                </div>
                                            ) : (
                                                <div style={{
                                                    background: '#52A4F6', borderRadius: 2, height: 18, padding: '2px 4px',
                                                    fontSize: 10, marginTop: 17, marginLeft: 21, width: 'max-content', color: '#FFFFFF',
                                                    display: 'flex', alignItems: 'center',
                                                }}>
                                                    部门
                                                </div>
                                            )
                                        }
                                        <div style={{ marginTop: 5, display: 'flex', justifyContent: 'space-between', padding: '0px 17px 0px 21px' }}>
                                            <div style={{ marginTop: 9 }}>
                                                <div style={{ display: 'flex' }}>
                                                    {
                                                        item.id ? (
                                                            <div style={{ fontSize: 14, color: '#4A4A4A', fontWeight: 600 }}>{item.name}</div>
                                                        ) : (
                                                            <div style={{ fontSize: 14, color: '#4A4A4A', fontWeight: 600 }}>虚席以待</div>
                                                        )
                                                    }

                                                    <div style={{ marginLeft: 4, cursor: "pointer", }} onClick={() => {
                                                        if (item.id) {
                                                            setEditObj(item)
                                                            setAdminEdit(true)
                                                        }
                                                        else {
                                                            setEditObj({})
                                                            setAdminEdit(false)
                                                        }
                                                        setAdminModal(true)
                                                    }}>
                                                        <img src="/assets/images/install/icon_edit.png" alt="" style={{ height: 18, width: 18 }} />
                                                    </div>
                                                    {
                                                        item.id ? (
                                                            <Popconfirm
                                                                title="是否要移除管理员"
                                                                arrowPointAtCenter={false}
                                                                showArrow={true}
                                                                position="topRight"
                                                                onConfirm={() => {
                                                                    dispatch(install.deteleOrganizationAdmin(item?.id)).then(() => getUserList())
                                                                }}
                                                            >
                                                                <div style={{ marginLeft: 4, cursor: "pointer", }}>
                                                                    <img src="/assets/images/install/icon_detele.png" alt="" style={{ height: 18, width: 18 }} />
                                                                </div>
                                                            </Popconfirm>

                                                        ) : ('')
                                                    }

                                                </div>
                                                <div style={{ fontSize: 12, color: '#969799', marginTop: 28, marginLeft: 50 }}>角色说明：拥有全平台的权限</div>
                                            </div>
                                            <div>
                                                <img src="/assets/images/install/setPermissions.png" alt="" style={{ height: 63, width: 61 }} />
                                            </div>
                                        </div>
                                    </div>
                                )
                            })
                        }
                    </div>
                </div>
            </div>
            <div className='roleBottom' style={{ margin: '20px 12px 12px 12px', background: '#FFFFFF', padding: '20px 20px 40px 20px' }}>
                <div style={{ display: 'flex', alignItems: 'center' }}>
                    <div style={{ width: 0, height: 20, borderLeft: '3px solid #005ABD', borderTop: '3px solid transparent', borderBottom: '3px solid transparent' }}></div>
                    <div style={{ fontFamily: "YouSheBiaoTiHei", fontSize: 24, color: '#101531', marginLeft: 8 }}>成员管理</div>
                    <div style={{ marginLeft: 6, fontSize: 12, color: '#969799', fontFamily: "DINExp", }}>MANAGEMENT OF MEMBERS</div>
                </div>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 20 }}>
                    <div style={{ fontSize: 12, color: '#8B8B8B' }}>平台有4种类型的成员角色，分别是数据分析师、售后运维、资源管理者和客户服务，每名项目成员可拥有多种成员角色；</div>
                    <div className='roleRadio' style={{ display: 'flex', alignItems: 'center' }}>
                        <div>
                            <RadioGroup onChange={roleOnChange} value={roleChoose} aria-label="单选组合示例" name="demo-radio-group">
                                <Radio value=''>全部</Radio>
                                <Radio value='data_analyst'>数据分析师</Radio>
                                <Radio value='after_sale'>售后运维</Radio>
                                <Radio value='resource_manage'>资源管理者</Radio>
                                <Radio value='customer_service'>客户服务</Radio>
                            </RadioGroup>
                        </div>
                        <div>
                            <Button
                                theme="solid"
                                type="primary"
                                style={{
                                    width: 108,
                                    height: 32,
                                    borderRadius: 2,
                                    marginLeft: 40
                                }}
                                onClick={() => {
                                    setEditObj({})
                                    setMemberEdit(false)
                                    setMemberModal(true);
                                }}
                            >
                                添加成员
                            </Button>
                        </div>
                    </div>
                </div>
                <Skeleton
                    loading={false}
                    active={true}
                    placeholder={SkeletonScreen()}
                >
                    <Table
                        columns={columns}
                        dataSource={tableData.current}
                        bordered={false}
                        onRow={handleRow}
                        empty="暂无数据"
                        pagination={false}
                    />
                </Skeleton>
                <div
                    style={{
                        display: "flex",
                        justifyContent: "flex-end",
                        padding: "20px 20px",
                    }}
                >
                    <span style={{ lineHeight: "30px", fontSize: 13, color: 'rgba(0,90,189,0.8)' }}>
                        共{limits.current}条信息
                    </span>
                    <Pagination
                        className="22"
                        total={limits.current}
                        showSizeChanger
                        currentPage={query.page + 1}
                        pageSizeOpts={[10, 20, 30, 40]}
                        onChange={(currentPage, pageSize) => {
                            setQuery({ limit: pageSize, page: currentPage - 1 });
                            page.current = currentPage - 1
                        }}
                    />
                </div>
            </div>
            {//管理员弹框
                adminModal ?
                    <AdminModal
                        visible={true}
                        pepList={pepList}
                        adminEdit={adminEdit}
                        editObj={editObj}
                        close={() => {
                            setAdminModal(false);
                            getUserList()
                        }} >
                    </AdminModal> : ''
            }
            {//成员弹框
                memberModal ?
                    <MemberModal
                        visible={true}
                        pepList={pepList}
                        memberEdit={memberEdit}
                        editObj={editObj}
                        close={() => {
                            setMemberModal(false);
                            getUserList()
                        }} >
                    </MemberModal> : ''
            }
        </>
    )
}

function mapStateToProps (state) {
    const { auth, global, members } = state;
    return {
        //   loading: members.isRequesting,
        user: auth.user,
        actions: global.actions,
        //   members: members.data,
    };
}
export default connect(mapStateToProps)(Roles);
