import { userPage, userUpPwd, userInfo, userUpdate, userAdd, userDelete } from '@/services/system/user';


import React, { useState, useRef, useEffect } from 'react';
import { useIntl, FormattedMessage, useAccess } from '@umijs/max';
import { Button, message, Modal, Tag, Image } from 'antd';
import { ActionType, PageContainer, ProColumns, ProTable } from '@ant-design/pro-components';
import { PlusOutlined } from '@ant-design/icons';
import UpdateForm from './edit';








/**
 * 添加节点
 *
 * @param fields
 */
const handleAdd = async (fields: API.System.Menu) => {
  const hide = message.loading('正在添加');
  try {
    await userAdd({ ...fields });
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    return false;
  }
};

/**
 * 更新节点
 *
 * @param fields
 */
const handleUpdate = async (fields: API.System.Menu) => {
  const hide = message.loading('正在修改');
  try {
    await userUpdate(fields);
    hide();
    message.success('修改成功');
    return true;
  } catch (error) {
    hide();
    return false;
  }
};

const handleRemoveOne = async (selectedRow: API.System.Menu) => {
  const hide = message.loading('正在删除');
  if (!selectedRow) return true;
  try {
    const params = [selectedRow.id];
    await userDelete(params);
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    return false;
  }
};


const UserTableList: React.FC = () => {
  const [modalVisible, setModalVisible] = useState<boolean>(false);
  const [currentRow, setCurrentRow] = useState();

  const actionRef = useRef<ActionType>();
  /** 国际化配置 */
  const intl = useIntl();
  const access = useAccess();
  useEffect(() => {

    // getDictValueEnum('sys_show_hide').then((data) => {  
    //   setVisibleOptions(data);
    // });
    // getDictValueEnum('sys_normal_disable').then((data) => {
    //   setStatusOptions(data);
    // });
  }, []);

  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      valueType: 'text',
      search: false,
    },
    {
      title: '用户信息',
      dataIndex: 'username',
      valueType: 'text',
      search: false,
      render: (_: any, record: any) => {
        return <div className='flex'>
          {/* <Image src={record.avatar} width={45} height={45}></Image> */}
          <div>
            <div>
              昵称：{record.nickName}
            </div>
            <div>
              用户名：{record.username}
            </div>
            <div>
              手机号：{record.phoneNumber}
            </div>
          </div>
        </div>
      }
    },
    {
      title: '角色',
      dataIndex: 'sysRoleDTOList',
      valueType: 'text',
      render: (_: any, record: any) => {
        return record?.sysRoleDTOList?.map((item: any) => {
          return <Tag key={item.id}>{item.roleName}</Tag>
        })
      }
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      valueType: 'text',
      search: false,
    },
    {
      title: '性别',
      dataIndex: 'sexName',
      valueType: 'text',
      search: false,
    },
    {
      title: '最后登录IP',
      dataIndex: 'loginIp',
      valueType: 'text',
      search: false,
    },
    {
      title: '最后登录时间',
      dataIndex: 'loginDate',
      valueType: 'text',
      search: false,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      search: false,
    },
    {
      title: <FormattedMessage id="pages.searchTable.titleOption" defaultMessage="操作" />,
      dataIndex: 'option',
      width: '220px',
      valueType: 'option',
      render: (_, record: any) => [
        <Button
          type="link"
          size="small"
          hidden={!access.hasPerms('/api/sys/user/update')}
          onClick={() => {
            setModalVisible(true);
            setCurrentRow(record);
          }}
        >
          编辑
        </Button>,
        <Button
          type="link"
          size="small"
          danger
          hidden={!access.hasPerms('/api/sys/user/deleteUserBatchByIds')}
          onClick={async () => {
            Modal.confirm({
              title: '删除',
              content: '确定删除该项吗？',
              okText: '确认',
              cancelText: '取消',
              onOk: async () => {
                const success = await handleRemoveOne(record);
                if (success) {
                  if (actionRef.current) {
                    actionRef.current.reload();
                  }
                }
              },
            });
          }}
        >
          删除
        </Button>,
      ],
    },

  ];

  return (
    <PageContainer>
      <div style={{ width: '100%', float: 'right' }}>
        <ProTable<API.System.Menu>
          actionRef={actionRef}
          rowKey="id"
          key="userList"
          search={{
            labelWidth: 120,
          }}
          toolBarRender={() => [
            <Button
              type="primary"
              key="add"
              hidden={!access.hasPerms('/api/sys/user/add')}
              onClick={async () => {
                setCurrentRow(undefined);
                setModalVisible(true);
              }}
            >
              <PlusOutlined /> 新增
            </Button>,
            // <Button
            //   type="primary"
            //   onClick={async () => {
            //     setCurrentRow(undefined);
            //     setModalVisible(true);
            //   }}
            // >
            //   修改密码
            // </Button>
          ]}
          request={async (params, sorter, filter) => {
            let { data } = await userPage(params)
            return {
              data: data?.records || [],
              total: data?.total,
            };
          }}
          columns={columns}
        />
      </div>
      <UpdateForm
        onSubmit={async (values) => {
          let success = false;
          if (values.id) {
            success = await handleUpdate({ ...values });
          } else {
            success = await handleAdd({ ...values });
          }
          if (success) {
            setModalVisible(false);
            setCurrentRow(undefined);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          setModalVisible(false);
          setCurrentRow(undefined);
        }}
        open={modalVisible}
        values={currentRow || {}}
      />
    </PageContainer>
  );
};

export default UserTableList;
