import React, {
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useState,
} from "react";
import styles from "./index.module.scss";
import {
  Button,
  Cascader,
  Checkbox,
  Input,
  Popconfirm,
  Select,
  Table,
  Tooltip,
} from "antd";
import { useDispatch, useSelector } from "react-redux";
import { B2FromDataType, B2ResNum } from "./data";
import { B1options1, B1options1Obj } from "../B1Plan/data";
import {
  B2_APIgetlist,
  B2_APIgetlistAll,
  B2_APIremove,
  B2_APIreset,
} from "@/store/action/B2Scene";
import store, { RootState } from "@/store";
import { B2tableType } from "@/types";
import { MessageFu } from "@/utils/message";
import { QuestionCircleOutlined } from "@ant-design/icons";
import ExportJsonExcel from "js-export-excel";
import dayjs from "dayjs";
import AuditMo from "./AuditMo";
import clasNames from "classnames";
import { mapDataAll1 } from "../C1User/AddUser/city";
import LookReDo from "./LookReDo";
import EditNum from "./EditNum";
import MateNum from "./MateNum";
import { getTokenInfo } from "@/utils/storage";

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

  // 筛选和分页
  const [tableSelect, setTableSelect] = useState<B2FromDataType>({
    siteArr: undefined,
    province: "",
    city: "",
    region: "",
    auditStatus: "",
    roomName: "",
    searchKey: "",
    pageSize: 10,
    pageNum: 1,
    isSiteEmpty: 0,
  });

  const tableSelectRef = useRef({} as B2FromDataType);

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

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

  // 发送接口的函数
  const getListFu = useCallback(() => {
    const objTemp: any = {};

    if (tableSelectRef.current.siteArr) {
      const temp = tableSelectRef.current.siteArr;
      objTemp.province = temp[0] || "";
      objTemp.city = temp[1] || "";
      objTemp.region = temp[2] || "";
    }

    const obj = {
      ...tableSelectRef.current,
      ...objTemp,
    };
    dispatch(B2_APIgetlist(obj));
  }, [dispatch]);

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

  // 输入框的改变
  const txtChangeFu = useCallback(
    (txt: string, key: "roomName" | "searchKey") => {
      setTableSelect({ ...tableSelect, [key]: txt });
    },
    [tableSelect]
  );

  // 点击搜索
  const clickSearch = useCallback(() => {
    setTableSelect({ ...tableSelect, pageNum: 1 });
    setTimeout(() => {
      setTimeKey(Date.now());
    }, 50);
  }, [tableSelect]);

  // 点击重置
  const [inputKey, setInputKey] = useState(1);
  const resetSelectFu = useCallback(() => {
    // 把2个输入框和时间选择器清空
    setInputKey(Date.now());
    setTableSelect({
      siteArr: undefined,
      province: "",
      city: "",
      region: "",
      auditStatus: "",
      roomName: "",
      searchKey: "",
      pageSize: 10,
      pageNum: 1,
      isSiteEmpty: 0,
    });
    setTimeout(() => {
      setTimeKey(Date.now());
    }, 50);
  }, []);

  // 从仓库获取列表
  const B2TableList = useSelector(
    (state: RootState) => state.B2Scene.B2TableList
  );
  // 页码变化
  const paginationChange = useCallback(
    () => (pageNum: number, pageSize: number) => {
      setTableSelect({ ...tableSelect, pageNum, pageSize });
      setTimeout(() => {
        setTimeKey(Date.now());
      }, 50);
    },
    [tableSelect]
  );

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

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

  // 修改机房编码
  const [editNum, setEditNum] = useState({
    id: 0,
    num: "",
    name: "",
    roomName: "",
  });

  const columns = useMemo(() => {
    return [
      {
        title: "机房编码",
        render: (item: B2tableType) =>
          item.roomNum ? (
            <span
              onClick={() =>
                setEditNum({
                  id: item.id,
                  num: item.roomNum,
                  name: item.sceneName,
                  roomName: item.roomName,
                })
              }
              className="B2audit"
            >
              {item.roomNum}
            </span>
          ) : (
            "（空）"
          ),
      },
      {
        title: "站址地区",
        render: (item: B2tableType) =>
          !item.province && !item.city && !item.region
            ? "（空）"
            : `${item.province}-${item.city}-${item.region}`,
      },
      {
        title: "站址名称",
        render: (item: B2tableType) => item.roomName || "（空）",
      },
      {
        title: "场景名称",
        render: (item: B2tableType) => item.sceneName || "（空）",
      },
      {
        title: "场景链接",
        render: (item: B2tableType) =>
          item.link ? (
            <a
              target="_blank"
              href={item.link}
              style={{ cursor: "pointer" }}
              title={item.link}
              rel="noreferrer"
            >
              {item.link.length >= 25
                ? item.link.substring(0, 25) + "..."
                : item.link}
            </a>
          ) : (
            "（空）"
          ),
      },
      {
        title: "场景码",
        render: (item: B2tableType) => (
          <>
            {item.sceneCode || "（空）"}

            {/* up-只有计算失败的时候显示 ?  */}
            {item.scheduleStatus === 2 ? (
              <span
                style={{ cursor: "pointer" }}
                hidden={!item.scheduleStatus && item.scheduleStatus !== 0}
              >
                <Tooltip title={Reflect.get(B2ResNum, item.scheduleStatus)}>
                  &nbsp;
                  <QuestionCircleOutlined rev={undefined} />
                </Tooltip>
              </span>
            ) : null}
          </>
        ),
      },
      {
        title: "相机SN码",
        render: (item: B2tableType) => item.cameraSn || "（空）",
      },
      {
        title: "拍摄时间",
        render: (item: B2tableType) => item.shootTime || "（空）",
      },
      {
        title: "审核状态",
        render: (item: B2tableType) => (
          <>
            <span
              className={clasNames(
                "B2audit",
                item.auditStatus === 2 ? "B2auditNo" : ""
              )}
              onClick={() => {
                if (item.auditStatus === 2) return;
                setAuditInfo({
                  oldState: item.auditStatus,
                  id: item.id,
                  sceneCode: item.sceneCode,
                  auditDesc: item.auditDesc,
                });
              }}
            >
              {Reflect.get(B1options1Obj, item.auditStatus) || "（空）"}
            </span>
            <span style={{ cursor: "pointer" }} hidden={!item.auditDesc}>
              <Tooltip title={item.auditDesc}>
                &nbsp;
                <QuestionCircleOutlined rev={undefined} />
              </Tooltip>
            </span>
          </>
        ),
      },
      {
        title: "审核时间",
        render: (item: B2tableType) => item.auditTime || "（空）",
      },
      {
        title: "操作",
        render: (item: B2tableType) => (
          <>
            <Popconfirm
              title="将重置该场景的审核状态，推送状态，请谨慎操作。"
              okText="重置"
              cancelText="取消"
              onConfirm={() => resByIdFu(item.id)}
              okButtonProps={{ loading: false }}
            >
              <Button size="small" type="text">
                重置
              </Button>
            </Popconfirm>

            {/* 暂时隐藏按钮 */}
            {/* {item.filePath ? (
              <a
                className="B2TabA"
                // hidden={!item.filePath}
                href={item.filePath}
                download={item.sceneName || item.sceneCode + ".json"}
              >
                下载Json
              </a>
            ) : (
              <span className="B2TabANo">下载Json</span>
            )} */}

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

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

    if (B2TableList.list.length === 0)
      return MessageFu.warning("当前搜索条件没有数据!");
    const name = "场景审核" + dayjs(new Date()).format("YYYY-MM-DD HH:mm");

    const objTemp: any = {};

    if (tableSelectRef.current.siteArr) {
      const temp = tableSelectRef.current.siteArr;
      objTemp.province = temp[0] || "";
      objTemp.city = temp[1] || "";
      objTemp.region = temp[2] || "";
    }

    const res = await B2_APIgetlistAll({
      ...tableSelect,
      ...objTemp,
      pageNum: 1,
      pageSize: 99999,
    });
    if (res.code === 0) {
      if (res.data.records.length <= 0)
        return MessageFu.warning("当前搜索条件没有数据!");
      const option = {
        fileName: name,
        datas: [
          {
            sheetData: res.data.records.map((v: B2tableType) => ({
              roomName: v.roomName || "（空）",
              roomNum: v.roomNum || "（空）",
              myCity:
                !v.province && !v.city && !v.region
                  ? "（空）"
                  : `${v.province}-${v.city}-${v.region}`,
              pmName: v.creatorId === 1 ? "管理员" : v.pmName || "（空）",
              sceneName: v.sceneName || "（空）",
              link: v.link || "（空）",
              sceneCode: v.sceneCode || "（空）",
              cameraSn: v.cameraSn || "（空）",
              shootTime: v.shootTime || "（空）",
              snapUseDept: v.snapUseDept || "（空）",
              snapUseName: v.snapUseName || "（空）",
              auditStatus:
                Reflect.get(B1options1Obj, v.auditStatus) || "（空）",
              auditTime: v.auditTime || "（空）",
            })),
            sheetName: name,
            sheetFilter: [
              "roomNum",
              "myCity",
              "roomName",
              "sceneName",
              "link",
              "sceneCode",
              "cameraSn",
              "shootTime",
              "auditStatus",
              "auditTime",
            ],
            sheetHeader: [
              "机房编码",
              "站址地区",
              "站址名称",
              "场景名称",
              "场景链接",
              "场景码",
              "相机SN码",
              "拍摄时间",
              "审核状态",
              "审核时间",
            ],
            columnWidths: [10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10],
          },
        ],
      };

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

  // 审核弹窗的信息
  const [auditInfo, setAuditInfo] = useState({
    oldState: -1,
    id: 0,
    sceneCode: "",
    auditDesc: "",
  });

  // 查看重复的场景
  const [lookReDo, setLookReDo] = useState(false);

  // 场景码匹配
  const [mateNum, setMateNum] = useState(false);

  // 场景码匹配按钮 只有管理员才会显示
  const [mateBtnShow, setMateBtnShow] = useState(false);

  useEffect(() => {
    const userInfo = getTokenInfo().user;
    if (userInfo && userInfo.isAdmin && userInfo.isAdmin === 1)
      setMateBtnShow(true);
  }, []);

  return (
    <div className={styles.B2Scene}>
      <div className="pageTitle">场景审核</div>
      {/* 顶部筛选 */}
      <div className="B2top">
        {/* 左侧输入框 */}
        <div className="B2top1">
          <div className="B2topRow">
            <span>搜索项：</span>
            <Input
              key={inputKey}
              maxLength={24}
              style={{ width: 250 }}
              placeholder="请输入机房编码/场景码,最多24字"
              allowClear
              onChange={(e) => txtChangeFu(e.target.value, "searchKey")}
            />
          </div>

          <div className="B2topRow">
            <span>站址地区：</span>
            <Cascader
              disabled={!!tableSelect.isSiteEmpty}
              changeOnSelect
              value={tableSelect.siteArr}
              style={{ width: 250 }}
              options={mapDataAll1}
              placeholder="全部"
              onChange={(e) =>
                setTableSelect({ ...tableSelect, siteArr: e as string[] })
              }
            />
          </div>
          <div className="B2topRow">
            <Checkbox
              checked={!!tableSelect.isSiteEmpty}
              onChange={(e) =>
                setTableSelect({
                  ...tableSelect,
                  siteArr: e.target.checked ? undefined : tableSelect.siteArr,
                  isSiteEmpty: e.target.checked ? 1 : 0,
                })
              }
            >
              仅查看站址地区为空的场景
            </Checkbox>
          </div>
        </div>
        {/* 右侧按钮 */}
        <div className="B2top2">
          <div>
            <div className="B2topRow">
              <span>站址名称：</span>
              <Input
                key={inputKey}
                maxLength={10}
                style={{ width: 235 }}
                placeholder="请输入站址名称,最多10字"
                allowClear
                onChange={(e) => txtChangeFu(e.target.value, "roomName")}
              />
            </div>

            <div className="B2topRow">
              <span>审核状态：</span>
              <Select
                style={{ width: 250 }}
                value={tableSelect.auditStatus}
                onChange={(e) =>
                  setTableSelect({ ...tableSelect, auditStatus: e })
                }
                options={B1options1}
              />
            </div>
          </div>
          <div>
            {mateBtnShow ? (
              <>
                <Button onClick={() => setMateNum(true)}>场景码匹配</Button>
                &emsp;
              </>
            ) : null}
            <Button onClick={() => setLookReDo(true)}>查看重复的场景</Button>
            &emsp;
            <Button onClick={resetSelectFu}>重置</Button>&emsp;
            <Button type="primary" onClick={clickSearch}>
              查询
            </Button>
            &emsp;
            <Button type="primary" onClick={deriveFu}>
              导出表格
            </Button>
          </div>
        </div>
      </div>

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

      {/* 点击审核出来的弹窗 */}
      {auditInfo.id ? (
        <AuditMo
          auditInfo={auditInfo}
          colseFu={() =>
            setAuditInfo({ oldState: -1, id: 0, sceneCode: "", auditDesc: "" })
          }
          upTableFu={(id, newState, newDesc, newTime) => {
            const oldObj = store.getState().B2Scene.B2TableList;
            const newObj = {
              list: oldObj.list.map((v) => ({
                ...v,
                auditStatus: v.id === id ? newState : v.auditStatus,
                auditDesc: v.id === id ? newDesc : v.auditDesc,
                auditTime: v.id === id ? newTime : v.auditTime,
              })),
              total: oldObj.total,
            };

            store.dispatch({ type: "B2/getList", payload: newObj });
          }}
        />
      ) : null}

      {/* 查看重复的场景 */}
      {lookReDo ? <LookReDo closePageFu={() => setLookReDo(false)} /> : null}

      {/* 修改机房编码 */}
      {editNum.num ? (
        <EditNum
          info={editNum}
          closeFu={() => setEditNum({ id: 0, num: "", name: "", roomName: "" })}
          upTableFu={getListFu}
        />
      ) : null}

      {/* 场景码匹配 */}
      {mateNum ? <MateNum closeFu={() => setMateNum(false)} /> : null}

      {/*  右下角的列表数量 */}
      <div className="tableNumBox">
        共 <span>{B2TableList.total}</span> 条数据
      </div>
    </div>
  );
}

const MemoB2Scene = React.memo(B2Scene);

export default MemoB2Scene;
