import BreadTit from "@/components/BreadTit";
import { Button, Input, Modal, Popconfirm, Table } from "antd";
import React, {
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useState,
} from "react";
import styles from "./index.module.scss";
import TextArea from "antd/es/input/TextArea";
import {
  DownOutlined,
  UpOutlined,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
} from "@ant-design/icons";
import "./index.css";
import classNames from "classnames";
import {
  getStores1DetailAPI,
  getStores1ListAPI,
  stores1AddAPI,
  stores1DelAPI,
} from "@/store/action/stores1";
import { useDispatch, useSelector } from "react-redux";
import { RootState } from "@/store";
import AuthButton from "@/components/AuthButton";
import { MessageFu } from "@/utils/message";

function Stores1() {
  const powerInfo = useSelector(
    (state: RootState) => state.loginStore.authPageArr
  );
  const [powerInfoRes1, setPowerInfoRes1] = useState(false);
  const [powerInfoRes2, setPowerInfoRes2] = useState(false);

  useEffect(() => {
    const powerInfoTemp = powerInfo.filter((v: any) => v.id === 700)[0];
    if (powerInfoTemp) {
      powerInfoTemp.children.forEach((v: any) => {
        if (v.id === 702 && v.authority) setPowerInfoRes1(true);
        if (v.id === 703 && v.authority) setPowerInfoRes2(true);
      });
    }
  }, [powerInfo]);

  const dispatch = useDispatch();

  // 封装获取列表的函数
  const getStores1ListAPIFu = useCallback(() => {
    dispatch(getStores1ListAPI());
  }, [dispatch]);

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

  // 从仓库中获取总信息
  const infoList1 = useSelector(
    (state: RootState) => state.stores1Store.infoList
  );
  // 第一级的选中
  const [acind1, setAcind1] = useState(0);
  const infoList2 = useMemo(() => {
    if (infoList1 && infoList1[acind1] && infoList1[acind1].children)
      return infoList1[acind1].children;
    else return [];
  }, [acind1, infoList1]);

  const setAcind1Fu = useCallback((i: number) => {
    setAcind2(0);
    setAcind1(i);
  }, []);

  // 第二级的选中 --表格数据
  const [acind2, setAcind2] = useState(0);
  const infoList3 = useMemo(() => {
    if (infoList2 && infoList2[acind2] && infoList2[acind2].children)
      return infoList2[acind2].children;
    else return [];
  }, [acind2, infoList2]);

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

  // 点击新建 或者编辑出来的页面

  const [val1, setVal1] = useState("");
  const [val2, setVal2] = useState("");
  const [val3, setVal3] = useState("");

  const addType = useRef("1");
  const [open, setOpen] = useState(false);

  const editIdRef = useRef(0);
  // 点击新增或者编辑
  const addFu = useCallback(async (type: string, id?: number) => {
    if (!id) {
      editIdRef.current = 0;
      setVal1("");
      setVal2("");
      setVal3("");
    } else {
      editIdRef.current = id;
      const res = await getStores1DetailAPI(id);
      setVal1(res.data.name);
      setVal2(res.data.num);
      setVal3(res.data.description);
    }
    addType.current = type;
    setOpen(true);
  }, []);

  // 点击提交
  const btnOk = useCallback(async () => {
    if (val1 === "") return MessageFu.warning("不能为空!");
    if (addType.current !== "1" && val2 === "")
      return MessageFu.warning("不能为空!");
    const obj = {
      name: val1,
      num: val2 ? val2 : "",
      description: val3 ? val3 : "",
      level: Number(addType.current),
    } as any;
    if (addType.current === "2") obj.parentId = infoList1[acind1].id;
    else if (addType.current === "3") obj.parentId = infoList2[acind2].id;
    // 判断是新增还是编辑
    if (editIdRef.current) obj.id = editIdRef.current;
    const res: any = await stores1AddAPI(obj);
    if (res.code === 0) {
      MessageFu.success("操作成功!");
      getStores1ListAPIFu();
      setOpen(false);
    }
  }, [
    acind1,
    acind2,
    getStores1ListAPIFu,
    infoList1,
    infoList2,
    val1,
    val2,
    val3,
  ]);

  const columns = useMemo(() => {
    return [
      {
        title: "货架名称",
        dataIndex: "name",
      },
      {
        title: "货架编号",
        dataIndex: "num",
      },
      {
        title: "备注",
        render: (item: any) => (item.description ? item.description : "-"),
      },
      {
        title: "操作",
        render: (item: any) => (
          <div className="storesRTitInco">
            {powerInfoRes1 ? (
              <>
                <EditOutlined
                  title="编辑货架"
                  onClick={() => addFu("3", item.id)}
                />
                &emsp;
              </>
            ) : null}

            <Popconfirm
              title="确定删除吗?"
              okText="确定"
              cancelText="取消"
              onConfirm={() => delOne(item.id)}
            >
              {powerInfoRes2 ? <DeleteOutlined title="删除货架" /> : null}
            </Popconfirm>
          </div>
        ),
      },
    ];
  }, [addFu, delOne, powerInfoRes1, powerInfoRes2]);

  return (
    <div className={styles.Stores1}>
      <div className="breadTit">
        <BreadTit>
          <div className="breadTitRow active">库房设置</div>
        </BreadTit>
      </div>
      <div className="objectSonMain">
        {/* 左边的库区 */}
        <div className="storesL">
          <div className="storesLTit">
            <AuthButton id={702} type="primary" onClick={() => addFu("1")}>
              新建库区
            </AuthButton>
            &emsp;
            <Popconfirm
              title="确定删除吗?"
              okText="确定"
              cancelText="取消"
              onConfirm={() => delOne(infoList1[acind1].id)}
            >
              <AuthButton id={703}>删除</AuthButton>
            </Popconfirm>
          </div>
          <div className="storesLBox">
            {infoList1 && infoList1.length ? (
              infoList1.map((v: any, i: number) => (
                <div
                  className={classNames(
                    "storesLRow",
                    i === acind1 ? "storesLRowActive" : ""
                  )}
                  key={v.id}
                >
                  <div className="storesLRow_top">
                    <div className="incol" onClick={() => setAcind1Fu(i)}>
                      <DownOutlined hidden={i === acind1} />
                      <UpOutlined hidden={i !== acind1} />
                    </div>
                    <div
                      className="txt"
                      title={v.name}
                      onClick={() => setAcind1Fu(i)}
                    >
                      {v.name}
                    </div>
                    <div className="inco2">
                      {powerInfoRes1 ? (
                        <>
                          <PlusOutlined
                            title="新增库房"
                            onClick={() => addFu("2")}
                          />
                          &emsp;
                        </>
                      ) : null}

                      {powerInfoRes1 ? (
                        <EditOutlined
                          title="编辑库区"
                          onClick={() => addFu("1", v.id)}
                        />
                      ) : null}
                    </div>
                  </div>
                  {infoList2 && infoList2.length && i === acind1 ? (
                    <div className="storesLRow_show">
                      {infoList2.map((v2: any, i2: number) => (
                        <div
                          onClick={() => setAcind2(i2)}
                          className={classNames(
                            "storesLRow_showRow",
                            i2 === acind2 ? "active2" : ""
                          )}
                          key={v2.id}
                        >
                          {v2.name}&nbsp;<span>编号：</span>
                          {v2.num}
                        </div>
                      ))}
                    </div>
                  ) : (
                    <div className="noneData2">暂无数据</div>
                  )}
                </div>
              ))
            ) : (
              <div className="noneData">暂无数据</div>
            )}
          </div>
        </div>
        {/* 右边的表格 */}
        <div className="storesR">
          <div className="storesRTit">
            {infoList2 && infoList2.length ? (
              <>
                <h3>{infoList2[acind2].name}</h3>
                <div className="storesRTit1">
                  仓库编号：{infoList2[acind2].num}
                </div>
                <div className="storesRTitInco">
                  {powerInfoRes1 ? (
                    <>
                      <PlusOutlined
                        title="新增货架"
                        onClick={() => addFu("3")}
                      />
                      &emsp;
                      <EditOutlined
                        title="编辑库房"
                        onClick={() => addFu("2", infoList2[acind2].id)}
                      />
                      &emsp;
                    </>
                  ) : null}

                  <Popconfirm
                    title="确定删除吗?"
                    okText="确定"
                    cancelText="取消"
                    onConfirm={() => delOne(infoList2[acind2].id)}
                  >
                    {powerInfoRes2 ? <DeleteOutlined title="删除库房" /> : null}
                  </Popconfirm>
                </div>
              </>
            ) : null}
          </div>
          {/* 表格主体 */}
          <Table
            scroll={{ y: 518 }}
            dataSource={infoList3}
            columns={columns}
            rowKey="id"
            pagination={false}
          />
        </div>
      </div>
      {/* 新增或者编辑 */}
      <Modal
        wrapClassName="Stores1Modal"
        destroyOnClose
        open={open}
        title={
          addType.current === "1"
            ? "库区名称"
            : addType.current === "2"
            ? "库房信息"
            : "货架信息"
        }
        onCancel={() => setOpen(false)}
        footer={
          [] // 设置footer为空，去掉 取消 确定默认按钮
        }
      >
        <div className="modalMain">
          <div className="row">
            <div className="bs">*</div>
            <span>
              {addType.current === "1"
                ? "库区名称："
                : addType.current === "2"
                ? "仓库名称："
                : "货架名称："}
            </span>
            <Input
              maxLength={15}
              showCount
              value={val1}
              onChange={(e) => setVal1(e.target.value.trim())}
              style={{ width: 300 }}
              placeholder="请输入"
            />
          </div>
          {addType.current !== "1" ? (
            <div className="row">
              <div className="bs">*</div>
              <span>
                {addType.current === "2" ? "仓库编号：" : "货架编号："}
              </span>
              <Input
                maxLength={15}
                showCount
                value={val2}
                onChange={(e) => setVal2(e.target.value.trim())}
                style={{ width: 300 }}
                placeholder="请输入"
              />
            </div>
          ) : null}
          {addType.current === "3" ? (
            <div className="row rowAll">
              <span>&emsp;&emsp;备注：</span>
              <TextArea
                value={val3}
                onChange={(e) => setVal3(e.target.value.trim())}
                rows={3}
                placeholder="请输入"
                showCount
                maxLength={255}
              />
            </div>
          ) : null}
        </div>
        <br />
        <div className="modalBtn">
          <Button type="primary" onClick={btnOk}>
            提交
          </Button>
          &emsp;
          <Button onClick={() => setOpen(false)}>取消</Button>
        </div>
      </Modal>
    </div>
  );
}

const MemoStores1 = React.memo(Stores1);

export default MemoStores1;
