import React, {
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useState,
} from "react";
import styles from "./index.module.scss";
import {
  A2_APIdelItem,
  A2_APIeditItem,
  A2_APIgetInfoById,
  A2_APIgetList,
  A2_APIupdateIndex,
} from "@/store/action/A2Gallery";
import { A2TableType } from "@/types";
import { useDispatch, useSelector } from "react-redux";
import { RootState } from "@/store";
import { Button, Form, FormInstance, Input, Popconfirm, Table } from "antd";
import TextArea from "antd/es/input/TextArea";
import ImageLazy from "@/components/ImageLazy";
import A2Modal from "../A2Modal";
import { MessageFu } from "@/utils/message";
import classNames from "classnames";

type Props = {
  editInfo: { type: string; id: number };
  editFu: () => void;
  closeFu: () => void;
};

function A2Edit({ editInfo, editFu, closeFu }: Props) {
  const dispatch = useDispatch();

  // 下面表格数据
  const inTableInfo = useSelector(
    (state: RootState) => state.A2Gallery.inTableInfo
  );

  // 防止每次进页面  placeholder 回显 跳动问题

  // 自己的id
  const [pid, setPid] = useState(0);

  const getInfoByIdFu = useCallback(
    async (id: number) => {
      const res = await A2_APIgetInfoById(id);
      if (res.code === 0) {
        FormBoxRef.current?.setFieldsValue(res.data);
        setPid(res.data.id);
      }
      dispatch(A2_APIgetList({ parentId: id }, true));
    },
    [dispatch]
  );

  const upTableInfo = useCallback(() => {
    dispatch(A2_APIgetList({ parentId: editInfo.id }, true));
  }, [dispatch, editInfo.id]);

  useEffect(() => {
    getInfoByIdFu(editInfo.id);
  }, [editInfo.id, getInfoByIdFu]);

  // 表单的ref
  const FormBoxRef = useRef<FormInstance>(null);

  // 没有通过校验
  const onFinishFailed = useCallback(() => {}, []);

  // 通过校验点击确定
  const onFinish = useCallback(
    async (value: any) => {
      const res = await A2_APIeditItem({
        ...value,
        id: editInfo.id,
      });
      if (res.code === 0) {
        MessageFu.success("保存成功!");
        editFu();
        closeFu();
      }
    },
    [closeFu, editFu, editInfo.id]
  );

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

  // 点击置顶
  const updateIndexFu = useCallback(
    async (id: number, pid: number) => {
      const res = await A2_APIupdateIndex(id, pid);
      if (res.code === 0) {
        MessageFu.success("置顶成功!");
        upTableInfo();
      }
    },
    [upTableInfo]
  );

  const columns = useMemo(() => {
    const arr = [
      {
        title: "展览名称",
        dataIndex: "name",
      },
      {
        title: "展览类型",
        dataIndex: "type",
      },
      {
        title: "封面图",
        render: (item: A2TableType) => (
          <div className="tableImgAuto">
            <ImageLazy width={60} height={60} src={item.thumb} />
          </div>
        ),
      },
      {
        title: "标签",
        render: (item: A2TableType) => (item.tag ? item.tag : "（空）"),
      },
      {
        title: "展览地点",
        dataIndex: "address",
      },
      {
        title: "跳转链接",
        render: (item: A2TableType) => (
          <a href={item.link} target="blank" title={item.link}>
            {item.link.length >= 50
              ? item.link.substring(0, 50) + "..."
              : item.link}
          </a>
        ),
      },
    ];

    if (editInfo.type === "edit") {
      arr.push({
        title: "操作",
        render: (item: A2TableType) => (
          <>
            <Button
              hidden={item.hasIndex === 1}
              size="small"
              type="text"
              onClick={() => updateIndexFu(item.id, pid)}
            >
              置顶
            </Button>
            <Button
              size="small"
              type="text"
              onClick={() =>
                setIsEdit({ type: "edit", id: item.id, info: item, pid })
              }
            >
              编辑
            </Button>
            <Popconfirm
              title="删除后无法恢复，是否删除?"
              okText="删除"
              cancelText="取消"
              onConfirm={() => delTableFu(item.id)}
            >
              <Button size="small" type="text" danger>
                删除
              </Button>
            </Popconfirm>
          </>
        ),
      });
    }

    return arr;
  }, [delTableFu, editInfo.type, pid, updateIndexFu]);

  // 内部的 新增 、或者 编辑
  const [isEdit, setIsEdit] = useState({
    type: "",
    id: 0,
    info: {} as A2TableType,
    pid: 0,
  });

  return (
    <div className={styles.A2Edit}>
      <div
        className={classNames(
          "A2E_topInfo",
          editInfo.type === "look" ? "nolyLookMain" : ""
        )}
      >
        <Form
          scrollToFirstError={true}
          ref={FormBoxRef}
          name="basic"
          labelCol={{ span: 3 }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item label="展馆名称" name="name">
            <Input
              disabled={editInfo.type === "edit"}
              maxLength={50}
              showCount
            />
          </Form.Item>
          <Form.Item label="地址" name="address">
            <Input
              placeholder={
                pid ? (editInfo.type === "look" ? "（空）" : "请输入内容") : ""
              }
              maxLength={50}
              showCount
            />
          </Form.Item>
          <Form.Item label="开放时间" name="openTime">
            <Input
              placeholder={
                pid ? (editInfo.type === "look" ? "（空）" : "请输入内容") : ""
              }
              maxLength={50}
              showCount
            />
          </Form.Item>
          <Form.Item label="展馆简介" name="description">
            <TextArea
              autoSize
              placeholder={
                pid ? (editInfo.type === "look" ? "（空）" : "请输入内容") : ""
              }
              showCount
              maxLength={500}
            />
          </Form.Item>
          {/* 确定和取消按钮 */}
          <div className="A2E_btn">
            {editInfo.type === "look" ? (
              <Button onClick={closeFu}>关 闭</Button>
            ) : (
              <>
                <Button type="primary" htmlType="submit">
                  保存
                </Button>
                &emsp;&emsp;
                <Popconfirm
                  title="放弃编辑后，信息将不会保存!"
                  okText="放弃"
                  cancelText="取消"
                  onConfirm={closeFu}
                >
                  <Button>取消</Button>
                </Popconfirm>
              </>
            )}
          </div>
        </Form>
      </div>
      {/* 展馆管理 */}
      <div className="A2E_flooBox">
        <div className="A2E_flooTit" hidden={editInfo.type === "look"}>
          <div className="A2E_flooTitl">展馆管理：</div>
          <Button
            type="primary"
            onClick={() =>
              setIsEdit({ type: "add", id: -1, info: {} as A2TableType, pid })
            }
          >
            新增
          </Button>
        </div>
        <div className="A2E_table">
          <Table
            scroll={{ y: 500 }}
            dataSource={inTableInfo}
            columns={columns}
            rowKey="id"
            pagination={false}
          />
        </div>
      </div>

      {/* 点击里面的 新增 和 编辑 */}
      {isEdit.id === 0 ? null : (
        <A2Modal
          isEdit={isEdit}
          inCloseFu={() =>
            setIsEdit({ type: "", id: 0, info: {} as A2TableType, pid })
          }
          inEditFu={() => upTableInfo()}
        />
      )}
    </div>
  );
}

const MemoA2Edit = React.memo(A2Edit);

export default MemoA2Edit;
