import React, { useState, useEffect, useRef } from 'react';
import { Space, Modal, Form, Input, Button, message, Select, Popconfirm } from 'antd';
import { userApi, roleApi } from '@/api/sys/service';
import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { ProTable, TableDropdown } from '@ant-design/pro-components';
import styles from './index.less';

const User: React.FC = () => {

    // 人员详情弹窗
    const [isPersonDetailVisible, setIsPersonDetailVisible] = useState<boolean>(false);
    const [isAccountVisible, setIsAccountVisible] = useState<boolean>(false);

    const [currentPerson, setCurrentPerson] = useState<UserTypes.PersonnelType>({
        status: 1,
        roleId: '',
        gender: 1,
        id: '',
        sort: 1,
        name: '',
        isAccount: false
    });
    const [form] = Form.useForm();
    const [formAccount] = Form.useForm();
    const actionRef = useRef<ActionType>();
    const [roleList, setRoleList] = useState<RolelTypes.RoleType[]>([]);

    const personelColumns: ProColumns<UserTypes.PersonnelType>[] = [
        {
            title: '姓名',
            dataIndex: 'name',
            key: 'name',
        },
        {
            title: '登录账号',
            dataIndex: 'account',
            key: 'account',
            hideInSearch: true,
        },
        {
            title: '性别',
            dataIndex: 'gender',
            key: 'gender',
            valueType: 'select',
            hideInSearch: false,
            valueEnum: {
                0: {
                    text: '男'
                },
                1: {
                    text: '女',
                }
            },
            render: (_, record) => (
                <>
                    {
                        record.gender === 0 ?
                            <div style={{ color: 'green' }}>
                                男
                            </div>
                            :
                            <div style={{ color: 'green' }}>
                                女
                            </div>
                    }
                </>
            )
        },
        {
            title: '角色',
            search: false,
            hideInSearch: true,
            dataIndex: 'roleId',
            key: 'roleId',
            render: (_, record) => (
                <>
                    {
                        (() => {
                            const role = roleList.find(item => item.id === record.roleId);
                            if (role) {
                                return <div>{role.name}</div>
                            } else {
                                return <div>未知角色</div>
                            }
                        })()
                    }
                </>
            )
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            valueType: 'select',
            hideInSearch: false,
            valueEnum: {
                0: {
                    text: '在职'
                },
                1: {
                    text: '出差',
                },
                2: {
                    text: '离职',
                }
            },
            render: (_, record) => (
                <>
                    {
                        record.status === 0 ?
                            <div style={{ color: 'green' }}>
                                在职
                            </div>
                            :
                            (record.status === 1 ? <div style={{ color: 'Orange' }}>
                                出差
                            </div> : <div style={{ color: 'red' }}>
                                离职
                            </div>)

                    }
                </>
            )
        },
        {
            title: '操作',
            search: false,
            key: 'action',
            fixed: 'right',
            valueType: 'option',

            render: (_, record) => [
                <Popconfirm
                    key="del"
                    title="确定要删除此条数据吗？"
                    onConfirm={async () => {
                        const response = await userApi.RemoveUser(record.id!);
                        if (response.data === true) {
                            message.success('删除成功!');
                            actionRef.current?.reload();
                        } else {
                            message.error(response.msg || '删除失败');
                        }
                    }}
                    onCancel={() => {
                        message.info('已取消删除');
                    }}
                    okText="确认"
                    cancelText="关闭"
                >
                    <a >删除员工</a>
                </Popconfirm>,
                <Popconfirm
                    key="reset"
                    title="确定要重置密码吗？"
                    onConfirm={async () => {
                        const response = await userApi.RestoreAccount(record.id!);
                        if (response.data === true) {
                            message.success('成功!');
                        } else {
                            message.error(response.msg || '重置失败');
                        }
                    }}
                    onCancel={() => {
                        message.info('已取消');
                    }}
                    okText="确认"
                    cancelText="关闭"
                >
                    <a >重置密码</a>
                </Popconfirm>,
                <TableDropdown key="actionGroup"
                    onSelect={(key: any) => {
                        switch (key) {
                            case 'edit':
                                setIsPersonDetailVisible(true);
                                setCurrentPerson(record);
                                const tempRecord = JSON.parse(JSON.stringify(record));
                                form.setFieldsValue(tempRecord);
                                break;
                            case 'shezhi':
                                setIsAccountVisible(true);
                                formAccount.setFieldValue('tB_Employee_Id', record.id);
                                formAccount.setFieldValue('account', record.account!);
                                break;
                            default:
                                break;
                        }
                    }}

                    menus={[
                        { key: 'edit', name: '编辑' },
                        { key: 'shezhi', name: '设置登录账号' },
                    ]}

                />

            ],
        },
    ];

    const onAddPerson = () => {
        setCurrentPerson({
            status: 1,
            roleId: '',
            gender: 1,
            id: '',
            sort: 1,
            name: ''
        });
        form.resetFields();
        setIsPersonDetailVisible(true);
    }

    /**
    * 获取角色列表
    */
    const onFetchRoleList = async () => {
        const response = await roleApi.GetRoleList();
        if (response.statusCode === 200) {
            setRoleList(response.data);
        } else {
            message.error(response.msg || '获取角色列表失败');
        }
    }
    useEffect(() => {
        if (isPersonDetailVisible) {
            onFetchRoleList();
        }
    }, [isPersonDetailVisible])
    /**
     * 新增/更新人员信息
     */
    const onFinishPerson = async (user: UserTypes.PersonnelType) => {
        if (user.id) {
            const response = await userApi.ModifyUser(user);
            if (response.data === true) {
                message.success('更新用户信息成功!');
                setIsPersonDetailVisible(false);
            } else {
                message.error(response.msg || '更新用户信息失败');
            }
        } else {
            const response = await userApi.CreateUser(user);
            if (response.statusCode === 200) {
                message.success('创建成功!');
                setIsPersonDetailVisible(false);
            } else {
                message.error(response.msg || '创建失败');
            }
        }
        actionRef.current?.reload();

    }
    /**
     * 绑定用户账户
     */
    const onBindAcction = async (acc: account.base_dto) => {
        // const md5_str = md5(acc.pwd)
        // acc.pwd = md5_str;
        const response = await userApi.BindAccount(acc);
        if (response.data === true) {
            message.success('绑定成功!');
            actionRef?.current?.reload();
            setIsAccountVisible(false);
        } else {
            message.error(response.msg || '绑定失败');
        }
    }



    useEffect(() => {
        onFetchRoleList();
    }, []);

    return (
        <div className={styles.log_container} >
            <ProTable<UserTypes.PersonnelType>
                columns={personelColumns}
                actionRef={actionRef}
                cardBordered
                bordered
                scroll={{ x: true }}
                rowClassName={(record: any, index: number, indent: number) => {
                    if (index % 2 === 0) {
                        return ''; // 偶数行的类名
                    } else {
                        return 'even-row-background'; // 奇数行的类名
                    }
                }}
                request={async (params = {}) => {
                    const response = await userApi.GetUserPagedList({
                        name: params.name,
                        status: params.status,

                        pageIndex: params.current || 1,
                        pageSize: params.pageSize || 10,
                        gender: params.gender
                    });
                    if (response.statusCode === 200) {
                        return {
                            data: response.data.items,
                            success: true,
                            total: response.data.total
                        }
                    } else {
                        message.error('获取用户列表出错');
                        return {
                            data: [],
                            success: false,
                            total: 0
                        }
                    }
                }}
                rowKey="id"
                pagination={{
                    pageSize: 10,
                    showSizeChanger: false
                }}
                dateFormatter="string"
                headerTitle="人员列表"
                toolBarRender={() => [
                    <Button key="button" icon={<PlusOutlined />} type="primary" onClick={() => onAddPerson()}>
                        添加
                    </Button>
                ]}
            />
            <Modal
                maskClosable={false} width={500} title={currentPerson.id === '' ? '新增人员' : '编辑人员'} open={isPersonDetailVisible}
                onOk={(e) => {
                    setIsPersonDetailVisible(false)
                }
                }
                onCancel={() => setIsPersonDetailVisible(false)}
                footer={[
                    <Button
                        key="back"
                        onClick={() => {
                            setIsPersonDetailVisible(false)
                        }}
                    >
                        返回
                    </Button>,
                    <Button key="submit" form="userForm" type="primary" htmlType="submit">
                        提交
                    </Button>,
                ]}
            >
                <Form
                    form={form}
                    name="basic"
                    id='userForm'
                    onFinish={onFinishPerson}
                >
                    <Form.Item
                        label="id"
                        name="id"
                        hidden={true}
                    >
                        <Input />
                    </Form.Item>

                    <Form.Item
                        label="姓名"
                        name="name"
                        rules={[{ required: true, message: '请输入员工名称！' }]}
                    >
                        <Input />
                    </Form.Item>

                    <Form.Item
                        label="性别"
                        name="gender"
                        rules={[{ required: true, message: '请选择性别！' }]}
                    >
                        <Select style={{ width: '100%' }}>
                            <Select.Option value={0}>男</Select.Option>
                            <Select.Option value={1}>女</Select.Option>
                        </Select>
                    </Form.Item>

                    <Form.Item
                        label="角色"
                        name="roleId"
                        rules={[{ required: true, message: '请选择角色！' }]}
                    >
                        <Select style={{ width: '100%' }}>
                            {
                                roleList.map(item => {
                                    return <Select.Option value={item.id} key={item.id}>{item.name}</Select.Option>
                                })
                            }
                        </Select>
                    </Form.Item>

                    <Form.Item
                        label="状态"
                        name="status"
                        rules={[{ required: true, message: '请选择状态！' }]}
                    >
                        <Select style={{ width: '100%' }}>
                            <Select.Option value={0}>在职</Select.Option>
                            <Select.Option value={1}>出差</Select.Option>
                            <Select.Option value={2}>离职</Select.Option>
                        </Select>
                    </Form.Item>
                </Form>
            </Modal>
            <Modal
                maskClosable={false} width={500} title='用户账户' open={isAccountVisible}
                onOk={() => {
                    formAccount?.resetFields();
                    setIsAccountVisible(false)

                }}
                onCancel={() => {
                    formAccount?.resetFields();
                    setIsAccountVisible(false)
                }
                }
                footer={[
                    <Button
                        key="back"
                        onClick={() => {
                            formAccount?.resetFields();
                            setIsAccountVisible(false)
                        }}
                    >
                        返回
                    </Button>,
                    <Button key="submit" form="setupUserForm" type="primary" htmlType="submit">
                        提交
                    </Button>,
                ]}
            >
                <Form
                    form={formAccount}
                    name="basic"
                    id='setupUserForm'
                    onFinish={onBindAcction}
                >
                    <Form.Item
                        label="员工Id"
                        name="tB_Employee_Id"
                        hidden={true}
                    >
                        <Input />
                    </Form.Item>

                    <Form.Item
                        label="账户名"
                        name="account"
                        rules={[{ required: true, message: '请输入账户！' }]}
                    >
                        <Input placeholder='请输入自定义账号名' />
                    </Form.Item>
                </Form>
            </Modal>
        </div >
    );
};

export default User;
