import React, { useCallback, useEffect, useMemo, useState } from "react";
import styles from "./index.module.scss";
import { Button, Table } from "antd";
import QTadd from "./QTadd";
import { A6Q_API_Tdel, A6Q_API_TgetList } from "@/store/action/A6_1ques";

// 表格拖动排序-----------------
// import { ExclamationCircleFilled } from "@ant-design/icons";
// import { DndProvider, useDrag, useDrop } from "react-dnd";
// import { HTML5Backend } from "react-dnd-html5-backend";

import MyPopconfirm from "@/components/MyPopconfirm";
import { MessageFu } from "@/utils/message";

type A6QT_TableType = {
  createTime: string;
  creatorId: number;
  creatorName: string;
  custom: boolean;
  id: number;
  question: string;
  questionnaireId: 1;
  skip: string;
  type: string;
  updateTime: string;
};

type Props = {
  fTitle?: string;
  sId: number;
  closeFu: () => void;
};

function A6Qtopic({ fTitle, sId, closeFu }: Props) {
  // 表格数组
  const [list, setList] = useState<A6QT_TableType[]>([]);

  const getInfoFu = useCallback(async () => {
    const res = await A6Q_API_TgetList(sId);
    if (res.code === 0) {
      setList(res.data);
    }
  }, [sId]);

  useEffect(() => {
    getInfoFu();
  }, [getInfoFu]);

  // 表格拖动排序
  // interface DraggableBodyRowProps
  //   extends React.HTMLAttributes<HTMLTableRowElement> {
  //   index: number;
  //   moveRow: (dragIndex: number, hoverIndex: number) => void;
  // }

  // const type = "DraggableBodyRow";

  // const DraggableBodyRow = useCallback(
  //   ({
  //     index,
  //     moveRow,
  //     className,
  //     style,
  //     ...restProps
  //   }: DraggableBodyRowProps) => {
  //     // eslint-disable-next-line react-hooks/rules-of-hooks
  //     const ref = useRef<HTMLTableRowElement>(null);
  //     // eslint-disable-next-line react-hooks/rules-of-hooks
  //     const [{ isOver, dropClassName }, drop] = useDrop({
  //       accept: type,
  //       collect: (monitor) => {
  //         const { index: dragIndex } = monitor.getItem() || {};
  //         if (dragIndex === index) {
  //           return {};
  //         }
  //         return {
  //           isOver: monitor.isOver(),
  //           dropClassName:
  //             dragIndex < index ? " drop-over-downward" : " drop-over-upward",
  //         };
  //       },
  //       drop: (item: { index: number }) => {
  //         if (moveRow) moveRow(item.index, index);
  //       },
  //     });
  //     // eslint-disable-next-line react-hooks/rules-of-hooks
  //     const [, drag] = useDrag({
  //       type,
  //       item: { index },
  //       collect: (monitor) => ({
  //         isDragging: monitor.isDragging(),
  //       }),
  //     });
  //     drop(drag(ref));

  //     return (
  //       <tr
  //         ref={ref}
  //         className={`${className}${isOver ? dropClassName : ""}`}
  //         style={{ cursor: "move", ...style }}
  //         {...restProps}
  //       />
  //     );
  //   },
  //   []
  // );

  // const components = {
  //   body: {
  //     row: DraggableBodyRow,
  //   },
  // };

  // const moveRow = useCallback(
  //   async (dragIndex: number, hoverIndex: number) => {
  //     if (dragIndex === hoverIndex) return;
  //     // 交互位置-之前的id
  //     const beforeId = list[dragIndex].id;
  //     const afterId = list[hoverIndex].id;
  //     // console.log("交换位置", beforeId, afterId);

  //     const res = await A6Q_API_Tsort(beforeId, afterId);

  //     if (res.code === 0) getInfoFu();
  //   },
  //   [getInfoFu, list]
  // );

  // 点击删除
  const delTableFu = useCallback(
    async (id: number) => {
      const res = await A6Q_API_Tdel(id);
      if (res.code === 0) {
        MessageFu.success("删除成功!");
        getInfoFu();
      }
    },
    [getInfoFu]
  );

  const columns = useMemo(() => {
    return [
      {
        width: 100,
        title: (
          <div className="moveTit">
            序号
            {/* <Tooltip title="按住鼠标可拖动表格调整顺序">
              <div className="inco" hidden={list.length < 2}>
                <ExclamationCircleFilled />
              </div>
            </Tooltip> */}
          </div>
        ),
        render: (_1: any, _2: any, index: number) => index + 1,
      },
      {
        title: "类型",
        dataIndex: "type",
      },
      {
        title: "题目描述",
        render: (item: A6QT_TableType) =>
          item.question.length >= 50 ? (
            <span style={{ cursor: "pointer" }} title={item.question}>
              {item.question.substring(0, 50) + "..."}
            </span>
          ) : (
            item.question
          ),
      },
      {
        title: "支持自定义回答",
        render: (item: A6QT_TableType) => (item.custom ? "是" : "否"),
      },
      {
        title: "跳题",
        dataIndex: "skip",
      },
      {
        title: "操作",
        render: (item: A6QT_TableType, _: any, index: number) => (
          <>
            <Button
              size="small"
              type="text"
              onClick={() => setMoInfo({ id: item.id, num: index + 1 })}
            >
              编辑
            </Button>
            <MyPopconfirm txtK="删除" onConfirm={() => delTableFu(item.id)} />
          </>
        ),
      },
    ];
  }, [delTableFu]);

  // 弹窗的显示和隐藏
  const [moInfo, setMoInfo] = useState({ id: 0, num: 0 });

  return (
    <div className={styles.A6Qtopic}>
      <div className="QTtop">
        <div className="QTtitle">{fTitle}</div>
        <div>
          <Button
            type="primary"
            onClick={() => {
              if (list.length >= 50) return MessageFu.warning("最多支持50题!");
              setMoInfo({ id: -1, num: 0 });
            }}
          >
            新增
          </Button>
          &emsp;
          <Button onClick={closeFu}>返回</Button>
        </div>
      </div>
      <div className="QTtable">
        <Table
          scroll={{ y: 688 }}
          columns={columns}
          dataSource={list}
          rowKey="id"
          pagination={false}
        />

        {/* <DndProvider backend={HTML5Backend}>
          <Table
            scroll={{ y: 688 }}
            columns={columns}
            dataSource={list}
            components={components}
            rowKey="id"
            pagination={false}
            onRow={(_, index) => {
              const attr = {
                index,
                moveRow,
              };
              return attr as React.HTMLAttributes<any>;
            }}
          />
        </DndProvider> */}
      </div>
      {moInfo.id ? (
        <QTadd
          moInfo={moInfo}
          closeFu={() => setMoInfo({ id: 0, num: 0 })}
          tableLen={list.length}
          upTableFu={getInfoFu}
          fatherId={sId}
        />
      ) : null}
    </div>
  );
}

const MemoA6Qtopic = React.memo(A6Qtopic);

export default MemoA6Qtopic;
