import { useEffect, useState } from "react";
import {
  Button,
  Checkbox,
  Form,
  Input,
  message,
  PaginationProps,
  Popconfirm,
  Space,
  Table,
  Typography,
} from "antd";
import { Store } from "antd/lib/form/interface";
import { inject, observer } from "mobx-react";
import "./source.less";
import { DataType } from "@/util/model/interface";
import Upload from "./upload";
const Source = (props: Store) => {
  const { sourceStore } = props;
  const [form] = Form.useForm();
  const [coloums, setColumns] = useState<any>([]);
  const [content, setContent] = useState([]);
  const [selectKey, setSelectKey] = useState<Array<string>>([]);
  const [page, setPage] = useState<number>(1);
  const [editingKey, setEditingKey] = useState("");
  const [loading, setLoading] = useState(false);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const isEditing = (record) => record.key === editingKey;
  const edit = (record: any) => {
    form.setFieldsValue({ ...record });
    setEditingKey(record.key);
  };
  // 获取列表数据
  useEffect(() => {
    sourceStore.getHead().then((res) => {
      res.forEach((element) => {
        element.dataIndex = "dbs_" + element.identity.toLowerCase();
        element.title = element.data_name;
        element.label = element.data_name;
        element.value = element.identity;
        element.editable = true;
      });
      setColumns(res);
    });
    getContent([], 1);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [sourceStore]);
  const save = async (key: React.Key) => {
    try {
      const row = (await form.validateFields()) as DataType;
      const newData: any = [...content];
      const index = newData.findIndex((item: any) => key === item.key);
      if (index > -1) {
        const item = newData[index];
        setLoading(true);
        let res = await sourceStore.modefyData(row, item.id_card);
        if (res) {
          getContent(selectKey, 1);
        }
        setLoading(false);
        setEditingKey("");
      }
    } catch (errInfo) {
      console.log("Validate Failed:", errInfo);
    }
  };
  const getContent = (list, index) => {
    sourceStore.geContent(list, index, 20).then((res) => {
      res.forEach((element) => {
        element.key = "dbs_" + element.identity;
      });
      setContent(res);
    });
  };
  const saveClo = () => {
    if (selectKey.length === 0) {
      message.info("请勾选需要收藏的数据");
    }
  };
  const cancel = () => {
    setEditingKey("");
  };
  interface EditableCellProps extends React.HTMLAttributes<HTMLElement> {
    editing: boolean;
    dataIndex: string;
    fixed: string;
    index: number;
  }
  const actionCloumn = {
    title: "操作",
    with: 200,
    fixed: "right",
    render: (_: any, record) => {
      const editable = isEditing(record);
      return editable ? (
        <span>
          <Typography.Link
            onClick={() => {
              save(record.key);
            }}
            style={{ marginInlineEnd: 8 }}
          >
            保存
          </Typography.Link>
          <Popconfirm title="Sure to cancel?" onConfirm={cancel}>
            取消
          </Popconfirm>
        </span>
      ) : (
        <Space>
          <Typography.Link
            disabled={editingKey !== ""}
            onClick={() => edit(record)}
          >
            编辑
          </Typography.Link>
          <Popconfirm
            title="删除确认"
            description="您是否需要删除该数据?"
            onConfirm={() => {
              // deleteCallback(record.identity);
            }}
            onCancel={cancel}
            okText="Yes"
            cancelText="No"
          >
            <Button type="dashed" danger size="small">
              删除
            </Button>
          </Popconfirm>
        </Space>
      );
    },
  };

  const EditableCell: React.FC<React.PropsWithChildren<EditableCellProps>> = ({
    editing,
    dataIndex,
    children,
    ...restProps
  }) => {
    const inputNode = <Input />;

    return (
      <td {...restProps}>
        {editing ? (
          <Form.Item name={dataIndex} style={{ margin: 0 }}>
            {inputNode}
          </Form.Item>
        ) : (
          children
        )}
      </td>
    );
  };

  const mergedColumns = coloums.map((col) => {
    if (!col.editable) {
      return col;
    }
    return {
      ...col,
      onCell: (record: DataType) => ({
        record,
        dataIndex: col.dataIndex,
        title: col.title,
        editing: isEditing(record),
      }),
    };
  });
 
  const onChange: PaginationProps["onChange"] = (page) => {
    setPage(page);
    getContent(selectKey, page);
    cancel();
  };
  const rowSelection = {
    selectedRowKeys,
    preserveSelectedRowKeys: true,
    fixed: true,
    onChange: (keys, rowKeys, info) => {
      setSelectedRowKeys(keys);
    },
  };
  return (
    <div className="contentBox">
      <Space direction="vertical" size="middle" style={{ display: "flex" }}>
        <Upload />
        <Space>
          <Checkbox.Group
            options={coloums}
            defaultValue={[
              "01JM4XMY2N9KN23XSZJSQQM3HY",
              "01JM4XMY2N9KN23XSZJSWQHHKA",
              "01JM4XMY2N9KN23XSZJW02PRCF",
              "01JM4XMY2N9KN23XSZJYCKT6XQ",
              "01JM4XMY2N9KN23XSZK0AJ6QEZ",
              "01JM4XMY2N9KN23XSZK10KM59Y",
              "01JM4XMY2N9KN23XSZK479Y59M",
              "01JM4XMY2N9KN23XSZK5F8Z2J8",
              "01JM4XMY2N9KN23XSZK6W7Q25F",
              "01JM4XMY2N9KN23XSZK7ET1GEB",
              "01JM4XMY2N9KN23XSZK9DNRCZZ",
            ]}
            onChange={(v) => {
              setSelectKey(v);
              getContent(v, 1);
            }}
          />
          <Button onClick={saveClo}>收藏</Button>
        </Space>

        <Form form={form} component={false}>
          <Table
            loading={loading}
            scroll={{ x: "max-content", scrollToFirstRowOnChange: true }}
            components={{
              body: { cell: EditableCell },
            }}
            bordered
            rowSelection={rowSelection}
            dataSource={content}
            columns={[...mergedColumns, actionCloumn]}
            rowClassName="editable-row"
            pagination={{
              onChange: onChange,
              total: sourceStore.total,
              current: page,
              pageSize: 20,
              showSizeChanger: false,
            }}
          />
        </Form>
      </Space>
    </div>
  );
};

export default inject("sourceStore")(observer(Source));
