import { PlusOutlined } from '@ant-design/icons';
import {
  ProTable,
  ProForm,
  ProFormText,
  ModalForm,
  ProFormSelect
} from '@ant-design/pro-components';
import { Button, Card, Space,Popconfirm, message } from 'antd';
import { useRef, useState, useEffect } from 'react';
import { adminUserConnect, adminUserUpdateConnect, adminUserRemoveConnect, adminUserAddConnect, adminRolesConnect } from '@/services/Limits/index';
import { PageContainer } from '@ant-design/pro-layout';


export default () => {

  const formRef = useRef<any>();
  const [modalVisit1, setModalVisit1] = useState(false);
  const [addVis, setAddVis] = useState(true);
  const [removeVis, setRemoveVis] = useState(true);
  const [editVis, setEditVis] = useState(true);
  const [searchVis, setSearchVis] = useState(true);
  const [editData, setEditData] = useState({});
  const [roleId, setRoleId] = useState<any>(null);
  const [activeType, setActiveType] = useState<any>('add');
  const [roleData, setRoleData] = useState<any>([]);


  useEffect(() => {
    initRoleData()  // 加载角色列表
  }, [])

  // 加载角色列表
  const initRoleData = () => {

    adminRolesConnect({
      // query
      /** 当前的页码 */
      current: 1,
      /** 页面的容量 */
      pageSize: 999
    }).then((res: any) => {
      setRoleData(res?.data)
    })
  };

  // 查看详情
  const onView = (record: any) => {
    setTimeout(() => {
      formRef?.current?.setFieldsValue(record);
      formRef?.current?.setFieldsValue({ role: record?.authorities[0]?.id });
      setEditData(record)
      setRoleId(record?.id)
    }, 100)
  };


  // 用户修改
  const userUpdate = (e: any) => {
    let data = { ...editData, ...e } as Object
    adminUserUpdateConnect(roleId, data).then((res: any) => {
      console.log(res);
      message.success('用户修改成功');
    })
  };


  // 用户修改
  const userAdd = (e: any) => {
    let data = { ...e } as Object
    adminUserAddConnect(data).then((res: any) => {
      console.log(res);
      message.success('用户新增成功');
    })
  };

  const columns = [
    { align: 'center', search: false, title: "序号", width: 68, render: (text, record, index) => `${index + 1}`, },
    {
      dataIndex: 'username',
      title: '用户名称',
      align: 'center',
      key: '1',
    },
    {
      dataIndex: 'login',
      title: '用户角色',
      align: 'center',
      key: '2',
      search: false,
      render: (_, record) => {
        return [
          <>
            <Space>{record?.authorities[0]?.name}</Space>
          </>
        ];
      },
    },
    {
      dataIndex: 'email',
      title: '联系方式',
      key: '3',
      align: 'center',
      search: false,
    },
    {
      dataIndex: 'status',
      title: '状态',
      key: '4',
      align: 'center',
      search: false,
    },
    {
      title: '操作',
      dataIndex: 'x',
      align: 'center',
      valueType: 'option',
      key: '5',
      render: (_, record) => {
        return [
          <> <Button
            key="editable"
            type="primary"
            style={!editVis ? {} : { background: '#2db7f5', border: 'none' }}
            disabled={!editVis}
            onClick={async (e) => {
              setModalVisit1(true);
              setActiveType('update')
              await onView(record);
            }}
          >
            修改
          </Button> </>,
          <>
            <Popconfirm
              title="确认删除？"
              onConfirm={() => {
                adminUserRemoveConnect(record?.id).then((res: any) => {
                  console.log(res);
                  message.success('删除成功');
                })
              }}
              onCancel={() => { }}
              disabled={!removeVis}
            >
              <Button
                key="remove"
                type="primary"
                danger
                disabled={!removeVis}
              >
                删除
              </Button>
            </Popconfirm>
          </>
        ];
      },
    },
  ];





  return (
    <PageContainer>
      <ProTable
        columns={columns}
        request={adminUserConnect}
        rowKey="id"
        cardBordered
        pagination={{
          showQuickJumper: true,
        }}
        search={searchVis ? {
          labelWidth: 'auto',
        } : false}
        toolBarRender={() => [
          <>
            <Button
              key="button"
              icon={<PlusOutlined />}
              type="primary"
              disabled={!addVis}
              onClick={() => {
                setModalVisit1(true);
                setActiveType('add')
                formRef?.current?.resetFields();
              }}
            >
              新建
            </Button>
          </>
        ]}
      />

      {/* 角色新建和修改 */}
      <ModalForm
        formRef={formRef}
        title="角色设置"
        visible={modalVisit1}
        onVisibleChange={setModalVisit1}
        onFinish={(e) => {
          if (activeType === 'add') {
            userAdd(e)   // 新增
          } else {
            userUpdate(e)   // 修改
          }
          return true;
        }}
      >
        <Card>
          <ProForm.Group>
            <ProFormText width="md" name="username" label="用户名称" placeholder="请输入用户名称" />
          </ProForm.Group>
          <ProForm.Group>
            <ProFormText.Password width="md" name="password" label="用户密码" placeholder="请输入用户密码" />
          </ProForm.Group>
          <ProForm.Group>
            <ProFormSelect
              name="role"
              label="用户角色"
              width="md"
              request={async () => roleData}
              placeholder="请选择用户角色"
              fieldProps={{
                fieldNames: {
                  label: 'name', value: 'id'
                }
              }}
            />
          </ProForm.Group>
          <ProForm.Group>
            <ProFormText width="md" name="email" label="联系方式" placeholder="请输入联系方式" />
          </ProForm.Group>
        </Card>
      </ModalForm>
    </PageContainer>
  );

};