import React, { useState, useCallback, useEffect } from "react";
import { Form } from "antd";
import { Input, Button } from "@ttk/component";
import { useActions, useData, useCommit } from "@ttk/app-loader";

export default React.memo(Header);
function Header(props) {
  return <Content {...props} />;
}

const Content = (props) => {
  const actions = useActions(props);
  const commit = useCommit();
  const { entity } = useData([props, "roleSearchParam"]).toJS();
  const { allocated } = useData([props, "showModal"]).toJS();
  const roleData = useData([props, "roleData"]).toJS();
  // 加载数据
  useEffect(() => {
    async function fetchData() {
      commit([props, "showState"], true);
      await actions.roleData();
      commit([props, "showState"], false);
    }
    fetchData();
  }, []);

  // 更新查询表单方法
  const updateForm = useCallback((e) => {
    async function asyncFun(arges) {
      await actions.roleSearch(e);
    }
    asyncFun(e);
  }, []);

  // 查询
  const onSearch = useCallback((e) => {
    commit([props, "showState"], true);
    actions.roleData();
    commit([props, "showState"], false);
  }, []);

  // 重置
  const onClear = useCallback((e) => {
    async function asyncFun() {
      commit([props, "showState"], true);
      commit([props, "roleSearchParam"], {
        type: "reset_search",
        data: { roleName: "", isNeedExists: "Y" },
      });
      actions.roleData();
      commit([props, "showState"], false);
    }
    asyncFun();
  }, []);
  //批量回收
  function remove() {
    const checkedData = roleData.filter((item) => {
      return item.selected;
    });
    actions.deleteItems(checkedData);
  }
  //批量分配
  function add() {
    const checkedData = roleData.filter((item) => {
      return item.selected;
    });
    actions.addItems(checkedData);
  }
  return (
    <div>
      <Form layout="inline">
        <Form.Item>
          <Input
            value={entity.roleName}
            onChange={(e) => updateForm({ roleName: e.target.value })}
            placeholder="角色名称"
          />
        </Form.Item>
        <Form.Item>
          <Button
            type="primary"
            onClick={onSearch}
            style={{ marginRight: "10px" }}
          >
            查询
          </Button>
          <Button onClick={onClear}>重置</Button>
        </Form.Item>
        <Form.Item style={{ float: "right", marginRight: 0 }}>
          {allocated ? (
            <Button type="primary" icon="delete" onClick={remove}>
              批量回收
            </Button>
          ) : (
            <Button type="primary" icon="plus" onClick={add}>
              批量分配
            </Button>
          )}
        </Form.Item>
      </Form>
    </div>
  );
};
