import { RootState } from "@/store";
import {
  barrageAuditAPI,
  barrageGetConfigAPI,
  barrageGetUnauditedAPI,
  barrageRemoveAPI,
  getBarrageListAPI,
} from "@/store/action/B4Barrage";
import { BarrageTableType } from "@/types";
import { Input, DatePicker, Select, Button, Table, Popconfirm } from "antd";
import React, {
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useState,
} from "react";
import { useDispatch, useSelector } from "react-redux";
import BarrageSet from "./BarrageSet";
import styles from "./index.module.scss";
const { RangePicker } = DatePicker;

function Barrage() {
  const dispatch = useDispatch();
  const pageNumRef = useRef(1);
  const pagePageRef = useRef(10);

  // 进页面获取弹幕管未审核个数
  useEffect(() => {
    dispatch(barrageGetUnauditedAPI());
  }, [dispatch]);

  const [barrageValue, setBarrageValue] = useState(false);

  // 进页面获取弹幕功能设置信息
  const getBarrageSetFu = useCallback(async () => {
    const res = await barrageGetConfigAPI();
    const dataRes = JSON.parse(res.data.content);
    setBarrageValue(dataRes.value);
  }, []);

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

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

  // 顶部筛选
  const [tableSelect, setTableSelect] = useState({
    searchKey: "",
    barrageStartTime: "",
    barrageEndTime: "",
    authorName: "",
    auditName: "",
    status: -1,
    display: -1,
    auditStartTime: "",
    auditEndTime: "",
    pageSize: 10,
    pageNum: 1,
  });

  // 封装发送请求的函数

  const getList = useCallback(async () => {
    const data = {
      ...tableSelect,
      status: tableSelect.status === -1 ? null : tableSelect.status,
      display: tableSelect.display === -1 ? null : tableSelect.display,
      pageNum: pageNumRef.current,
    };
    dispatch(getBarrageListAPI(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 barrageTimeChange = (date: any, dateString: any) => {
    let barrageStartTime = "";
    let barrageEndTime = "";
    if (dateString[0] && dateString[1]) {
      barrageStartTime = dateString[0] + " 00:00:00";
      barrageEndTime = dateString[1] + " 23:59:59";
    }
    setTableSelect({
      ...tableSelect,
      barrageStartTime,
      barrageEndTime,
      pageNum: 1,
    });
  };

  // 作者称呼的输入
  const nameTime2 = useRef(-1);
  const nameChange2 = useCallback(
    (e: React.ChangeEvent<HTMLInputElement>) => {
      clearTimeout(nameTime2.current);
      nameTime2.current = window.setTimeout(() => {
        setTableSelect({
          ...tableSelect,
          authorName: e.target.value,
          pageNum: 1,
        });
      }, 500);
    },
    [tableSelect]
  );

  // 审核人的输入
  const nameTime3 = useRef(-1);
  const nameChange3 = useCallback(
    (e: React.ChangeEvent<HTMLInputElement>) => {
      clearTimeout(nameTime3.current);
      nameTime3.current = window.setTimeout(() => {
        setTableSelect({
          ...tableSelect,
          auditName: e.target.value,
          pageNum: 1,
        });
      }, 500);
    },
    [tableSelect]
  );

  // 审核日期的改变
  const timeChange = (date: any, dateString: any) => {
    let auditStartTime = "";
    let auditEndTime = "";
    if (dateString[0] && dateString[1]) {
      auditStartTime = dateString[0] + " 00:00:00";
      auditEndTime = dateString[1] + " 23:59:59";
    }
    setTableSelect({
      ...tableSelect,
      auditStartTime,
      auditEndTime,
      pageNum: 1,
    });
  };

  // 点击重置
  const [inputKey, setInputKey] = useState(1);
  const resetSelectFu = useCallback(() => {
    // 把2个输入框和时间选择器清空
    setInputKey(Date.now());
    setTableSelect({
      searchKey: "",
      barrageStartTime: "",
      barrageEndTime: "",
      authorName: "",
      auditName: "",
      status: -1,
      display: -1,
      auditStartTime: "",
      auditEndTime: "",
      pageSize: 10,
      pageNum: 1,
    });
  }, []);

  // -----------表格数据

  // 采纳状态的下拉框返回值
  const tableSelectRes = useCallback((status: number) => {
    const arr = [
      { value: 1, label: "采纳" },
      { value: 0, label: "不采纳" },
    ];
    if (status !== 2) arr.unshift({ value: -1, label: "请选择" });
    return arr;
  }, []);

  // 采纳状态的下拉选择
  const tableSelectFu = useCallback(
    async (id: number, val: number) => {
      const res = await barrageAuditAPI(id, val);
      if (res.code === 0) {
        getList();
        dispatch(barrageGetUnauditedAPI());
      }
    },
    [dispatch, getList]
  );

  // 点击删除
  const delTableFu = useCallback(
    async (id: number) => {
      const res = await barrageRemoveAPI(id);
      if (res.code === 0) {
        getList();
        dispatch(barrageGetUnauditedAPI());
      }
    },
    [dispatch, getList]
  );

  const columns = useMemo(() => {
    return [
      {
        title: "弹幕内容",
        render: (item: BarrageTableType) =>
          item.name.length >= 30 ? (
            <span style={{ cursor: "pointer" }} title={item.name}>
              {item.name.substring(0, 30) + "..."}
            </span>
          ) : (
            item.name
          ),
      },
      {
        title: "关联文物",
        dataIndex: "goodsName",
      },
      {
        title: "弹幕时间",
        dataIndex: "createTime",
      },
      {
        title: "作者称呼",
        dataIndex: "authorName",
      },
      {
        title: "审核状态",
        render: (item: BarrageTableType) =>
          item.status === 2 ? "已审核" : "待审核",
      },
      {
        title: "采纳状态",
        render: (item: BarrageTableType) => (
          <Select
            placeholder="请选择"
            style={{ width: 90 }}
            value={item.display}
            onChange={(e) => tableSelectFu(item.id, e)}
            options={tableSelectRes(item.status)}
          />
        ),
      },
      {
        title: "最近审核时间",
        render: (item: BarrageTableType) =>
          item.status === 2 ? item.updateTime : "（空）",
      },
      {
        title: "审核人",
        render: (item: BarrageTableType) =>
          item.status === 2 ? item.auditName : "（空）",
      },
      {
        title: "操作",
        render: (item: BarrageTableType) => (
          <Popconfirm
            title="删除后无法恢复，是否删除?"
            okText="删除"
            cancelText="取消"
            onConfirm={() => delTableFu(item.id)}
          >
            <Button size="small" type="text" danger>
              删除
            </Button>
          </Popconfirm>
        ),
      },
    ];
  }, [delTableFu, tableSelectFu, tableSelectRes]);

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

  // 弹幕功能设置的弹窗
  const [barrageSet, setBarrageSet] = useState(0);

  return (
    <div className={styles.Barrage}>
      <div className="pageTitlt">弹幕管理</div>
      {/* 上面的搜索盒子 */}
      <div className="searchBox">
        <div className="searchBoxSon1">
          <div className="searchRow">
            <span>弹幕/文物搜索：</span>
            <Input
              key={inputKey}
              maxLength={25}
              style={{ width: 246 }}
              placeholder="请输入关键字"
              allowClear
              onChange={(e) => nameChange(e)}
            />
          </div>

          <div className="searchRow">
            <span>弹幕日期：</span>
            <RangePicker
              style={{ width: 240 }}
              key={inputKey}
              onChange={barrageTimeChange}
            />
          </div>

          <div className="searchRow">
            <span>作者称呼：</span>
            <Input
              key={inputKey}
              maxLength={10}
              style={{ width: 150 }}
              placeholder="请输入关键字"
              allowClear
              onChange={(e) => nameChange2(e)}
            />
          </div>

          <div className="searchRow">
            <span>审核人：</span>
            <Input
              key={inputKey}
              maxLength={10}
              style={{ width: 150 }}
              placeholder="请输入关键字"
              allowClear
              onChange={(e) => nameChange3(e)}
            />
          </div>
        </div>

        <div className="searchBoxSon1">
          <div className="searchRow">
            <span>审核状态：</span>
            <Select
              placeholder="请选择"
              style={{ width: 90 }}
              value={tableSelect.status}
              onChange={(e) =>
                setTableSelect({ ...tableSelect, status: e, pageNum: 1 })
              }
              options={[
                { value: -1, label: "全部" },
                { value: 1, label: "待审核" },
                { value: 2, label: "已审核" },
              ]}
            />
          </div>
          <div className="searchRow">
            <span>采纳状态：</span>
            <Select
              placeholder="请选择"
              style={{ width: 90 }}
              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>
            <RangePicker
              style={{ width: 240 }}
              key={inputKey}
              onChange={timeChange}
            />
          </div>

          {/* 按钮 */}
          <div className="searchBtn">
            <Button onClick={resetSelectFu}>重置</Button>&emsp;
            <Button onClick={() => setBarrageSet(1)}>
              弹幕功能设置（当前：{barrageValue ? "开启" : "关闭"}）
            </Button>
          </div>
        </div>
      </div>
      {/* 表格主体 */}
      <div className="tableBox">
        <Table
          scroll={{ y: 580 }}
          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>

      {barrageSet ? (
        <BarrageSet
          closeMoalFu={() => setBarrageSet(0)}
          barrageValue={barrageValue}
          upBarrageFu={() => getBarrageSetFu()}
        />
      ) : null}
    </div>
  );
}

const MemoBarrage = React.memo(Barrage);

export default MemoBarrage;
