import AuthButton from "@/components/AuthButton";
import BreadTit from "@/components/BreadTit";
import ImageLazy from "@/components/ImageLazy";
import LookModal from "@/components/LookObjTable/LookModal";
import { RootState } from "@/store";
import { object4infoOutAPI, returnObject4API } from "@/store/action/object4";
import { statusObjCK2 } from "@/utils/dataChange";
import history, { urlParameter } from "@/utils/history";
import { MessageFu } from "@/utils/message";
import { Button, Popconfirm, Table } from "antd";
import React, {
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useState,
} from "react";
import { useDispatch, useSelector } from "react-redux";
import { useLocation } from "react-router-dom";
import styles from "./index.module.scss";
function LookObject4() {
  const dispatch = useDispatch();

  // 获取地址栏参数
  const location = useLocation();
  const urlParamRef = useRef<any>({});
  useEffect(() => {
    urlParamRef.current = urlParameter(location.search);
    // console.log("地址栏参数", urlParamRef.current);
  }, [location]);

  const getInfo = useCallback(async () => {
    const id = urlParamRef.current.id;
    const res1 = await object4infoOutAPI(id);
    const info = res1.data.entity;
    const list = res1.data.child;
    info.statusTxt = statusObjCK2[info.status];
    dispatch({ type: "object4/getLookInfo", payload: { info, list } });
  }, [dispatch]);

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

  const { info, list: tableList } = useSelector(
    (state: RootState) => state.object4Store.lookInfo
  );

  // 点击返回
  const cancelFu = () => {
    history.push({
      pathname: `/object/4`,
      state: {
        k: urlParamRef.current.k ? urlParamRef.current.k : "1",
        d: urlParamRef.current.d,
      },
    });
  };

  // 控制弹窗的显示隐藏
  const [show, setShow] = useState(false);
  // 点击表格里面的查看
  const lookIdRef = useRef(-1);

  const lookGoods = useCallback((id: number) => {
    lookIdRef.current = id;
    setShow(true);
  }, []);

  // 表格格式
  const columns = useMemo(() => {
    const tempArr = [
      {
        title: "缩略图",
        render: (item: any) => (
          <ImageLazy width={120} height={70} src={item.thumb} />
        ),
      },
      {
        title: "藏品编号名称",
        dataIndex: "dictNum",
      },
      {
        title: "藏品编号",
        render: (item: any) => (item.num ? item.num : "-"),
      },
      {
        title: "藏品名称",
        dataIndex: "name",
      },
      {
        title: "类别",
        dataIndex: "dictGoodType",
      },
      {
        title: "完残程度",
        dataIndex: "complete",
      },
      {
        title: "出库位置",
        dataIndex: "outLocation",
      },

      {
        title: "出库状态",
        render: (item: any) =>
          item.storageStatus === "out"
            ? "待归还"
            : item.storageStatus === "in"
            ? "已归还"
            : "-",
      },
      {
        title: "操作",
        render: (item: any) => (
          <>
            <Button type="text" danger onClick={() => lookGoods(item.id)}>
              查看
            </Button>
          </>
        ),
      },
    ];

    return tempArr;
  }, [lookGoods]);

  // 选中的表格数据
  const [tableSelectList, setTableSelectList] = useState([]);
  // 表格的多选和禁选
  const rowSelection = {
    selectedRowKeys: tableSelectList,
    onChange: (selectedRowKeys: any) => {
      setTableSelectList(selectedRowKeys);
    },
    getCheckboxProps: (record: any) => ({
      disabled: record.storageStatus === "in" || info.status !== 3, // 已归还的禁止选中
    }),
  };

  // 点击归还
  const returnGoodsFu = useCallback(async () => {
    console.log("---------点击了归还", tableSelectList);
    const obj = {
      goodsIds: tableSelectList.join(","),
      id: info.id,
    };
    const res: any = await returnObject4API(obj);
    if (res.code === 0) {
      MessageFu.success("归还成功!");
      // 清空表格选中状态和数据
      setTableSelectList([]);
      getInfo();
    }
  }, [getInfo, info.id, tableSelectList]);

  return (
    <div className={styles.LookObject4}>
      <div className="breadTit">
        <BreadTit>
          <div className="breadTitRow">出库管理</div>
          <div className="splitStr">/</div>
          <div className="breadTitRow active">
            {info.status === 3 ? "查看-归还" : "查看"}
          </div>
        </BreadTit>
      </div>
      <div className="objectSonMain">
        <div className="topTit">出库信息</div>
        <div className="topInfo">
          <div className="topInfoRow">
            <div>
              <div className="one">出库编号：</div>
              <div>{info.num}</div>
            </div>
            <div>
              <div className="one">出库人员：</div>
              <div>{info.creatorName}</div>
            </div>
            <div>
              <div className="one">出库类型：</div>
              <div>{info.outType}</div>
            </div>
            <div>
              <div className="one">审核结果：</div>
              <div>{info.statusTxt}</div>
            </div>
          </div>
          <div className="topInfoTex" title={info.description}>
            <span>登记说明：</span>
            {info.description ? info.description : "-"}
          </div>
          <div className="topInfoTex" title={info.reason}>
            <span>审核说明：</span>
            {info.reason ? info.reason : "-"}
          </div>
        </div>
        <br />
        <div className="topTit topTit2">
          藏品信息
          {info.status === 3 ? (
            <div className="titBtn">
              <Popconfirm
                disabled={tableSelectList.length === 0}
                title="确定归还吗?"
                okText="确定"
                cancelText="取消"
                onConfirm={returnGoodsFu}
              >
                <AuthButton id={406} disabled={tableSelectList.length === 0}>
                  归还
                </AuthButton>
              </Popconfirm>
            </div>
          ) : null}
        </div>
        <div className="goodsInfo">
          {/* 表格信息 */}
          <Table
            size="small"
            scroll={{ y: 360 }}
            rowSelection={{
              type: "checkbox",
              ...rowSelection,
            }}
            dataSource={tableList}
            columns={columns}
            rowKey="id"
            pagination={false}
          />
        </div>
        <div className="backBtn">
          {info.status === 2 ? (
            <AuthButton
              id={402}
              type="primary"
              onClick={() =>
                history.push(
                  `/object/4/add?k=${urlParamRef.current.k}&d=${urlParamRef.current.d}&id=${urlParamRef.current.id}`
                )
              }
            >
              编辑
            </AuthButton>
          ) : null}
          &emsp;
          <Button onClick={cancelFu}>返回</Button>
        </div>
      </div>
      {/* 点击查看出来的对话框 */}
      {show ? (
        <LookModal
          id={lookIdRef.current}
          show={show}
          closeShow={() => setShow(false)}
        />
      ) : null}
    </div>
  );
}

const MemoLookObject4 = React.memo(LookObject4);

export default MemoLookObject4;
