import React, { useState, useEffect, useRef } from 'react';
import styles from './index.less';
import { Space, Modal, Form, Input, Button, message, Select, DatePicker as TDatePicker, Popconfirm, Tag } from 'antd';
import roleAPI from "@/api/sys/Role";
import userAPI from "@/api/sys/User";
import moment from 'moment'
import md5 from 'js-md5'
import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import Password from 'antd/es/input/Password';

const DatePicker: any = TDatePicker;

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

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

    const [currentPerson, setCurrentPerson] = useState<UserTypes.PersonnelType>({
        phone: '',
        joinDate: '',
        outDate: '',
        idCard: '',
        stutas: 1,
        tB_RoleId: '',
        gender: 1,
        id: '',
        sort: 1,
        name: '',
        iCCard: ''
    });
    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',
        },
        {
            title: '电话',
            search: false,
            dataIndex: 'phone',
            key: 'phone'
        },
        {
            title: 'IC卡',
            search: false,
            dataIndex: 'icCard',
            key: 'icCard'
        },
        {
            title: '身份证',
            search: false,
            dataIndex: 'idCard',
            key: 'idCard'
        },
        {
            title: '性别',
            dataIndex: 'gender',
            key: 'gender',
            valueType: 'select',
            valueEnum: {
                0: {
                    text: '全部'
                },
                1: {
                    text: '男'
                },
                2: {
                    text: '女',
                }
            },
            render: (_, record) => (
                <>
                    {
                        record.gender === 1 ?
                            <div style={{ color: 'green' }}>
                                男
                            </div>
                            :
                            <div style={{ color: 'green' }}>
                                女
                            </div>
                    }
                </>
            )
        },
        {
            title: '入职时间',
            dataIndex: 'joinDate',
            key: 'joinDate',
            valueType: 'date',
            render: (_, record) => (<>
                {
                    (() => {
                        return <div>{moment(record.joinDate).format('yyyy-MM-DD')}</div>
                    })()
                }
            </>)
        },
        {
            title: '离职时间',
            dataIndex: 'outDate',
            search: false,
            key: 'outDate',
            render: (_, record) => (<>
                {
                    (() => {
                        return record.outDate === null ? '-' : <div>{moment(record.outDate).format('yyyy-MM-DD')}</div>
                    })()
                }
            </>)
        },
        {
            title: '角色',
            search: false,
            dataIndex: 'roleId',
            key: 'roleId',
            render: (_, record) => (
                <>
                    {
                        (() => {
                            const role = roleList.find(item => item.id === record.tB_RoleId);
                            if (role) {
                                return <div>{role.name}</div>
                            } else {
                                return <div>未知角色</div>
                            }
                        })()
                    }
                </>
            )
        },
        {
            title: '状态',
            dataIndex: 'stutas',
            key: 'stutas',
            valueType: 'select',
            valueEnum: {
                0: {
                    text: '全部'
                },
                1: {
                    text: '在职'
                },
                2: {
                    text: '出差',
                },
                3: {
                    text: '离职',
                }
            },
            render: (_, record) => (
                <>
                    {
                        record.stutas === 1 ?
                            <div style={{ color: 'green' }}>
                                在职
                            </div>
                            :
                            (record.stutas === 2 ? <div style={{ color: 'Orange' }}>
                                出差
                            </div> : <div style={{ color: 'red' }}>
                                离职
                            </div>)

                    }
                </>
            )
        },
        {
            title: '操作',
            search: false,
            key: 'action',
            render: (_, record) => (
                <Space size="middle" >
                   { 
                 
                 <a onClick={() => {
                        setIsAccountVisible(true);
                        formAccount.setFieldValue('tB_Employee_Id', record.id);
                        formAccount.setFieldValue('account', record.account!);
                    }}>账户设置</a>
                   
                    }
                    <a onClick={async () => {
                        const response = await userAPI.RestoreAccount(record.id!);
                        if (response.data === true) {
                            message.success('成功!');
                        } else {
                            message.error(response.msg || '重置失败');
                        }
                    }}>重置密码</a>
                    <a onClick={() => {
                        setIsPersonDetailVisible(true);
                        setCurrentPerson(record);
                        const tempRecord = JSON.parse(JSON.stringify(record));
                        tempRecord.joinDate = moment(record.joinDate)
                        if (record.outDate !== null) {
                            tempRecord.outDate = moment(record.outDate)
                        }
                        form.setFieldsValue(tempRecord);
                    }}>查看详情</a>
                    <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="关闭"
        >
          <Button  type="primary" danger ghost>删除员工</Button>
        </Popconfirm>
                </Space>
            ),
        },
    ];

    const onAddPerson = () => {
        setCurrentPerson({
            phone: '',
            joinDate: '',
            outDate: '',
            idCard: '',
            stutas: 1,
            tB_RoleId: '',
            gender: 1,
            id: '',
            sort: 1,
            name: '',
            iCCard: ''
        });
        form.resetFields();
        setIsPersonDetailVisible(true);
    }

    /**
    * 获取角色列表
    */
    const onFetchRoleList = async () => {
        const response = await roleAPI.GetRoleList();
        if (response.statusCode === 200) {
            setRoleList(response.data);
        } else {
            message.error(response.msg || '获取角色列表失败');
        }
    }

    /**
     * 新增/更新人员信息
     */
    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();
        onFetchRoleList();
    }
    /**
     * 绑定用户账户
     */
    const onBindAcction = async (acc: Account.TBAccountDTO) => {
        // 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
                request={async (params = {}) => {
                    const response = await userAPI.GetUserPagedList({
                        keyword: params.name,
                        joinDate: params.joinDate,
                        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
                }}
                dateFormatter="string"
                headerTitle="员工列表"
                toolBarRender={() => [
                    <Button key="button" icon={<PlusOutlined />} type="primary" onClick={() => onAddPerson()}>
                        添加
                    </Button>
                ]}
            />
            <Modal footer={null} width={500} title={currentPerson.id === '' ? '新增人员' : '编辑人员'} open={isPersonDetailVisible} onOk={() => setIsPersonDetailVisible(false)} onCancel={() => setIsPersonDetailVisible(false)}>
                <Form
                    form={form}
                    name="basic"
                    onFinish={onFinishPerson}
                >
                    <Form.Item
                        label="id"
                        name="id"
                        hidden={true}
                    >
                        <Input />
                    </Form.Item>

                    <Form.Item
                        label="电话"
                        name="phone"
                        rules={[{ required: true, message: '请输入联系电话！' }]}
                    >
                        <Input />
                    </Form.Item>

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

                    <Form.Item
                        label="身份证"
                        name="idCard"
                        rules={[{ required: true, message: '请输入身份证！' }]}
                    >
                        <Input />
                    </Form.Item>

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

                    <Form.Item
                        label="角色"
                        name="tB_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="stutas"
                        rules={[{ required: true, message: '请选择状态！' }]}
                    >
                        <Select style={{ width: '100%' }}>
                            <Select.Option value={1}>在职</Select.Option>
                            <Select.Option value={2}>出差</Select.Option>
                            <Select.Option value={3}>离职</Select.Option>
                        </Select>
                    </Form.Item>

                    <Form.Item
                        label="入职日期"
                        name="joinDate"
                        rules={[{ required: true, message: '请输入入职日期！' }]}
                    >
                        <DatePicker format="YYYY-MM-DD" />
                    </Form.Item>

                    <Form.Item
                        label="离职日期"
                        name="outDate"
                        rules={[{ required: false, message: '请输入离职日期！' }]}
                    >
                        <DatePicker format="YYYY-MM-DD" />
                    </Form.Item>

                    <Form.Item >
                        <Button type="primary" htmlType="submit">
                            确定
                        </Button>
                    </Form.Item>
                </Form>
            </Modal>
            <Modal footer={null} width={500} title='用户账户' open={isAccountVisible} 
             onOk={()=>
                {
                    formAccount?.resetFields(); 
                setIsAccountVisible(false)
               
             }} 
               onCancel={()=>{ 
                formAccount?.resetFields(); 
               setIsAccountVisible(false)
                }
            }>
                <Form
                    form={formAccount}
                    name="basic"
                    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.Item >
                        <Button type="primary" htmlType="submit">
                            确定
                        </Button>
                    </Form.Item>
                </Form>
            </Modal>
        </div >
    );
};

export default User;
