import React, { useCallback, useEffect, useMemo, useState } from "react";
import styles from "./index.module.scss";
import { Button, Input, Popconfirm, Switch, Table } from "antd";
import { MessageFu } from "@/utils/message";
import {
  A3_APIdel,
  A3_APIdisplay,
  A3_APIgetConfig,
  A3_APIgetList,
  A3_APIsort,
  A3_APIupdateConfig,
} from "@/store/action/A3Fliqlo";

import { RootState } from "@/store";
import A3Modal from "./A3Modal";
import { useDispatch, useSelector } from "react-redux";
import { A3TableType } from "@/types";
import ImageLazy from "@/components/ImageLazy";

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

  const [edit, setEdit] = useState(false);

  const [open1, setOpen1] = useState(false);
  const [open2, setOpen2] = useState(false);

  const [time1, setTime1] = useState("");
  const [time2, setTime2] = useState("");

  const time2ChangeFu = useCallback((val: string) => {
    if (Number(val) > 600) val = "600";
    setTime2(val.replace(/^(0+)|[^\d]+/g, ""));
  }, []);

  useEffect(() => {
    if (edit) {
      setOpen2(open1);
      setTime2(time1);
    }
  }, [edit, open1, time1]);

  const btnOk = useCallback(async () => {
    if (!time2) return MessageFu.warning("请输入时间!");
    const obj = {
      autoPlay: open2 ? "true" : "false",
      time: time2,
    };

    const res = await A3_APIupdateConfig(JSON.stringify(obj));

    if (res.code === 0) {
      MessageFu.success("修改成功!");
      setOpen1(open2);
      setTime1(time2);
      setEdit(false);
    }
  }, [open2, time2]);

  const [pid, setPid] = useState(0);

  // 获取配置
  const getConfigFu = useCallback(async () => {
    const res = await A3_APIgetConfig();
    if (res.code === 0) {
      setPid(res.data.id);
      const data = JSON.parse(res.data.content);
      setOpen1(data.autoPlay);
      setTime1(data.time);
    }
  }, []);

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

  // 获取表格列表
  const getListFu = useCallback(() => {
    if (pid) dispatch(A3_APIgetList(pid));
  }, [dispatch, pid]);

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

  const [open, setOpen] = useState(false);

  // 切换表格中的启用停用状态
  const isEnabledClickFu = useCallback(
    async (val: boolean, id: number) => {
      const isDisable = val ? 1 : 0;
      const res: any = await A3_APIdisplay(id, isDisable);
      if (res.code === 0) getListFu();
    },
    [getListFu]
  );

  // 点击上移和下移动
  const moveTableFu = useCallback(
    async (id1: number, id2: number) => {
      const res = await A3_APIsort(id1, id2);
      if (res.code === 0) getListFu();
    },
    [getListFu]
  );

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

  // 获取表格数据
  const tableInfo = useSelector((state: RootState) => state.A3Fliqlo.tableInfo);

  const columns = useMemo(() => {
    return [
      {
        title: "序号",
        render: (_: any, __: any, index: number) => index + 1,
      },
      {
        title: "图片",
        render: (item: A3TableType) => (
          <div className="tableImgAuto">
            <ImageLazy width={60} height={60} src={item.thumb} />
          </div>
        ),
      },
      {
        title: "展示状态",
        render: (item: A3TableType) => (
          <Switch
            checkedChildren="展示"
            unCheckedChildren="隐藏"
            checked={item.display === 1}
            onChange={(val) => isEnabledClickFu(val, item.id!)}
          />
        ),
      },
      {
        title: "操作",
        render: (item: A3TableType, record: any, index: number) => (
          <>
            <Button
              size="small"
              type="text"
              onClick={() => moveTableFu(item.id, tableInfo[index - 1].id)}
              disabled={index === 0}
            >
              上移
            </Button>
            <Button
              size="small"
              type="text"
              onClick={() => moveTableFu(item.id, tableInfo[index + 1].id)}
              disabled={index === tableInfo.length - 1}
            >
              下移
            </Button>

            <Popconfirm
              title="删除后无法恢复，是否删除?"
              okText="删除"
              cancelText="取消"
              onConfirm={() => delTableFu(item.id)}
            >
              <Button size="small" type="text" danger>
                删除
              </Button>
            </Popconfirm>
          </>
        ),
      },
    ];
  }, [delTableFu, isEnabledClickFu, moveTableFu, tableInfo]);

  // 点击上传图片
  const addClickFu = useCallback(() => {
    if (tableInfo.length >= 5) return MessageFu.warning("最多增加5条数据!");
    setOpen(true);
  }, [tableInfo.length]);

  return (
    <div className={styles.A3Fliqlo}>
      <div className="pageTitle">屏保管理</div>
      <div className="A3_top">
        <div className="A3_title">自动播放管理</div>

        <div className="A3_tit">
          <div>自动播放：</div>

          {edit ? (
            <Switch
              checkedChildren="开启"
              unCheckedChildren="关闭"
              checked={open2}
              onChange={(val) => setOpen2(val)}
            />
          ) : (
            <span>{open1 ? "开启" : "关闭"}</span>
          )}
          {edit ? (
            <div className="A3_time">
              <div className="A3_timeTxt">时间设置：</div>
              <Input
                style={{ width: 210 }}
                value={time2}
                onChange={(e) => time2ChangeFu(e.target.value)}
                addonAfter="秒"
                placeholder="请输入数字，不超过600"
              />
            </div>
          ) : (
            <div className="A3_time">超过 {time1} 秒时自动播放</div>
          )}
        </div>
        <div className="A3_topBtn">
          {edit ? (
            <>
              <Popconfirm
                title="放弃编辑后，信息将不会保存!"
                okText="放弃"
                cancelText="取消"
                onConfirm={() => setEdit(false)}
              >
                <Button>取消</Button>
              </Popconfirm>
              &emsp;
              <Button type="primary" onClick={btnOk}>
                提交
              </Button>
            </>
          ) : (
            <Button type="primary" onClick={() => setEdit(true)}>
              修改
            </Button>
          )}
        </div>
      </div>

      {/* 关于表格 */}

      <div className="tableBox">
        <div className="A3_title A3_title2">
          内容管理
          <div className="A3_Fbtn" onClick={addClickFu}>
            <Button type="primary">上传图片</Button>
          </div>
        </div>

        <Table
          dataSource={tableInfo}
          columns={columns}
          rowKey="id"
          pagination={false}
        />
      </div>

      {/* 点击上传图片出来的弹窗 */}
      {open ? (
        <A3Modal
          pid={pid}
          closeFu={() => setOpen(false)}
          addTableFu={() => getListFu()}
        />
      ) : null}
    </div>
  );
}

const MemoA3Fliqlo = React.memo(A3Fliqlo);

export default MemoA3Fliqlo;
