import { Button, Card, Form, Input, message, Modal, Table } from 'antd';
import React, { useEffect, useState, useRef } from 'react';
import TemplateContainer from '@/pages/TemplateContainer';
import { ExclamationCircleOutlined, PlusOutlined } from '@ant-design/icons';
import { ColumnsType, TablePaginationConfig } from 'antd/es/table';
import { DeleteRoleById, QueryRoleList } from '@/services/services/role';
import { FormatDate } from '@/util/time';
import ManageRoleModal from '../ManageRoleModal';
import { useFormReset } from '@/hooks/useFormReset';
import AddRoleForm from '../AddRoleForm';
import { FilterValue, SorterResult, TableCurrentDataSource } from 'antd/es/table/interface';
import { useModel } from '@umijs/max';


const RoleManagement: React.FC = () => {
  const { initialState } = useModel('@@initialState');
  const [data, setData] = useState<RoleModel.Collection[]>(); // 数据
  const [form] = Form.useForm();
  const { setFormRef, resetForm } = useFormReset();

  let [loading, setLoading] = useState<boolean>(true);
  const [roleId, setRoleId] = useState<number>(0);
  const [openModal, setOpenModal] = useState<boolean>(false);
  const [modal, contextHolder] = Modal.useModal();
  const [modalTitle, setModalTitle] = useState<string>("编辑角色");
  const [type, setType] = useState<string>("edit");
  const [messageApi, messageHolder] = message.useMessage();

  const [tableParams, setTableParams] = useState<TableModel.TableParams>({
    pagination: {
      current: 1,
      pageSize: 10,
      showQuickJumper: true,
      totalBoundaryShowSizeChanger: true,
    },
  });
  useEffect(() => {
    // 初始化加载数据
    QueryRoleList(tableParams, form.getFieldsValue())
      .then((res) => {
        setData(res.collection);
        setTableParams({
          pagination: {
            ...tableParams.pagination,
            total: res.total
          }
        })
        setLoading(false);
      })
      .catch((error) => {
        messageApi.error(error.message);
      }).finally(() => {
        setLoading(false);
      })
  }, []);

  async function modalCancel() {
    try {
      resetForm();
      setOpenModal(false);
      setLoading(true);
      let res = await QueryRoleList(tableParams, form.getFieldsValue());
      setData(res.collection);
    } catch (error: any) {
      messageApi.error(error.message);
    } finally {
      setLoading(false);
    }
  }

  async function QueryRoleByName(values: any): Promise<void> {
    setLoading(true);
    try {
      let queryRole = await QueryRoleList(tableParams, values);
      setData(queryRole.collection);
      setTableParams({
        pagination: {
          ...tableParams.pagination,
          total: queryRole.total
        }
      })
    } catch (error: any) {
      messageApi.error(error.message);
    } finally {
      setLoading(false);
    }
  }

  function DeleteRole(roleId: number) {
    try {
      modal.confirm({
        title: '确认删除',
        icon: <ExclamationCircleOutlined />,
        content: '是否确认删除选中的角色，改操作不可逆，请谨慎操作！',
        okText: '确认',
        cancelText: '取消',
        onOk: async () => {
          // 开始删除
          try {
            await DeleteRoleById(roleId);
            await QueryRoleByName(form.getFieldsValue());
            messageApi.success("删除角色成功");
          } catch (error: any) {
            messageApi.error(error.message);
          }
        },
        onCancel: async () => {
          await QueryRoleByName(form.getFieldsValue());
        },
      });
    } catch (error) {

    }
  }

  function AddRole() {
    setModalTitle("新增角色");
    setOpenModal(true);
    setType("add");
  }

  const columns: ColumnsType<RoleModel.Collection> = [
    {
      title: 'ID',
      dataIndex: 'id',
      sorter: true,
      width: '100px',
    },
    {
      title: '角色名',
      dataIndex: 'name',
      width: '200px',
    },
    {
      title: '创建者',
      dataIndex: 'createdUser',
      width: '150px',
      render: (text, record) => record.createdUser?.nickName,
    },
    {
      title: '更新者',
      dataIndex: 'updeatedUser',
      width: '150px',
      render: (text, record) => record.updeatedUser?.nickName,
    },
    {
      title: '创建时间',
      dataIndex: 'createdTime',
      render: (text, record) => FormatDate(record.createdTime),
      width: '200px',
    },
    {
      title: '更新时间',
      dataIndex: 'updatedTime',
      render: (text, record) => FormatDate(record.updatedTime),
      width: '200px',
    },
    {
      title: '备注',
      dataIndex: 'remark',
    },
    {
      title: '操作',
      width: '120px',
      render: (text, record) => (
        <div style={{ display: "flex" }}>
          <Button size='small' style={{ marginRight: 5 }} type="primary" onClick={() => {
            setRoleId(record.id);
            setModalTitle("编辑角色");
            setOpenModal(true);
            setType("edit");
          }}>编辑</Button>
          <Button danger size='small' type="primary" onClick={() => DeleteRole(record.id)}>删除</Button>
        </div>
      ),
    },
  ];


  async function handleTableChange(pagination: TablePaginationConfig, filters: Record<string, FilterValue | null>, sorter: SorterResult<RoleModel.Collection> | SorterResult<RoleModel.Collection>[], extra: TableCurrentDataSource<RoleModel.Collection>): Promise<void> {
    setLoading(true);
    try {
      let queryRole = await QueryRoleList({ pagination }, form.getFieldsValue());
      setData(queryRole.collection);
      setTableParams({
        pagination: {
          ...pagination,
          total: queryRole.total
        }
      })
    } catch (error: any) {
      messageApi.error(error.message);
    } finally {
      setLoading(false);
    }
  }

  return (
    <TemplateContainer navTheme={initialState?.settings?.navTheme ?? "realDark"}>
      <div>
        <Form
          layout='inline'
          form={form}
          onFinish={QueryRoleByName}
        >
          <Form.Item label="角色ID" name='roleId'>
            <Input placeholder="请输入角色ID" />
          </Form.Item>
          <Form.Item label="角色名称" name='roleName'>
            <Input placeholder="请输入角色名称" />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType='submit'>查询</Button>
          </Form.Item>
          <Form.Item>
            <Button type="primary" icon={<PlusOutlined />} onClick={AddRole}>新增</Button>
          </Form.Item>
        </Form>
        <Table<RoleModel.Collection>
          columns={columns}
          rowKey={(record) => record.id}
          dataSource={data}
          pagination={tableParams.pagination}
          loading={loading}
          onChange={handleTableChange}
        />
      </div>

      <Modal title={modalTitle} maskClosable={false} open={openModal} footer={null} onCancel={modalCancel}>
        {
          type === "edit" ? <ManageRoleModal setFormRef={setFormRef} roleId={roleId} /> : <AddRoleForm setFormRef={setFormRef}></AddRoleForm>
        }
      </Modal>
      {contextHolder}
      {messageHolder}
    </TemplateContainer>
  )
}

export default RoleManagement;