import BreadTit from "@/components/BreadTit";
import { RootState } from "@/store";
import { Button, Input, Pagination, Select, Table } from "antd";
import { useEffect, useMemo, useRef, useState } from "react";
import { useSelector } from "react-redux";
import styles from "./index.module.scss";
import { UnorderedListOutlined, AppstoreOutlined } from "@ant-design/icons";
import classNames from "classnames";
import ImageLazy from "@/components/ImageLazy";
import history from "@/utils/history";
import { useLocation } from "react-router-dom";
import dayjs from "dayjs";
import ExportJsonExcel from "js-export-excel";
const { Option } = Select;
export default function Object2() {
  // 从仓库中获取藏品编号名称下拉数据
  const options = useSelector(
    (state: RootState) => state.loginStore.selectAll["藏品编号名称"]
  );

  // 封装发送请求的函数
  const getList = () => {
    const data = { ...tableSelect, pageNum: pageNumRef.current, aaaaa: value };
    console.log("------", data);
  };

  // 获取地址栏参数
  const location = useLocation();

  // 如果有参数 根据参数页码在次发送请求
  useEffect(() => {
    const urlParam = location.state || {};
    if (urlParam.k && urlParam.k !== "1")
      setTableSelect({ ...tableSelect, pageNum: Number(urlParam.k) });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [location]);

  // 筛选表格的数据
  const [tableSelect, setTableSelect] = useState<any>({
    bianhao: null,
    name: "",
    pageSize: 10,
    pageNum: 1,
  });
  // 当前页码统一
  const pageNumRef = useRef(1);
  useEffect(() => {
    pageNumRef.current = tableSelect.pageNum;
  }, [tableSelect.pageNum]);

  // 防止返回的时候发送了2次请求来对应页码
  const getListRef = useRef(-1);

  useEffect(() => {
    clearTimeout(getListRef.current);
    getListRef.current = window.setTimeout(() => {
      getList();
    }, 100);

    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [tableSelect]);

  // 藏品来源下拉框改变
  const handleChange = (val: string) => {
    setTableSelect({ ...tableSelect, bianhao: val, pageNum: 1 });
  };

  // 搜索输入框下拉
  const [value, setValue] = useState("name1");
  const valueChangeFu = (val: string) => {
    setValue(val);
  };
  const nameTime = useRef(-1);
  const nameChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    clearTimeout(nameTime.current);
    nameTime.current = window.setTimeout(() => {
      setTableSelect({ ...tableSelect, name: e.target.value, pageNum: 1 });
    }, 500);
  };

  // 图片页面和列表页面的切换
  const [cutShow, setCutShow] = useState("cutShow1");

  // 关于表格的数据
  const paginationChange = (pageNum: number, pageSize: number) => {
    setTableSelect({ ...tableSelect, pageNum, pageSize });
  };

  const results = {
    list: [
      { img: "", name: "666-1", id: 1 },
      {
        img: "http://project.4dage.com:8016/content/1_1001/img/20220810_1553241331042.JPG",
        name: "666-2",
        id: 2,
      },
      { img: "", name: "sada阿三大苏打sada阿三大苏打-3", id: 3 },
      { img: "", name: "666-4", id: 4 },
      { img: "", name: "666-5", id: 5 },
      { img: "", name: "666-6", id: 6 },
      { img: "", name: "666-7", id: 7 },
      { img: "", name: "666-8", id: 8 },
      { img: "", name: "666-9", id: 9 },
      { img: "", name: "666-10", id: 10 },
      { img: "", name: "666-11", id: 11 },
      { img: "", name: "666-12", id: 12 },
      { img: "", name: "666-13", id: 13 },
      { img: "", name: "666-14", id: 14 },
      { img: "", name: "666-15", id: 15 },
      { img: "", name: "666-16", id: 16 },
      { img: "", name: "666-17", id: 17 },
      { img: "", name: "666-18", id: 18 },
      { img: "", name: "666-19", id: 19 },
      { img: "", name: "666-20", id: 20 },
      { img: "", name: "666-21", id: 21 },
      { img: "", name: "666-22", id: 22 },
      { img: "", name: "666-23", id: 23 },
    ],
    total: 23,
  };

  const columns = useMemo(() => {
    return [
      {
        title: "缩略图",
        render: (item: any) => (
          <ImageLazy width={120} height={70} src={item.img} />
        ),
      },
      {
        title: "标题",
        dataIndex: "name",
      },
      {
        title: "操作",
        render: (item: any) => (
          <>
            <Button
              type="text"
              danger
              onClick={() =>
                history.push(
                  `/object/2/look?k=${pageNumRef.current}&id=${item.id}`
                )
              }
            >
              查看
            </Button>
          </>
        ),
      },
    ];
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // 点击导出
  const deriveFu = () => {
    const name = dayjs(new Date()).format("YYYYMMDDHHmmss");
    const option = {
      fileName: name,
      datas: [
        {
          sheetData: results.list,
          sheetName: name,
          sheetFilter: ["img", "name", "id"],
          sheetHeader: ["图片", "名字", "id"],
          // columnWidths: [10, 10, 10],
        },
      ],
    };
    const toExcel = new ExportJsonExcel(option); //new
    toExcel.saveExcel(); //保存
  };

  return (
    <div className={styles.Object2}>
      <div className="breadTit">
        <BreadTit>
          <div className="breadTitRow active">藏品总账</div>
        </BreadTit>
      </div>
      <div className="objectSonMain">
        {/* 顶部搜索和筛选 */}
        <div className="searchBox">
          <div className="row">
            <span>藏品编号名称：</span>
            <Select
              placeholder="请选择"
              allowClear
              style={{ width: 150 }}
              value={tableSelect.bianhao}
              onChange={handleChange}
              options={options.map((v: any) => ({
                label: v.name,
                value: v.name,
              }))}
            />
          </div>
          <div className="row">
            <span>搜索：</span>
            <Select
              style={{ width: 100 }}
              value={value}
              onChange={(val) => valueChangeFu(val)}
            >
              <Option value="name1">藏品名称</Option>
              <Option value="name2">藏品年代</Option>
              <Option value="name3">藏品质地</Option>
            </Select>
            <Input
              maxLength={10}
              style={{ width: 150 }}
              placeholder="请输入"
              allowClear
              onChange={(e) => nameChange(e)}
            />
          </div>
          <div className="row">
            <Button onClick={deriveFu}>导出</Button>
          </div>
          <div className="row">
            <div
              onClick={() => setCutShow("cutShow1")}
              className={classNames(
                "cutShow",
                cutShow === "cutShow1" ? "active" : ""
              )}
            >
              <AppstoreOutlined />
            </div>
            <div
              onClick={() => setCutShow("cutShow2")}
              className={classNames(
                "cutShow",
                "cutShow2",
                cutShow === "cutShow2" ? "active" : ""
              )}
            >
              <UnorderedListOutlined />
            </div>
          </div>
        </div>
        {/* 图片展示列表 */}
        <div className="imgList" hidden={cutShow !== "cutShow1"}>
          {results.list.map((v) => (
            <div
              title="666666"
              onClick={() =>
                history.push(
                  `/object/2/look?k=${pageNumRef.current}&id=${v.id}`
                )
              }
              key={v.id}
              className="imgListRow"
            >
              <ImageLazy noLook={true} width={193} height={190} src={v.img} />
              <p>{v.name}</p>
            </div>
          ))}
        </div>

        {/* 表格展示列表 */}
        <div className="tableBox" hidden={cutShow !== "cutShow2"}>
          <Table
            scroll={{ y: 450 }}
            dataSource={results.list}
            columns={columns}
            rowKey="id"
            pagination={false}
          />
        </div>

        {/* 从表格里面拆出来的分页 */}
        <div className="pageBox">
          <Pagination
            showQuickJumper
            showSizeChanger
            current={tableSelect.pageNum}
            pageSize={tableSelect.pageSize}
            onChange={paginationChange}
            total={results.total}
          />
        </div>
      </div>
    </div>
  );
}
