import React, { useCallback, useRef, useState } from "react";
import styles from "./index.module.scss";
import dayjs from "dayjs";
import { Button } from "antd";
import { API_upFile } from "@/store/action/layout";
import { MessageFu } from "@/utils/message";
import { fileDomInitialFu } from "@/utils/domShow";
import MyTable from "@/components/MyTable";
import { A1tableC } from "@/utils/tableData";
import ExportJsonExcel from "js-export-excel";

type listType = {
  startTime: string;
  endTime: string;
  day: number;
};

function A1xlsx() {
  const [list, setList] = useState<listType[]>([]);

  const myInput = useRef<HTMLInputElement>(null);

  const dataChangeFu = useCallback((list: listType[]) => {
    const arr = [] as listType[];

    list.forEach((v) => {
      const temp1 = dayjs(v.startTime).format("YYYY-MM-DD");
      const temp2 = dayjs(v.endTime).format("YYYY-MM-DD");

      let num = dayjs(temp2).diff(temp1, "day");

      const Sshi = dayjs(v.startTime).get("hour");
      const Sfen = dayjs(v.startTime).get("minute");

      // console.log("ppp", Sshi);

      if (Sshi < 12 || (Sshi === 12 && Sfen <= 30)) num += 0.5;

      const Eshi = dayjs(v.endTime).get("hour");
      // const Efen = dayjs(v.endTime).get("minute");

      if (Eshi >= 14) num += 0.5;
      arr.push({
        startTime: v.startTime,
        endTime: v.endTime,
        day: num,
      });
    });
    setList(arr);
  }, []);

  // 上传表格
  const handeUpPhoto = useCallback(
    async (e: React.ChangeEvent<HTMLInputElement>) => {
      if (e.target.files) {
        // 拿到files信息
        const filesInfo = e.target.files[0];
        // console.log("-----", filesInfo.type);
        console.log(filesInfo);

        // 校验格式
        // const type = format;
        if (!filesInfo.name.includes(".xlsx"))
          return MessageFu.warning("只支持.xlsx文件!");

        // 创建FormData对象
        const fd = new FormData();
        fd.append("type", "doc");
        fd.append("dirCode", "A1Day");
        fd.append("file", filesInfo);

        e.target.value = "";

        try {
          const res = await API_upFile(fd, "cms/trip/upload");
          if (res.code === 0) {
            MessageFu.success("上传成功!");
            // setFileUrl(res.data);
            dataChangeFu(res.data || []);
          }
          fileDomInitialFu();
        } catch (error) {
          fileDomInitialFu();
        }
      }
    },
    [dataChangeFu]
  );

  // 点击导出
  const deriveFu = useCallback(async () => {
    // if (list.length <= 0) return;

    const name = "计算差旅天数" + dayjs(new Date()).format("YYYY-MM-DD HH:mm");

    const option = {
      fileName: name,
      datas: [
        {
          sheetData: list,
          sheetName: name,
          sheetFilter: ["startTime", "endTime", "day"],
          sheetHeader: ["开始时间", "结束时间", "计算后天数"],
          columnWidths: [10, 10, 10],
        },
      ],
    };

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

  return (
    <div className={styles.A1xlsx}>
      <input
        id="upInput"
        type="file"
        accept=".xlsx"
        ref={myInput}
        onChange={(e) => handeUpPhoto(e)}
      />
      <div className="pageTitle">计算差旅天数</div>

      <div className="A1top">
        {list.length ? (
          <>
            <Button className="A1btn" onClick={() => setList([])}>
              清空
            </Button>
            &emsp;&emsp;
            <Button type="primary" onClick={deriveFu}>
              导出表格
            </Button>
          </>
        ) : (
          <Button
            type="primary"
            className="A1btn"
            onClick={() => myInput.current?.click()}
          >
            上传表格
          </Button>
        )}
      </div>

      <div className="tableBox">
        <MyTable
          yHeight={707}
          list={list}
          columnsTemp={A1tableC}
          pagingInfo={false}
        />
      </div>
    </div>
  );
}

const MemoA1xlsx = React.memo(A1xlsx);

export default MemoA1xlsx;
