import React, {
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useState,
} from "react";
import styles from "./index.module.scss";
import { Button, Modal, DatePicker, Table } from "antd";
import dayjs from "dayjs";
import { B1_APIgetTimeList } from "@/store/action/B1Plan";
import ExportJsonExcel from "js-export-excel";
import { MessageFu } from "@/utils/message";

const { RangePicker } = DatePicker;

type ListType = {
  id: string;
  pcsCalculate: number;
  pcsFirst: number;
  pcsPass: number;
  pcsReject: number;
  pcsScene: number;
  today: string;
};

type DateType = {
  timeAll: null | string[];
  startTime: string;
  endTime: string;
  province: string;
  city: string;
  region: string;
};

type Props = {
  title: string;
  closePageFu: () => void;
};

const nowTime = Date.now();
const timeArrTemp = [
  dayjs(nowTime - 86400000 * 30).format("YYYY-MM-DD"),
  dayjs(nowTime).format("YYYY-MM-DD"),
];

const tempObj: DateType = {
  timeAll: timeArrTemp,
  startTime: timeArrTemp[0] + " 00:00:00",
  endTime: timeArrTemp[1] + " 23:59:59",
  province: "",
  city: "",
  region: "",
};

function PlanModal({ title, closePageFu }: Props) {
  // 筛选
  const [tableSelect, setTableSelect] = useState({ ...tempObj });
  const tableSelectRef = useRef({ ...tempObj });

  useEffect(() => {
    tableSelectRef.current = { ...tableSelect };
  }, [tableSelect]);

  // 初始化 表单数据，带入 城市信息
  const baseFromDataFu = useCallback(() => {
    const obj = { ...tempObj };
    const arr = title.split("/");
    obj.province = arr[0] || "";
    obj.city = arr[1] || "";
    obj.region = arr[2] || "";
    setTableSelect(obj);
  }, [title]);

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

  // 点击搜索的 时间戳
  const [timeKey, setTimeKey] = useState(-1);

  const timeRef = useRef(-1);

  // 表格数据
  const [list, setList] = useState<ListType[]>([]);

  const getListFu = useCallback(() => {
    clearTimeout(timeRef.current);
    timeRef.current = window.setTimeout(async () => {
      const res = await B1_APIgetTimeList(tableSelectRef.current);
      if (res.code === 0) {
        setList(
          res.data.map((v: any) => ({
            ...v,
            id:
              v.pcsCalculate +
              "" +
              v.pcsFirst +
              v.pcsPass +
              v.pcsReject +
              v.pcsScene +
              v.today,
          }))
        );
      }
    }, 50);
  }, []);

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

  // 时间选择器改变
  const timeChange = useCallback(
    (e: any) => {
      let temp: any = null;

      const obj = {
        ...tableSelect,
        timeAll: null,
        startTime: "",
        endTime: "",
      };

      if (e) {
        temp = [
          dayjs(e[0]).format("YYYY-MM-DD"),
          dayjs(e[1]).format("YYYY-MM-DD"),
        ];

        obj.timeAll = temp;
        obj.startTime = temp[0] + " 00:00:00";
        obj.endTime = temp[1] + " 23:59:59";
      }

      setTableSelect(obj);
    },
    [tableSelect]
  );

  // 设置选择日期的范围为90天
  const disabledDate = useCallback((e: any) => {
    const time = nowTime - 86400000 * 90;

    const flag = e.valueOf() < time || e.valueOf() > nowTime + 86400000;

    return flag;
  }, []);

  // 点击重置
  const resListFu = useCallback(() => {
    baseFromDataFu();
    setTimeKey(Date.now());
  }, [baseFromDataFu]);

  // 点击昨日 或者 近7天
  const numChangeTimeFu = useCallback((num: 1 | 7) => {
    const numRes = nowTime - 86400000 * num;
    const arr = [
      dayjs(numRes).format("YYYY-MM-DD"),
      dayjs(num === 1 ? numRes : nowTime).format("YYYY-MM-DD"),
    ];

    const obj = {
      ...tableSelectRef.current,
      timeAll: arr,
      startTime: arr[0] + " 00:00:00",
      endTime: arr[1] + " 23:59:59",
    };
    setTableSelect(obj);
  }, []);

  const columns = useMemo(() => {
    return [
      {
        title: "日期",
        render: (item: ListType) => item.today || "空",
      },
      {
        title: "上传场景",
        render: (item: ListType) => item.pcsScene || 0,
      },
      {
        title: "完成场景计算",
        render: (item: ListType) => item.pcsCalculate || 0,
      },
      {
        title: "初审通过",
        render: (item: ListType) => item.pcsFirst || 0,
      },
      {
        title: "审核通过",
        render: (item: ListType) => item.pcsPass || 0,
      },
      {
        title: "审核驳回",
        render: (item: ListType) => item.pcsReject || 0,
      },
    ];
  }, []);

  // 点击导出
  const deriveFu = useCallback(async () => {
    if (list.length > 30000)
      return MessageFu.warning(
        "只支持导出最多30000条数据。请增加筛选条件，并重新尝试"
      );

    if (list.length === 0) return MessageFu.warning("当前搜索条件没有数据!");
    let name = title + dayjs(new Date()).format("YYYY-MM-DD HH:mm");
    name = name.replaceAll("/", "_");

    const option = {
      fileName: name,
      datas: [
        {
          sheetData: list,
          sheetName: name,
          sheetFilter: [
            "today",
            "pcsScene",
            "pcsCalculate",
            "pcsFirst",
            "pcsPass",
            "pcsReject",
          ],
          sheetHeader: [
            "日期",
            "上传场景",
            "完成场景计算",
            "初审通过",
            "审核通过",
            "审核驳回",
          ],
          columnWidths: [10, 5, 5, 5, 5, 5],
        },
      ],
    };

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

  return (
    <Modal
      wrapClassName={styles.PlanModal}
      open={true}
      title={title}
      footer={
        [] // 设置footer为空，去掉 取消 确定默认按钮
      }
    >
      <div className="B1Mmain">
        {/* 顶部筛选 */}
        <div className="B1MmainTop">
          <div>
            <span>日期：</span>
            <RangePicker
              allowClear={false}
              disabledDate={disabledDate}
              value={
                tableSelect.timeAll
                  ? [
                      dayjs(tableSelect.timeAll[0]),
                      dayjs(tableSelect.timeAll[1]),
                    ]
                  : null
              }
              onChange={(e) => timeChange(e)}
            />
            &emsp;<Button onClick={() => numChangeTimeFu(1)}>昨日</Button>
            &emsp;<Button onClick={() => numChangeTimeFu(7)}>近七天</Button>
          </div>
          <div>
            <Button onClick={resListFu}>重置</Button>&emsp;
            <Button type="primary" onClick={() => setTimeKey(Date.now())}>
              查询
            </Button>
            &emsp;
            <Button
              disabled={list.length === 0}
              type="primary"
              onClick={deriveFu}
            >
              导出表格
            </Button>
          </div>
        </div>
        {/* 表格 */}
        <div className="B1MmainTable">
          <Table
            size="small"
            scroll={{ y: 578 }}
            dataSource={list}
            columns={columns}
            rowKey="id"
            pagination={false}
          />
        </div>

        <div className="B1Mbtn">
          <Button onClick={closePageFu}>关闭</Button>
          {/*  右下角的列表数量 */}
          <div className="tableNumBox">
            共 <span>{list.length}</span> 条数据
          </div>
        </div>
      </div>
    </Modal>
  );
}

const MemoPlanModal = React.memo(PlanModal);

export default MemoPlanModal;
