import React, {
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useState,
} from "react";
import styles from "./index.module.scss";
import { useDispatch, useSelector } from "react-redux";
import {
  A5_APIgetInfo,
  A5_APIgetList,
  A5_APIgetListDerive,
} from "@/store/action/A5cash";
import { RootState } from "@/store";
import { Button, DatePicker, Input, Select, Switch } from "antd";
import MyTable from "@/components/MyTable";
import { A5tableC } from "@/utils/tableData";
import { A5tableType } from "@/types";
import ExportJsonExcel from "js-export-excel";
import dayjs from "dayjs";
const { RangePicker } = DatePicker;

function A5cash() {
  const dispatch = useDispatch();

  const [fromData, setFromData] = useState({
    pageNum: 1,
    pageSize: 10,
    searchKey: "",
    startTime: "",
    endTime: "",
    isSend: "",
  });

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

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

  const [inputKey, setInputKey] = useState(1);

  // 标题的输入
  const timeRef = useRef(-1);
  const fromKeyChangeFu = useCallback(
    (e: React.ChangeEvent<HTMLInputElement>, key: "searchKey") => {
      clearTimeout(timeRef.current);
      timeRef.current = window.setTimeout(() => {
        setFromData({ ...fromData, [key]: e.target.value, pageNum: 1 });
      }, 500);
    },
    [fromData]
  );

  // 时间选择器改变
  const timeChange = useCallback(
    (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";
      }
      setFromData({ ...fromData, startTime, endTime, pageNum: 1 });
    },
    [fromData]
  );

  // 点击重置
  const resetSelectFu = useCallback(() => {
    setInputKey(Date.now());
    setFromData({
      pageNum: 1,
      pageSize: 10,
      searchKey: "",
      startTime: "",
      endTime: "",
      isSend: "",
    });
  }, []);

  const tableInfo = useSelector((state: RootState) => state.A5cash.tableInfo);

  // 点击导出
  const deriveFu = useCallback(async () => {
    const name = "兑奖记录" + dayjs(new Date()).format("YYYY-MM-DD HH:mm");

    const res = await A5_APIgetListDerive({
      ...fromData,
      pageNum: 1,
      pageSize: 99999,
    });

    if (res.code === 0) {
      const option = {
        fileName: name,
        datas: [
          {
            sheetData: res.data.records.map((v: A5tableType) => ({
              ...v,
              isSend: v.isSend ? "是" : "否",
            })),
            sheetName: name,
            sheetFilter: [
              "createTime",
              "creatorName",
              "prizeName",
              "score",
              "name",
              "phone",
              "description",
              "isSend",
            ],
            sheetHeader: [
              "时间",
              "用户名",
              "兑换奖品",
              "爱心币记录",
              "称呼",
              "联系方式",
              "地址和留言",
              "是否寄送",
            ],
            columnWidths: [10, 10, 10, 6, 10, 6, 20, 10],
          },
        ],
      };

      const toExcel = new ExportJsonExcel(option); //new
      toExcel.saveExcel(); //保存
    }
  }, [fromData]);

  // 是否寄送
  const switchChangeFu = useCallback(
    async (val: boolean, id: number) => {
      const res = await A5_APIgetInfo(id, val ? 1 : 0);
      if (res.code === 0) getListFu();
    },
    [getListFu]
  );

  const tableLastBtn = useMemo(() => {
    return [
      {
        title: "是否寄送",
        render: (item: A5tableType) => (
          <Switch
            checkedChildren="是"
            unCheckedChildren="否"
            checked={item.isSend === 1}
            onChange={(e) => switchChangeFu(e, item.id)}
          />
        ),
      },
    ];
  }, [switchChangeFu]);

  return (
    <div className={styles.A5cash}>
      <div className="pageTitle">兑换记录</div>

      {/* 顶部筛选 */}
      <div className="A5top">
        <div>
          <div className="A5row">
            <span>日期：</span>
            <RangePicker onChange={timeChange} key={inputKey} />
          </div>
          <div className="A5row">
            <span>用户名：</span>
            <Input
              key={inputKey}
              maxLength={10}
              showCount
              style={{ width: 240 }}
              placeholder="请输入"
              allowClear
              onChange={(e) => fromKeyChangeFu(e, "searchKey")}
            />
          </div>
          <div className="A5row">
            <span>类型：</span>
            <Select
              style={{ width: 120 }}
              value={fromData.isSend}
              onChange={(e) =>
                setFromData({ ...fromData, isSend: e, pageNum: 1 })
              }
              options={[
                { value: "", label: "全部" },
                { value: 1, label: "是" },
                { value: 0, label: "否" },
              ]}
            />
          </div>
        </div>
        <div>
          <Button onClick={resetSelectFu}>重置</Button>&emsp;
          <Button
            type="primary"
            disabled={tableInfo.list.length <= 0}
            onClick={deriveFu}
          >
            导出
          </Button>
        </div>
      </div>

      {/* 表格主体 */}
      <div className="A5tableBox">
        <MyTable
          yHeight={625}
          list={tableInfo.list}
          columnsTemp={A5tableC}
          lastBtn={tableLastBtn}
          pageNum={fromData.pageNum}
          pageSize={fromData.pageSize}
          total={tableInfo.total}
          onChange={(pageNum, pageSize) =>
            setFromData({ ...fromData, pageNum, pageSize })
          }
        />
      </div>
    </div>
  );
}

const MemoA5cash = React.memo(A5cash);

export default MemoA5cash;
