import React, {
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useState,
} from "react";
import styles from "./index.module.scss";
import { useDispatch, useSelector } from "react-redux";
import {
  A6_APIgetInfo,
  A6_APIgetList,
  A6_APIgetListDerive,
} from "@/store/action/A6message";
import ExportJsonExcel from "js-export-excel";
import { RootState } from "@/store";
import dayjs from "dayjs";
import { A6tableType } from "@/types";
import { Button, DatePicker, Input, Switch } from "antd";
import MyTable from "@/components/MyTable";
import { A6tableC } from "@/utils/tableData";
const { RangePicker } = DatePicker;

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

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

  const getListFu = useCallback(() => {
    dispatch(A6_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: "",
    });
  }, []);

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

  // 点击导出
  const deriveFu = useCallback(async () => {
    const name = "留言反馈" + dayjs(new Date()).format("YYYY-MM-DD HH:mm");

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

    if (res.code === 0) {
      const option = {
        fileName: name,
        datas: [
          {
            sheetData: res.data.records.map((v: A6tableType) => ({
              ...v,
              status: v.status === 1 ? "已处理" : "未处理",
            })),
            sheetName: name,
            sheetFilter: ["createTime", "name", "phone", "content", "status"],
            sheetHeader: ["时间", "称呼", "联系方式", "反馈内容", "处理状态"],
            columnWidths: [10, 10, 10, 20, 10],
          },
        ],
      };

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

  // 处理状态
  const switchChangeFu = useCallback(
    async (val: boolean, id: number) => {
      const res = await A6_APIgetInfo(id, val ? 1 : 2);
      if (res.code === 0) getListFu();
    },
    [getListFu]
  );

  const tableLastBtn = useMemo(() => {
    return [
      {
        title: "处理状态",
        render: (item: A6tableType) => (
          <Switch
            checkedChildren="已处理"
            unCheckedChildren="未处理"
            checked={item.status === 1}
            onChange={(e) => switchChangeFu(e, item.id)}
          />
        ),
      },
    ];
  }, [switchChangeFu]);

  return (
    <div className={styles.A6message}>
      <div className="pageTitle">留言反馈</div>
      {/* 顶部筛选 */}
      <div className="A6top">
        <div>
          <div className="A6row">
            <span>日期：</span>
            <RangePicker onChange={timeChange} key={inputKey} />
          </div>
          <div className="A6row">
            <span>称呼：</span>
            <Input
              key={inputKey}
              maxLength={10}
              showCount
              style={{ width: 240 }}
              placeholder="请输入"
              allowClear
              onChange={(e) => fromKeyChangeFu(e, "searchKey")}
            />
          </div>
        </div>
        <div>
          <Button onClick={resetSelectFu}>重置</Button>&emsp;
          <Button
            type="primary"
            disabled={tableInfo.list.length <= 0}
            onClick={deriveFu}
          >
            导出
          </Button>
        </div>
      </div>

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

const MemoA6message = React.memo(A6message);

export default MemoA6message;
