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, "searchParam"]).toJS();
  // 加载数据
  useEffect(() => {
    async function fetchData() {
      // 获取列表数据
      commit([props, "showState"], true);
      await actions.tableData();
      commit([props, "showState"], false);
    }
    fetchData();
  }, []);

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

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

  // 重置
  const onClear = useCallback((e) => {
    async function asyncFun() {
      commit([props, "showState"], true);
      commit([props, "searchParam"], {
        type: "reset_search",
        data: { insId: "" },
      });
      actions.tableData();
      commit([props, "showState"], false);
    }
    asyncFun();
  }, []);
  //新增
  const onAdd = useCallback((e) => {
    commit([props, "showModal"], { type: "visible", data: true });
    commit([props, "showModal"], { type: "isEdit", data: false });
    commit([props, "FormData"], { type: "reset" });
    commit([props, "validateState"], { type: "reset" });
  }, []);

  return (
    <div>
      <Form layout="inline">
        <Form.Item>
          <Input
            value={entity.insId}
            onChange={(e) => updateForm({ insId: 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 }}>
          <Button type="primary" onClick={onAdd}>
            新增
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
};
