import React, { useCallback, useEffect, useMemo, useState } from "react";
import styles from "./index.module.scss";
import { Button, DatePicker, Input, Modal, Popconfirm, Table } from "antd";
import {
  A1_APIaddBySn,
  A1_APIgetInfoBySn,
  A1_APIgetListBySn,
  A1_APIremoveBySn,
} from "@/store/action/A1Camera";
import dayjs from "dayjs";
import { MessageFu } from "@/utils/message";
import classNames from "classnames";

const { RangePicker } = DatePicker;

type TableType = {
  cameraSn: string;
  createTime: string;
  creatorId: number;
  creatorName: string;
  dept: string;
  endTime: string;
  id: number;
  startTime: string;
  updateTime: string;
  user: string;
};

type Props = {
  closeFu: () => void;
  logSn: string;
};

function LogCamera({ logSn, closeFu }: Props) {
  const [tableList, setTableList] = useState([] as TableType[]);

  const getListFu = useCallback(async () => {
    const res = await A1_APIgetListBySn(logSn);
    if (res.code === 0) {
      setTableList(res.data);
    }
  }, [logSn]);

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

  // 点击外面表格的删除
  const delByIdFu = useCallback(
    async (id: number) => {
      const res = await A1_APIremoveBySn(id);
      if (res.code === 0) {
        MessageFu.success("删除成功!");
        getListFu();
      }
    },
    [getListFu]
  );

  const columns = useMemo(() => {
    return [
      {
        title: "领用部门",
        render: (item: TableType) => (item.dept ? item.dept : "（空）"),
      },
      {
        title: "领用人员",
        render: (item: TableType) => (item.user ? item.user : "（空）"),
      },
      {
        title: "领用日期",
        render: (item: TableType) => `${item.startTime} 至 ${item.endTime}`,
      },
      {
        title: "操作",
        render: (item: TableType) => (
          <>
            <Button
              size="small"
              type="text"
              onClick={() => setModelId(item.id)}
            >
              编辑
            </Button>
            <Popconfirm
              title="删除后无法恢复，是否删除?"
              okText="删除"
              cancelText="取消"
              onConfirm={() => delByIdFu(item.id)}
              okButtonProps={{ loading: false }}
            >
              <Button size="small" type="text" danger>
                删除
              </Button>
            </Popconfirm>
          </>
        ),
      },
    ];
  }, [delByIdFu]);

  // 表单弹窗
  const [modelId, setModelId] = useState(0);

  // modelId 改变的时候 把表单里面的数据 初始化

  const getInfoBySnFu = useCallback(async (id: number) => {
    const res = await A1_APIgetInfoBySn(id);
    if (res.code === 0) {
      const { dept, user, startTime, endTime } = res.data;
      // console.log(123, res);
      setDept(dept);
      setUser(user);
      setTime([startTime, endTime]);
    }
  }, []);

  useEffect(() => {
    if (modelId === 0) {
      setDept("");
      setUser("");
      setTime(null);
      setIsOk(false);
    } else if (modelId > 0) getInfoBySnFu(modelId);
  }, [getInfoBySnFu, modelId]);

  // 表单信息
  const [dept, setDept] = useState("");
  const [user, setUser] = useState("");
  const [time, setTime] = useState<null | string[]>(null);

  const [isOk, setIsOk] = useState(false);

  // 点击确定
  const btnOkFu = useCallback(async () => {
    setIsOk(true);
    if (!dept && !user) return;
    const res = await A1_APIaddBySn({
      cameraSn: logSn,
      dept,
      user,
      startTime: time![0],
      endTime: time![1],
      id: modelId > 0 ? modelId : null,
    });

    if (res.code === 0) {
      MessageFu.success(modelId > 0 ? "编辑成功!" : "新增成功!");
      getListFu();
      setModelId(0);
    }
  }, [dept, getListFu, logSn, modelId, time, user]);

  return (
    <div className={styles.LogCamera}>
      <div className="A1Ltop">
        <div>{logSn} - 领用记录</div>&emsp;&emsp;
        <Button
          type="primary"
          onClick={() => setModelId(-1)}
          disabled={tableList.length >= 20}
        >
          登记领用信息
        </Button>
        &emsp;&emsp;
        <span hidden={tableList.length < 20}>最多只能添加20条记录</span>
        <div className="A1LtopBack" onClick={closeFu}>
          <Button>返回</Button>
        </div>
      </div>
      <div className="A1Ltable">
        <Table
          scroll={{ y: 670 }}
          dataSource={tableList}
          columns={columns}
          rowKey="id"
          pagination={false}
        />
      </div>

      {/* 新增和编辑领用信息的弹窗 */}
      <Modal
        wrapClassName={styles.LogCameraModal}
        open={!!modelId}
        title={`${modelId > 0 ? "编辑" : "登记"}领用信息`}
        footer={
          [] // 设置footer为空，去掉 取消 确定默认按钮
        }
      >
        <div className="A1LMmain">
          <div className="A1LMrow">
            <div className="A1LMrow1">领用部门：</div>
            <div className="A1LMrow2">
              <Input
                value={dept}
                onChange={(e) => setDept(e.target.value.replace(/\s+/g, ""))}
                maxLength={20}
                showCount
                placeholder="请输入内容，如采集部门等"
              />
            </div>
          </div>

          <div className="A1LMrow">
            <div className="A1LMrow1">领用人员：</div>
            <div className="A1LMrow2">
              <Input
                value={user}
                onChange={(e) => setUser(e.target.value.replace(/\s+/g, ""))}
                maxLength={20}
                showCount
                placeholder="请输入内容，如人员姓名，联系方式等"
              />
            </div>
          </div>

          <div className="A1LMrow">
            <div className="A1LMrow1">
              <span>* </span> 领用日期：
            </div>
            <div className="A1LMrow2">
              <RangePicker
                value={
                  time
                    ? [
                        dayjs(time[0], "YYYY-MM-DD"),
                        dayjs(time[1], "YYYY-MM-DD"),
                      ]
                    : null
                }
                onChange={(e) => {
                  if (e && e.length && e.length > 1) {
                    const str1 = dayjs(e[0]).format("YYYY-MM-DD");
                    const str2 = dayjs(e[1]).format("YYYY-MM-DD");
                    setTime([str1, str2]);
                  } else setTime(null);
                }}
              />
            </div>
          </div>

          <div className="A1LMrow A1LMrowLast">
            <div className="A1LMrow1"></div>
            <div className="A1LMrow2">
              <div
                className={classNames(
                  "A1LMrow2tit",
                  !time && isOk ? "A1LMrow2titShow" : ""
                )}
              >
                请选择领用日期!
              </div>
              <div
                className={classNames(
                  "A1LMrow2tit",
                  !dept && !user && isOk ? "A1LMrow2titShow" : ""
                )}
              >
                部门和人员至少填入一项
              </div>
            </div>
          </div>

          <div className="A1LMbtn">
            <Button type="primary" onClick={btnOkFu}>
              提交
            </Button>
            &emsp;
            <Popconfirm
              title="放弃编辑后，信息将不会保存!"
              okText="放弃"
              cancelText="取消"
              onConfirm={() => setModelId(0)}
              okButtonProps={{ loading: false }}
            >
              <Button>取消</Button>
            </Popconfirm>
          </div>
        </div>
      </Modal>
    </div>
  );
}

const MemoLogCamera = React.memo(LogCamera);

export default MemoLogCamera;
