import React from "react";
import { Button, Space, Modal, FormInstance } from "antd";
import { Store } from "antd/lib/form/interface";
import { inject, observer } from "mobx-react";
import { useEffect, useState } from "react";
import { columns, formConfig } from "./config";
import BTable from "@/components/b_table";
import SimpleForm from "@/components/form/simple_form";
const City = (props: Store) => {
  const { cityStore } = props;
  const [isModalOpen, setIsModalOpen] = useState<boolean>(false);
  const formRef = React.useRef<FormInstance>(null);
  const [userId, setId] = useState<Number | null>(null);
  const [record, setRecord] = useState<any>(null);

  // 获取列表数据
  useEffect(() => {
    cityStore.getlist();
  }, [cityStore]);

  return (
    <div className="contentBox">
      <Space direction="vertical" size="middle" style={{ display: "flex" }}>
        <Button type="default" onClick={() => setIsModalOpen(true)}>
          添加
        </Button>
        <BTable
          store={cityStore}
          scroll={{ x: "max-content" }}
          columns={columns}
          dataSource={cityStore.list}
          deleteCallback={(record) => {
            cityStore.deleteItem(record);
          }}
          editCallback={(record) => {
            setIsModalOpen(true);
            formRef.current?.setFieldsValue(record);
            setRecord(record);
            setId(record.id);
          }}
        />

        <Modal
          title={!userId ? "添加" : "编辑"}
          width={800}
          open={isModalOpen}
          afterClose={() => formRef.current?.resetFields()}
          onOk={() => formRef.current?.submit()}
          okText="确定"
          cancelText="取消"
          onCancel={() => {
            setId(null);
            setRecord(null);
            setIsModalOpen(false);
          }}
        >
          <SimpleForm
            formName={"city_form"}
            formRef={formRef}
            colProps={25}
            onFinish={() => {
              cityStore.add(formRef.current?.getFieldsValue())
              setIsModalOpen(false);
            }}
            createCallback={() => {
              formRef.current?.setFieldsValue(record);
            }}
            formDatas={formConfig as any}
          ></SimpleForm>
        </Modal>
      </Space>
    </div>
  );
};

export default inject("cityStore")(observer(City));
