import React, {
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useState,
} from "react";
import styles from "./index.module.scss";
import { useDispatch, useSelector } from "react-redux";
import { Button, DatePicker, Input, Popconfirm, Select, Table } from "antd";
import {
  A1_APIdelById,
  A1_APIgetList,
  A1_APIlistExport,
} from "@/store/action/A1Order";
import { RootState } from "@/store";
import { A1TableType } from "@/types";
import { MessageFu } from "@/utils/message";
import ExportJsonExcel from "js-export-excel";
import dayjs from "dayjs";
import A1Look from "./A1Look";

const { RangePicker } = DatePicker;

// 获取展馆下拉信息
const select = [
  { value: "", label: "全部" },
  { value: "南京博物院", label: "南京博物院" },
  { value: "中国大运河博物馆", label: "中国大运河博物馆" },
  { value: "苏州博物馆", label: "苏州博物馆" },
];

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

  const [fromData, setFromData] = useState({
    startTime: "",
    endTime: "",
    exhibitionName: "",
    name: "",
    phone: "",
    bookDayStart: "",
    bookDayEnd: "",
    pageNum: 1,
    pageSize: 10,
  });

  // 封装发送接口的函数
  const getListFu = useCallback(() => {
    dispatch(A1_APIgetList(fromData));
  }, [dispatch, fromData]);

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

  // 申请日期的改变
  const timeChange1 = useCallback(
    (_: 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 timeChange2 = useCallback(
    (_: any, dateString: any) => {
      let bookDayStart = "";
      let bookDayEnd = "";
      if (dateString[0] && dateString[1]) {
        bookDayStart = dateString[0] + " 00:00:00";
        bookDayEnd = dateString[1] + " 23:59:59";
      }
      setFromData({ ...fromData, bookDayStart, bookDayEnd, pageNum: 1 });
    },
    [fromData]
  );

  // 名称的输入
  const nameTime = useRef(-1);
  const nameChange = useCallback(
    (e: React.ChangeEvent<HTMLInputElement>) => {
      clearTimeout(nameTime.current);
      nameTime.current = window.setTimeout(() => {
        setFromData({
          ...fromData,
          name: e.target.value,
          pageNum: 1,
        });
      }, 500);
    },
    [fromData]
  );

  // 联系电话的输入
  const phoneTime = useRef(-1);
  const phoneChange = useCallback(
    (e: React.ChangeEvent<HTMLInputElement>) => {
      clearTimeout(phoneTime.current);
      phoneTime.current = window.setTimeout(() => {
        setFromData({
          ...fromData,
          phone: e.target.value,
          pageNum: 1,
        });
      }, 500);
    },
    [fromData]
  );

  // 点击重置
  const [inputKey, setInputKey] = useState(1);
  const resetSelectFu = useCallback(() => {
    // 把2个输入框和时间选择器清空
    setInputKey(Date.now());
    setFromData({
      startTime: "",
      endTime: "",
      exhibitionName: "",
      name: "",
      phone: "",
      bookDayStart: "",
      bookDayEnd: "",
      pageNum: 1,
      pageSize: 10,
    });
  }, []);

  // 点击删除
  const delTableFu = useCallback(
    async (id: number) => {
      const res = await A1_APIdelById(id);
      if (res.code === 0) {
        MessageFu.success("删除成功!");
        getListFu();
      }
    },
    [getListFu]
  );

  // 从仓库获取表格数据
  const tableInfo = useSelector((state: RootState) => state.A1Order.tableInfo);
  // 页码变化
  const paginationChange = useCallback(
    () => (pageNum: number, pageSize: number) => {
      setFromData({ ...fromData, pageNum, pageSize });
    },
    [fromData]
  );

  const resField = useCallback((val: string) => {
    let res = ["（空）", "（空）"];
    if (val) {
      const str1 = val.split(",")[0] || "";
      if (str1) {
        res = str1.split("-");
      }
    }
    return res;
  }, []);

  const columns = useMemo(() => {
    return [
      {
        title: "申请时间",
        dataIndex: "createTime",
      },
      {
        title: "参观展馆",
        dataIndex: "exhibitionName",
      },
      {
        title: "所在单位",
        dataIndex: "organ",
      },
      {
        title: "姓名",
        render: (item: A1TableType) => resField(item.contact)[0],
      },
      {
        title: "联系电话",
        render: (item: A1TableType) => resField(item.contact)[1],
      },
      {
        title: "人数",
        render: (item: A1TableType) => item.contact.split(",").length,
      },
      {
        title: "预约时间",
        render: (item: A1TableType) => item.bookDay + " " + item.bootTimeScope,
      },
      {
        title: "操作",
        render: (item: A1TableType) => (
          <>
            <Button size="small" type="text" onClick={() => setLookInfo(item)}>
              查看
            </Button>
            <Popconfirm
              title="删除后无法恢复，是否删除?"
              okText="删除"
              cancelText="取消"
              onConfirm={() => delTableFu(item.id)}
            >
              <Button size="small" type="text" danger>
                删除
              </Button>
            </Popconfirm>
          </>
        ),
      },
    ];
  }, [delTableFu, resField]);

  // 点击导出
  const deriveFu = useCallback(async () => {
    if (tableInfo.list.length === 0)
      return MessageFu.warning("当前搜索条件没有数据!");
    const name = "预约" + dayjs(new Date()).format("YYYY-MM-DD HH:mm");

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

    if (res.code === 0) {
      const option = {
        fileName: name,
        datas: [
          {
            sheetData: res.data.records.map((v: A1TableType) => {
              return {
                ...v,
                name: resField(v.contact)[0],
                phone: resField(v.contact)[1],
                rNum: v.contact.split(",").length,
                time: v.bookDay + " " + v.bootTimeScope,
              };
            }),
            sheetName: name,
            sheetFilter: [
              "createTime",
              "exhibitionName",
              "organ",
              "name",
              "phone",
              "rNum",
              "time",
              "description",
            ],
            sheetHeader: [
              "申请时间",
              "参观展馆",
              "所在单位",
              "姓名",
              "联系电话",
              "人数",
              "预约时间",
              "备注",
            ],
            columnWidths: [10, 10, 10, 10, 10, 10, 10, 10],
          },
        ],
      };

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

  // 查看的数据
  const [lookInfo, setLookInfo] = useState({} as A1TableType);

  return (
    <div className={styles.A1Order}>
      <div className="pageTitle">预约管理</div>
      <div className="A1Top">
        <div className="A1TopRow">
          <span>申请日期：</span>
          <RangePicker key={inputKey} onChange={timeChange1} />
        </div>
        <div className="A1TopRow">
          <span>参观展馆：</span>
          <Select
            placeholder="请选择"
            style={{ width: 240 }}
            value={fromData.exhibitionName}
            onChange={(e) =>
              setFromData({ ...fromData, exhibitionName: e, pageNum: 1 })
            }
            options={select}
          />
        </div>
        <div className="A1TopRow">
          <span>姓名：</span>
          <Input
            key={inputKey}
            maxLength={50}
            style={{ width: 200 }}
            placeholder="请输入关键字"
            allowClear
            onChange={(e) => nameChange(e)}
          />
        </div>
        <div className="A1TopRow">
          <span>联系电话：</span>
          <Input
            key={inputKey}
            maxLength={11}
            style={{ width: 200 }}
            placeholder="请输入关键字"
            allowClear
            onChange={(e) => phoneChange(e)}
          />
        </div>
        <div className="A1TopRow">
          <span>预约日期：</span>
          <RangePicker key={inputKey} onChange={timeChange2} />
        </div>
        <Button onClick={resetSelectFu}>重置</Button>
        &emsp;&emsp;&emsp;&emsp;
        <Button type="primary" onClick={deriveFu}>
          导出数据
        </Button>
      </div>

      {/* 表格主体 */}
      <div className="tableBox">
        <Table
          scroll={{ y: 565 }}
          dataSource={tableInfo.list}
          columns={columns}
          rowKey="id"
          pagination={{
            showQuickJumper: true,
            position: ["bottomCenter"],
            showSizeChanger: true,
            current: fromData.pageNum,
            pageSize: fromData.pageSize,
            total: tableInfo.total,
            onChange: paginationChange(),
          }}
        />
      </div>

      {/* 点击查看 */}
      {lookInfo.id ? (
        <A1Look
          data={lookInfo}
          closeModelFu={() => setLookInfo({} as A1TableType)}
        />
      ) : null}
    </div>
  );
}

const MemoA1Order = React.memo(A1Order);

export default MemoA1Order;
