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 BTable from "@/components/b_table";
import SimpleForm from "@/components/form/simple_form";
import { columns, formConfig } from "./config";
const History = (props: Store) => {
  const { cityhisStore } = 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(() => {
    cityhisStore.getlist();
  }, [cityhisStore]);

  return (
    <div className="contentBox">
      <Space direction="vertical" size="middle" style={{ display: "flex" }}>
        <Button type="default" onClick={() => setIsModalOpen(true)}>
          添加
        </Button>
        <BTable
          store={cityhisStore}
          scroll={{ x: "max-content" }}
          columns={columns}
          dataSource={cityhisStore.list}
          deleteCallback={(record) => {
            cityhisStore.deleteItem(record);
          }}
          editCallback={(record) => {
            let data = {...record}
            data.cover = [{url:record.cover}]
            formRef.current?.setFieldsValue(data);
            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={() => {
              let data = formRef.current?.getFieldsValue();
              data.cover = data.cover[0].url;
              cityhisStore.add(data);
              setIsModalOpen(false);
            }}
            createCallback={() => {
              formRef.current?.setFieldsValue(record);
            }}
            formDatas={formConfig as any}
          ></SimpleForm>
        </Modal>
      </Space>
    </div>
  );
};

export default inject("cityhisStore")(observer(History));
