import AuthButton from "@/components/AuthButton";
import BreadTit from "@/components/BreadTit";
import ImageLazy from "@/components/ImageLazy";
import ObjectAdd from "@/components/ObjectAdd";
import { RootState } from "@/store";
import history, { urlParameter } from "@/utils/history";
import { Button, Cascader, Modal, Select, 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";
import "./index.css";
import LookObject2Log from "./table";
import { baseURL } from "@/utils/http";
import classNames from "classnames";
import { editObj2StoresAPI, getObj2InfoInAPI } from "@/store/action/object2";
import { obj3InStorage, storageStatusObj } from "@/utils/dataChange";
import { getStores1ListAPI } from "@/store/action/stores1";
import { MessageFu } from "@/utils/message";

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

  // 进页面通过id获取单个藏品详情
  const getObj2InfoInAPIFu = useCallback(async () => {
    const id = urlParamRef.current.id;
    const res = await getObj2InfoInAPI(id);
    const info = res.data.entity;
    const fileList = {
      img: [],
      video: [],
      audio: [],
      model: [],
      doc: [],
    } as any;
    res.data.file.forEach((v: any) => {
      fileList[v.type].push(v);
    });

    dispatch({
      type: "object2/getOneGoodsInfo",
      payload: { info, fileList },
    });
  }, [dispatch]);

  // 申请编辑和申请移库之后需要重新发送请求来更新按钮状态
  const upInfoAPIFu = useCallback(() => {
    getObj2InfoInAPIFu();
  }, [getObj2InfoInAPIFu]);

  useEffect(() => {
    getObj2InfoInAPIFu();
    return () => {
      // 退出页面的时候初始化仓库数据
      dispatch({
        type: "object2/getOneGoodsInfo",
        payload: {
          info: {},
          fileList: {
            img: [],
            video: [],
            audio: [],
            model: [],
            doc: [],
          },
        },
      });
    };
  }, [dispatch, getObj2InfoInAPIFu]);

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

  // 附件类型下拉框

  const fileSelectList = useMemo(() => {
    return [
      { id: 1, value: "img", label: "高清图片" },
      { id: 2, value: "video", label: "视频文件" },
      { id: 3, value: "audio", label: "音频文件" },
      { id: 4, value: "model", label: "三维模型" },
      { id: 5, value: "doc", label: "文档资料" },
    ];
  }, []);
  const [fileSelect, setFileSelect] = useState("img");
  const fileSelectChangeFu = (value: string) => {
    setFileSelect(value);
  };

  // 从仓库中获取信息
  const { info, fileList } = useSelector(
    (state: RootState) => state.object2Store.oneGoodsInfo
  );

  // 外形尺寸和具体质量
  let sizeRes = "";
  if (info.size && info.size.length) {
    const sizeArr = info.size.split(",");
    sizeRes = `(通长)${sizeArr[0]}cm&emsp;(通宽)${sizeArr[1]}cm&emsp;(通高)${sizeArr[2]}cm`;
  }

  let qualityRes = "-";
  if (info.quality && info.quality.length) {
    const qualityArr = info.quality.split(",");
    qualityRes = qualityArr[0] + qualityArr[1];
  }

  // 里面表格格式
  const columns = useMemo(() => {
    const tempArr = [
      {
        title: "附件名称",
        dataIndex: "name",
      },
      {
        title: "上传人",
        dataIndex: "creatorName",
      },

      {
        title: "上传时间",
        dataIndex: "updateTime",
      },
      {
        title: "操作",
        render: (item: any) => (
          <a
            target="_blank"
            href={baseURL + item.filePath}
            download
            rel="noreferrer"
          >
            下载
          </a>
        ),
      },
    ] as any;
    if (fileSelect === "img") {
      tempArr.unshift({
        title: "缩略图",
        render: (item: any) => (
          <ImageLazy width={80} height={50} src={item.filePath} />
        ),
      });
    }
    return tempArr;
  }, [fileSelect]);

  // 关于  申请编辑  申请移库  操作记录
  const [titCut, setTitCut] = useState("");

  const titCutFu = useCallback(
    (val: string) => {
      if (val === "2") {
        dispatch(getStores1ListAPI());
      }
      setTitCut(val);
    },
    [dispatch]
  );

  // 从仓库中获取库房总信息
  const moveOptions = useSelector(
    (state: RootState) => state.stores1Store.infoList
  );

  const moveLocRef = useRef("");
  const [moveLoc, setMoveLoc] = useState<any>([]);
  const moveLocChangeFu = (val: any, names: any) => {
    setMoveLoc(val);
    let temp = "";
    names.forEach((v: any, i: number) => {
      if (i < names.length - 1) temp += v.name + "/";
      else temp += v.name;
    });
    moveLocRef.current = temp;
  };

  const moveBtnOk = useCallback(async () => {
    const oldLoc = info.storageAncestor;
    const newLoc = moveLoc.join(",");
    if (!newLoc) return MessageFu.warning("请选择移库位置!");
    if (oldLoc === newLoc) return MessageFu.warning("位置不能相同!");
    const obj = {
      beforeJson: { id: oldLoc, name: obj3InStorage(info.storageAncestor) },
      afterJson: { id: newLoc, name: moveLocRef.current },
      goodsIds: info.id,
    };

    const res: any = await editObj2StoresAPI(obj);
    if (res.code === 0) {
      MessageFu.success("申请移库成功!");
      // 更新页面
      getObj2InfoInAPIFu();
      setTitCut("");
    }

    console.log("移库点击提交", oldLoc, newLoc);
  }, [getObj2InfoInAPIFu, info.id, info.storageAncestor, moveLoc]);

  return (
    <div className={styles.LookObject2}>
      <div className="breadTit">
        <BreadTit>
          <div className="breadTitRow">藏品总账</div>
          <div className="splitStr">/</div>
          <div className="breadTitRow active">查看</div>
        </BreadTit>
      </div>
      <div className="objectSonMain">
        {/* 上面的信息 */}
        <div className="topInfoBox">
          <div className="topInfoBoxL">
            {/* 解决有图片进页面显示 加载失败 图片 问题 */}
            {info.id ? (
              <ImageLazy src={info.thumb} width={300} height={300} />
            ) : null}
          </div>
          <div className="topInfoBoxR">
            <div className="topInfoBoxRTit">
              <div>
                <h1>{info.name}</h1>
                <div
                  className={classNames(
                    "bs",
                    info.storageStatus === "0"
                      ? "bs1"
                      : info.storageStatus === "in"
                      ? "bs2"
                      : info.storageStatus === "otu"
                      ? "bs3"
                      : "bs4"
                  )}
                >
                  {storageStatusObj[info.storageStatus]}
                </div>
              </div>
              <div>
                <AuthButton
                  id={202}
                  disabled={info.tempEdit !== 0}
                  size="small"
                  type="primary"
                  onClick={() => titCutFu("1")}
                >
                  申请编辑
                </AuthButton>
                &emsp;
                {info.storageStatus !== "0" && info.storageStatus !== "temp" ? (
                  <>
                    <AuthButton
                      id={205}
                      disabled={
                        info.tempMove !== 0 || info.storageStatus === "out"
                      }
                      size="small"
                      type="primary"
                      onClick={() => titCutFu("2")}
                    >
                      申请移库
                    </AuthButton>
                    &emsp;
                  </>
                ) : null}
                <Button size="small" onClick={() => titCutFu("3")}>
                  操作记录
                </Button>
              </div>
            </div>
            <div className="topInfoBoxRTxt">
              <div className="row">
                <div title={info.name}>
                  <span>藏品名称：</span>
                  <p>{info.name}</p>
                </div>
                <div title={info.namePrimitive}>
                  <span>原名：</span>
                  <p>{info.namePrimitive ? info.namePrimitive : "-"}</p>
                </div>
              </div>
              <div className="row">
                <div title={info.dictNum}>
                  <span>藏品编号名称：</span>
                  <p>{info.dictNum}</p>
                </div>
                <div title={info.num}>
                  <span>藏品编号：</span>
                  <p>{info.num ? info.num : "-"}</p>
                </div>
              </div>
              <div className="row">
                <div title={info.dictAge}>
                  <span>年代：</span>
                  <p>{info.dictAge}</p>
                </div>
                <div title={info.dictTexture}>
                  <span>文物质地：</span>
                  <p>{info.dictTexture}</p>
                </div>
              </div>
              <div className="row">
                <div title={info.ageSpecific}>
                  <span>具体年代：</span>
                  <p>{info.ageSpecific ? info.ageSpecific : "-"}</p>
                </div>
                <div title={info.dictGoodType}>
                  <span>文物类别：</span>
                  <p>{info.dictGoodType}</p>
                </div>
              </div>

              <div className="row">
                <div title={info.pcs}>
                  <span>实际数量：</span>
                  <p>{info.pcs}</p>
                </div>
                <div title={info.dictLevel}>
                  <span>文物级别：</span>
                  <p>{info.dictLevel}</p>
                </div>
              </div>
              <div className="row">
                <div title={sizeRes.replaceAll("&emsp;", " ")}>
                  <span>外形尺寸：</span>
                  <p dangerouslySetInnerHTML={{ __html: sizeRes }}></p>
                </div>
                <div title={info.sizeSpecific}>
                  <span>具体尺寸：</span>
                  <p>{info.sizeSpecific}</p>
                </div>
              </div>
              <div className="row">
                <div title={info.dictQualityScope}>
                  <span>质量范围：</span>
                  <p>{info.dictQualityScope}</p>
                </div>
                <div title={qualityRes}>
                  <span>具体质量：</span>
                  <p>{qualityRes}</p>
                </div>
              </div>

              <div className="row">
                <div title={info.complete}>
                  <span>完残程度：</span>
                  <p>{info.complete}</p>
                </div>
                <div title={info.repair}>
                  <span>保存状态：</span>
                  <p>{info.repair ? info.repair : "-"}</p>
                </div>
              </div>

              <div className="row">
                <div title={info.dictCheckInScope}>
                  <span>入藏时间范围：</span>
                  <p>{info.dictCheckInScope}</p>
                </div>
                <div title={info.checkInYear}>
                  <span>入藏年度：</span>
                  <p>{info.checkInYear ? info.checkInYear : "-"}</p>
                </div>
              </div>

              <div className="row">
                <div title={info.author}>
                  <span>著者：</span>
                  <p>{info.author ? info.author : "-"}</p>
                </div>
                <div title={info.vision}>
                  <span>版本：</span>
                  <p>{info.vision ? info.vision : "-"}</p>
                </div>
              </div>

              <div className="row">
                <div title={info.onFile}>
                  <span>存卷：</span>
                  <p>{info.onFile ? info.onFile : "-"}</p>
                </div>
                <div title={info.description}>
                  <span>来源说明：</span>
                  <p>{info.description ? info.description : "-"}</p>
                </div>
              </div>

              <div className="row">
                <div
                  title={
                    info.storageStatus !== "0" &&
                    info.storageStatus !== "temp" &&
                    info.storageAncestor
                      ? obj3InStorage(info.storageAncestor)
                      : ""
                  }
                >
                  <span>入库位置：</span>
                  <p>
                    {info.storageStatus !== "0" &&
                    info.storageStatus !== "temp" &&
                    info.storageAncestor
                      ? obj3InStorage(info.storageAncestor)
                      : "-"}
                  </p>
                </div>
                <div title={info.outLocation}>
                  <span>出库位置：</span>
                  <p>{info.outLocation ? info.outLocation : "-"}</p>
                </div>
              </div>
            </div>
          </div>
        </div>
        {/* 下面的表格 */}
        <div className="tableInfoBox">
          <div className="tableInfoBoxTit">
            <div className="rowTit">数字资源：</div>
            <div className="rowRr">
              <Select
                style={{ width: 150 }}
                value={fileSelect}
                onChange={fileSelectChangeFu}
                options={fileSelectList}
              />
            </div>
          </div>
          {/* 表格主体 */}
          <Table
            size="small"
            scroll={{ y: 190 }}
            dataSource={fileList[fileSelect]}
            columns={columns}
            rowKey="id"
            pagination={false}
          />
        </div>

        <div className="backBtn">
          <Button onClick={cancelFu}>返回</Button>
        </div>
      </div>

      {/* 点击上面的编辑 移库 操作记录出来的弹窗 */}

      {/*  申请编辑 */}
      {titCut === "1" ? (
        <ObjectAdd
          upInfoAPIFu={upInfoAPIFu}
          dirCode={info.dirCode}
          id={urlParamRef.current.id}
          colsePage={() => setTitCut("")}
          editId="edit"
        />
      ) : (
        <Modal
          wrapClassName="LookObject2Model"
          destroyOnClose
          open={!!titCut}
          title={titCut === "2" ? "申请移库" : "操作记录"}
          onCancel={() => setTitCut("")}
          footer={
            [] // 设置footer为空，去掉 取消 确定默认按钮
          }
        >
          {/* 申请移库 */}
          {titCut === "2" ? (
            <div className="moveLocBox">
              <div>
                <span>当前位置：</span>
                <p>{obj3InStorage(info.storageAncestor)}</p>
              </div>
              <div>
                <span>移库位置：</span>
                <Cascader
                  style={{ width: 300 }}
                  allowClear={false}
                  value={moveLoc}
                  onChange={moveLocChangeFu}
                  fieldNames={{
                    label: "name",
                    value: "id",
                    children: "children",
                  }}
                  options={moveOptions}
                  placeholder="请选择"
                />
              </div>
              <br />
              <br />
              <div className="moveBtn">
                <Button type="primary" onClick={moveBtnOk}>
                  提交
                </Button>
              </div>
            </div>
          ) : null}

          {/* 操作记录 */}
          {titCut === "3" ? (
            <div className="logBox">
              {/* 表格 */}
              <LookObject2Log id={info.id} />
            </div>
          ) : null}
        </Modal>
      )}
    </div>
  );
}

const MemoLookObject2 = React.memo(LookObject2);

export default MemoLookObject2;
