import React, { useCallback, useEffect, useMemo, useState } from "react";
import styles from "./index.module.scss";
import { useDispatch, useSelector } from "react-redux";
import {
  B2_APIdel,
  B2_APIgetList,
  B2_APIsetStatus,
} from "@/store/action/B2orderh";
import { MessageFu } from "@/utils/message";
import { RootState } from "@/store";
import { B2tableType } from "@/types";
import MyPopconfirm from "@/components/MyPopconfirm";
import MyTable from "@/components/MyTable";
import { B2tableC, B3tableC } from "@/utils/tableData";
import { Switch } from "antd";

type Props = {
  type: "activity" | "volunteer";
};

function B2orB3Com({ type }: Props) {
  const dispatch = useDispatch();

  const [fromData, setFromData] = useState({
    pageNum: 1,
    pageSize: 10,
  });

  const getListFu = useCallback(() => {
    dispatch(B2_APIgetList(fromData, type));
  }, [dispatch, fromData, type]);

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

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

  const { tableInfo1, tableInfo2 } = useSelector(
    (state: RootState) => state.B2orderh
  );

  const tableRes = useMemo(() => {
    return type === "activity" ? tableInfo1 : tableInfo2;
  }, [tableInfo1, tableInfo2, type]);

  // 处理状态
  const switchChangeFu = useCallback(
    async (val: boolean, id: number) => {
      const res = await B2_APIsetStatus(id, val ? 1 : 0);
      if (res.code === 0) getListFu();
    },
    [getListFu]
  );

  const tableLastBtn = useMemo(() => {
    return [
      {
        title: "处理状态",
        render: (item: B2tableType) => (
          <Switch
            checkedChildren="已处理"
            unCheckedChildren="未处理"
            checked={item.status === 1}
            onChange={(e) => switchChangeFu(e, item.id)}
          />
        ),
      },
      {
        title: "操作",
        render: (item: B2tableType) => (
          <MyPopconfirm txtK="删除" onConfirm={() => delTableFu(item.id)} />
        ),
      },
    ];
  }, [delTableFu, switchChangeFu]);

  return (
    <div className={styles.B2orB3Com}>
      <div className="pageTitle">
        {type === "activity" ? "活动预约" : "志愿者预约"}
      </div>
      <MyTable
        yHeight={702}
        list={tableRes.list}
        columnsTemp={type === "activity" ? B2tableC : B3tableC}
        lastBtn={tableLastBtn}
        pageNum={fromData.pageNum}
        pageSize={fromData.pageSize}
        total={tableRes.total}
        onChange={(pageNum, pageSize) =>
          setFromData({ ...fromData, pageNum, pageSize })
        }
      />
    </div>
  );
}

const MemoB2orB3Com = React.memo(B2orB3Com);

export default MemoB2orB3Com;
