import React from "react";
import { Button, Input, List, Popconfirm, Spin, Modal, message } from "antd";
import useBool from "@/utils/hooks/useBool";
import classNames from "classnames";
import {
  getSysRole,
  postSysRole,
  putSysRole,
  deleteSysRole,
} from "@/service/sysrole";
import "./style.less";

const Header = (props) => {
  return (
    <div className="role-list-header">
      <div className="role-list-header-body">{props.children}</div>
      <div className="role-list-header-action">{props.action}</div>
    </div>
  );
};

export default (props) => {
  const { current, onChange } = props;

  const [loading, startLoading, cancelLoading] = useBool();
  const [visible, openModel, hideModel] = useBool();
  const [finished, setFinished] = React.useState(false);
  const [inText, setInText] = React.useState();
  const [list, setList] = React.useState([]);

  const onAdd = () => {
    openModel();
    setInText();
    onChange();
  };

  const onEdit = (item) => {
    openModel();
    setInText(item.name);
    onChange(item);
  };

  const onDelete = (item) => {
    startLoading();
    // 删除角色
    deleteSysRole(item.roleId)
      .then(() => {
        setList(list.filter((x) => x.roleId !== item.roleId));
        cancelLoading();
        hideModel();
        onChange();
      })
      .catch(() => {
        cancelLoading();
      });
  };

  const handleOk = () => {
    if (!inText) {
      message.warn("请输入角色名称");
      return;
    }
    startLoading();
    const data = { name: inText };

    if (current) {
      // 修改角色
      putSysRole(current.roleId, data)
        .then((res) => {
          setList(list.map((x) => (x.roleId === current.roleId ? res : x)));
          cancelLoading();
          hideModel();
        })
        .catch(() => {
          cancelLoading();
        });
    } else {
      // 新增角色
      postSysRole(data)
        .then((res) => {
          setList([res].concat(list));
          cancelLoading();
          hideModel();
          onChange(res);
        })
        .catch(() => {
          cancelLoading();
        });
    }
  };

  const handleCancel = () => {
    if (loading) {
      return;
    }

    hideModel();
  };

  const queryRoles = React.useCallback((params) => {
    startLoading();
    getSysRole(params)
      .then((res) => {
        setList(res.records);
        cancelLoading();
        setFinished(res.current >= res.pages);
      })
      .catch(() => {
        cancelLoading();
      });
  }, []);

  React.useEffect(() => {
    queryRoles({ pageNum: 1, pageSize: 500 });
  }, []);

  return (
    <Spin spinning={loading}>
      <List
        header={
          <Header
            action={
              <Button type="primary" onClick={onAdd}>
                新增
              </Button>
            }
          >
            角色列表
          </Header>
        }
        style={{ background: "#fff" }}
        bordered
        dataSource={list}
        renderItem={(item) => (
          <List.Item
            className={classNames("role-list-item", {
              active: current && current.roleId === item.roleId,
            })}
            onClick={() => onChange(item)}
            actions={[
              <Button key="edit" type="link" onClick={() => onEdit(item)}>
                编辑
              </Button>,
              <Popconfirm
                key="delete"
                title="确认删除?"
                onConfirm={() => onDelete(item)}
              >
                <Button type="link" danger>
                  删除
                </Button>
              </Popconfirm>,
            ]}
          >
            {item.name}
          </List.Item>
        )}
      />
      <Modal
        title="请输入角色名称"
        open={visible}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Input value={inText} onChange={(e) => setInText(e.target.value)} />
      </Modal>
    </Spin>
  );
};
