import { RootState } from "@/store";
import {
  getGoodsListDeriveAPI,
  getGoodsListAPI,
  goodsDisplayAPI,
  goodsRemoveAPI,
  goodsBarrageAPI,
} from "@/store/action/B2Goods";
import { MessageFu } from "@/utils/message";
import {
  Input,
  Select,
  DatePicker,
  Button,
  Table,
  Switch,
  Popconfirm,
} from "antd";
import dayjs from "dayjs";
import React, {
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useState,
} from "react";
import { useDispatch, useSelector } from "react-redux";
import styles from "./index.module.scss";
import ExportJsonExcel from "js-export-excel";
import ImageLazy from "@/components/ImageLazy";
import GoodsBarrage from "./GoodsBarrage";
import GoodsAdd from "./GoodsAdd";
import GoogsDown from "./GoogsDown";
import { GoodsTableType } from "@/types";

const { RangePicker } = DatePicker;
function Goods() {
  const dispatch = useDispatch();
  const pageNumRef = useRef(1);
  const pagePageRef = useRef(10);

  // 从仓库获取下拉列表数据
  const dictList = useSelector((state: RootState) => state.loginStore.dictList);

  // 从仓库获取表格列表信息
  const tableInfo = useSelector(
    (state: RootState) => state.goodsReducer.tableInfo
  );

  // 顶部筛选
  const [tableSelect, setTableSelect] = useState({
    searchKey: "",
    num: "",
    dictTexture: "",
    dictAge: "",
    dictLevel: "",
    dictSource: "",
    startTime: "",
    endTime: "",
    topic: "",
    display: -1,
    pageSize: 10,
    pageNum: 1,
    isBarrage: -1,
  });

  // 封装发送请求的函数

  const getList = useCallback(async () => {
    const data = {
      ...tableSelect,
      display: tableSelect.display === -1 ? null : tableSelect.display,
      isBarrage: tableSelect.isBarrage === -1 ? null : tableSelect.isBarrage,
      pageNum: pageNumRef.current,
    };
    dispatch(getGoodsListAPI(data));
  }, [dispatch, tableSelect]);

  // 当前页码统一
  useEffect(() => {
    pageNumRef.current = tableSelect.pageNum;
    pagePageRef.current = tableSelect.pageSize;
  }, [tableSelect.pageNum, tableSelect.pageSize]);

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

  // 名称的输入
  const nameTime = useRef(-1);
  const nameChange = useCallback(
    (e: React.ChangeEvent<HTMLInputElement>) => {
      clearTimeout(nameTime.current);
      nameTime.current = window.setTimeout(() => {
        setTableSelect({
          ...tableSelect,
          searchKey: e.target.value,
          pageNum: 1,
        });
      }, 500);
    },
    [tableSelect]
  );

  // 登记编号的输入
  const numTime = useRef(-1);
  const numChange = useCallback(
    (e: React.ChangeEvent<HTMLInputElement>) => {
      clearTimeout(numTime.current);
      numTime.current = window.setTimeout(() => {
        setTableSelect({
          ...tableSelect,
          num: e.target.value,
          pageNum: 1,
        });
      }, 500);
    },
    [tableSelect]
  );

  // 时间选择器改变
  const timeChange = (date: any, dateString: any) => {
    let startTime = "";
    let endTime = "";
    if (dateString[0] && dateString[1]) {
      startTime = dateString[0] + " 00:00:00";
      endTime = dateString[1] + " 23:59:59";
    }
    setTableSelect({ ...tableSelect, startTime, endTime, pageNum: 1 });
  };

  // 点击重置
  const [inputKey, setInputKey] = useState(1);
  const resetSelectFu = useCallback(() => {
    // 把2个输入框和时间选择器清空
    setInputKey(Date.now());
    setTableSelect({
      searchKey: "",
      num: "",
      dictTexture: "",
      dictAge: "",
      dictLevel: "",
      dictSource: "",
      startTime: "",
      endTime: "",
      topic: "",
      display: -1,
      pageSize: 10,
      pageNum: 1,
      isBarrage: -1,
    });
  }, []);

  // 点击导出
  const deriveFu = useCallback(async () => {
    if (tableInfo.list.length === 0)
      return MessageFu.warning("当前搜索条件没有数据!");

    const data = {
      ...tableSelect,
      display: tableSelect.display === -1 ? null : tableSelect.display,
      isBarrage: tableSelect.isBarrage === -1 ? null : tableSelect.isBarrage,
      pageNum: 1,
      pageSize: 9999,
    };

    const res = await getGoodsListDeriveAPI(data);

    if (res.code === 0) {
      const name = dayjs(new Date()).format("YYYYMMDD");

      const resData: GoodsTableType[] = res.data.records;

      const option = {
        fileName: name,
        datas: [
          {
            sheetData: resData.map((v, i) => {
              return {
                ...v,
                index: i + 1,
                display: v.display ? "展示" : "不展示",
                isBarrage: v.isBarrage ? "开启" : "关闭",
              };
            }),
            sheetName: name,
            sheetFilter: [
              "index",
              "name",
              "num",
              "dictTexture",
              "dictAge",
              "dictLevel",
              "dictSource",
              "description",
              "updateTime",
              "topic",
              "display",
              "isBarrage",
            ],
            sheetHeader: [
              "序号",
              "名称",
              "登记编号",
              "类别",
              "年代",
              "级别",
              "来源",
              "简介",
              "最近编辑时间",
              "万物墙主题",
              "展示状态",
              "弹幕留言",
            ],
            // columnWidths: [5, 20, 5],
          },
        ],
      };

      const toExcel = new ExportJsonExcel(option); //new
      toExcel.saveExcel(); //保存
    }
  }, [tableInfo.list.length, tableSelect]);

  // ----------关于表格的数据

  // 页码变化
  const paginationChange = useCallback(
    () => (pageNum: number, pageSize: number) => {
      pageNumRef.current = pageNum;
      pagePageRef.current = pageSize;
      setTableSelect({ ...tableSelect, pageNum, pageSize });
    },
    [tableSelect]
  );

  // 切换表格中的启用停用状态
  const isEnabledClickFu = useCallback(
    async (val: boolean, id: number) => {
      const isDisable = val ? 1 : 0;
      const res = await goodsDisplayAPI(id, isDisable);
      if (res.code === 0) getList();
    },
    [getList]
  );

  // 切换表格中的弹幕留言开启和关闭
  const isBarrageFu = useCallback(
    async (val: boolean, id: number) => {
      const isDisable = val ? 1 : 0;
      const res = await goodsBarrageAPI(id, isDisable);
      if (res.code === 0) getList();
    },
    [getList]
  );

  // 点击下载图片打开的弹窗
  const [downPage, setDownPage] = useState(0);

  // 点击下载图片
  const downTableImgFu = useCallback((type: string, id: number) => {
    if (type.includes("img")) {
      setDownPage(id);
    } else MessageFu.warning("该文物未上传图片!");
  }, []);

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

  const columns = useMemo(() => {
    return [
      {
        title: "名称",
        dataIndex: "name",
      },
      {
        title: "登记编号",
        render: (item: GoodsTableType) => (item.num ? item.num : "（空）"),
      },
      {
        title: "类别",
        dataIndex: "dictTexture",
      },
      {
        title: "年代",
        dataIndex: "dictAge",
      },
      {
        title: "级别",
        dataIndex: "dictLevel",
      },
      {
        title: "来源",
        dataIndex: "dictSource",
      },
      {
        title: "简介",
        render: (item: GoodsTableType) =>
          item.description ? (
            item.description.length >= 20 ? (
              <span style={{ cursor: "pointer" }} title={item.description}>
                {item.description.substring(0, 20) + "..."}
              </span>
            ) : (
              item.description
            )
          ) : (
            "（空）"
          ),
      },
      {
        title: "封面图",
        render: (item: GoodsTableType) => (
          <div className="tableImgAuto">
            <ImageLazy width={60} height={60} src={item.thumb!} />
          </div>
        ),
      },
      {
        title: "最近编辑时间",
        dataIndex: "updateTime",
      },
      {
        title: "万物墙主题",
        dataIndex: "topic",
      },
      {
        title: "展示状态",
        render: (item: GoodsTableType) => (
          <Switch
            checkedChildren="启用"
            unCheckedChildren="停用"
            checked={item.display === 1}
            onChange={(val) => isEnabledClickFu(val, item.id!)}
          />
        ),
      },
      {
        title: "弹幕留言",
        render: (item: GoodsTableType) => (
          <Switch
            checkedChildren="启用"
            unCheckedChildren="停用"
            checked={item.isBarrage === 1}
            onChange={(val) => isBarrageFu(val, item.id!)}
          />
        ),
      },

      {
        title: "操作",
        render: (item: GoodsTableType) => (
          <>
            <Button
              style={{ opacity: item.type.includes("img") ? "1" : "0.5" }}
              size="small"
              type="text"
              onClick={() => downTableImgFu(item.type, item.id!)}
            >
              下载图片
            </Button>
            <Button size="small" type="text" onClick={() => setAddId(item.id!)}>
              编辑
            </Button>
            <Popconfirm
              title="删除后无法恢复，是否删除?"
              okText="删除"
              cancelText="取消"
              onConfirm={() => delTableFu(item.id!)}
            >
              <Button size="small" type="text" danger>
                删除
              </Button>
            </Popconfirm>
          </>
        ),
      },
    ];
  }, [delTableFu, downTableImgFu, isBarrageFu, isEnabledClickFu]);

  // 弹幕设置的弹窗
  const [barrage, setBarrage] = useState(false);

  // 新增或者编辑的弹窗
  const [addId, setAddId] = useState(0);

  return (
    <div className={styles.Goods}>
      <div className="pageTitlt">
        {addId === 0 ? "馆藏管理" : addId > 0 ? "编辑馆藏" : "新增馆藏"}
      </div>
      {/* 搜索信息 */}
      <div className="searchBox" hidden={addId !== 0}>
        <div className="searchRow">
          <span>名称：</span>
          <Input
            key={inputKey}
            maxLength={25}
            style={{ width: 150 }}
            placeholder="请输入关键字"
            allowClear
            onChange={(e) => nameChange(e)}
          />
        </div>

        <div className="searchRow">
          <span>登记编号：</span>
          <Input
            key={inputKey}
            maxLength={25}
            style={{ width: 150 }}
            placeholder="请输入关键字"
            allowClear
            onChange={(e) => numChange(e)}
          />
        </div>

        <div className="searchRow">
          <span>类别：</span>
          <Select
            placeholder="请选择"
            style={{ width: 160 }}
            value={tableSelect.dictTexture}
            onChange={(e) =>
              setTableSelect({ ...tableSelect, dictTexture: e, pageNum: 1 })
            }
            options={dictList["texture"]}
          />
        </div>

        <div className="searchRow">
          <span>年代：</span>
          <Select
            placeholder="请选择"
            style={{ width: 150 }}
            value={tableSelect.dictAge}
            onChange={(e) =>
              setTableSelect({ ...tableSelect, dictAge: e, pageNum: 1 })
            }
            options={dictList["age"]}
          />
        </div>
        <div className="searchRow">
          <span>级别：</span>
          <Select
            placeholder="请选择"
            style={{ width: 135 }}
            value={tableSelect.dictLevel}
            onChange={(e) =>
              setTableSelect({ ...tableSelect, dictLevel: e, pageNum: 1 })
            }
            options={dictList["level"]}
          />
        </div>
        <div className="searchRow">
          <span>来源：</span>
          <Select
            placeholder="请选择"
            style={{ width: 135 }}
            value={tableSelect.dictSource}
            onChange={(e) =>
              setTableSelect({ ...tableSelect, dictSource: e, pageNum: 1 })
            }
            options={dictList["source"]}
          />
        </div>

        <div className="searchRow">
          <span>最近编辑日期：</span>
          <RangePicker
            style={{ width: 240 }}
            key={inputKey}
            onChange={timeChange}
          />
        </div>

        <div className="searchRow">
          <span>万物墙：</span>
          <Select
            placeholder="请选择"
            style={{ width: 100 }}
            value={tableSelect.topic}
            onChange={(e) =>
              setTableSelect({ ...tableSelect, topic: e, pageNum: 1 })
            }
            options={[
              { value: "", label: "全部" },
              { value: "战争", label: "战争" },
              { value: "生活", label: "生活" },
              { value: "不展示", label: "不展示" },
            ]}
          />
        </div>

        <div className="searchRow">
          <span>展示状态：</span>
          <Select
            placeholder="请选择"
            style={{ width: 100 }}
            value={tableSelect.display}
            onChange={(e) =>
              setTableSelect({ ...tableSelect, display: e, pageNum: 1 })
            }
            options={[
              { value: -1, label: "全部" },
              { value: 1, label: "开启" },
              { value: 0, label: "关闭" },
            ]}
          />
        </div>

        <div className="searchRow">
          <span>弹幕留言：</span>
          <Select
            placeholder="请选择"
            style={{ width: 100 }}
            value={tableSelect.isBarrage}
            onChange={(e) =>
              setTableSelect({ ...tableSelect, isBarrage: e, pageNum: 1 })
            }
            options={[
              { value: -1, label: "全部" },
              { value: 1, label: "开启" },
              { value: 0, label: "关闭" },
            ]}
          />
        </div>

        <div className="searchRow">
          <Button onClick={resetSelectFu}>重置</Button>&emsp;
          <Button onClick={deriveFu}>批量导出</Button>&emsp;
          <Button onClick={() => setBarrage(true)}>弹幕设置</Button>&emsp;
          <Button type="primary" onClick={() => setAddId(-1)}>
            新增
          </Button>
        </div>
      </div>
      {/* 表格主体 */}
      <div className="tableBox" hidden={addId !== 0}>
        <Table
          scroll={{ y: 560 }}
          dataSource={tableInfo.list}
          columns={columns}
          rowKey="id"
          pagination={{
            showQuickJumper: true,
            position: ["bottomCenter"],
            showSizeChanger: true,
            current: tableSelect.pageNum,
            pageSize: tableSelect.pageSize,
            total: tableInfo.total,
            onChange: paginationChange(),
          }}
        />
      </div>

      {/* 弹幕设置 */}
      {barrage ? (
        <GoodsBarrage
          closeMoalFu={() => setBarrage(false)}
          editListFu={getList}
        />
      ) : null}

      {/* 下载图片的弹窗 */}
      {downPage ? (
        <GoogsDown id={downPage} closeMoalFu={() => setDownPage(0)} />
      ) : null}

      {/* 新增和编辑的弹窗 */}
      {addId !== 0 ? (
        <GoodsAdd
          id={addId}
          closeMoalFu={() => setAddId(0)}
          addListFu={resetSelectFu}
          editListFu={getList}
        />
      ) : null}
    </div>
  );
}

const MemoGoods = React.memo(Goods);

export default MemoGoods;
