import BreadTit from "@/components/BreadTit";
import { object4AddAPI, object4infoOutAPI } from "@/store/action/object4";
import history, { urlParameter } from "@/utils/history";
import { Button, Input, Popconfirm, Select, Table } from "antd";
import TextArea from "antd/es/input/TextArea";
import React, {
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useState,
} from "react";
import { useLocation } from "react-router-dom";
import _ from "lodash";
import styles from "./index.module.scss";
import { useDispatch, useSelector } from "react-redux";
import { RootState } from "@/store";
import ImageLazy from "@/components/ImageLazy";
import GoodsAll from "./GoodsAll";
import LookModal from "@/components/LookObjTable/LookModal";
import { MessageFu } from "@/utils/message";
function AddObject4() {
  const dispatch = useDispatch();

  // 从仓库拿表格信息
  const results = useSelector(
    (state: RootState) => state.object4Store.goodsTableList
  );

  // 表格里面的输入框信息
  const inputRef = useRef(-1);
  const inputInfoRef = useRef<any>({});
  const inputChangeFu = useCallback(
    (e: React.ChangeEvent<HTMLInputElement>, id: number) => {
      clearTimeout(inputRef.current);
      inputRef.current = window.setTimeout(() => {
        if (e.target.value.trim() === "") return;
        inputInfoRef.current[id] = {
          names: e.target.value.trim(),
        };
        console.log(inputInfoRef.current);
      }, 500);
    },
    []
  );

  // 顶部数据
  const [addInfoTop, setAddInfoTop] = useState<any>({
    outType: "展览",
  });

  // 进入页面新增请求函数
  const object4AddAPIFu = useCallback(async () => {
    const res = await object4AddAPI();
    setAddInfoTop({ ...res.data, outType: "展览" });
    // 初始化表格数据
    dispatch({
      type: "object4/getGoodsTableList",
      payload: [],
    });
  }, [dispatch]);

  // 通过id获取详情函数
  const object4infoOutAPIFu = useCallback(
    async (id: number) => {
      const res = await object4infoOutAPI(id);
      setAddInfoTop(res.data.entity);
      // 设置表格信息
      dispatch({
        type: "object4/getGoodsTableList",
        payload: res.data.child,
      });
      // 设置出库位置ref
      if (res.data.child && res.data.child.length) {
        res.data.child.forEach((v: any) => {
          inputInfoRef.current[v.id] = {
            names: v.outLocation,
          };
        });
      }
    },
    [dispatch]
  );

  // 获取地址栏参数
  const location = useLocation();
  const [urlParam, setUrlParam] = useState<any>({});
  useEffect(() => {
    const obj = urlParameter(location.search);
    setUrlParam(obj);

    if (obj.id) {
      // 如果是编辑
      object4infoOutAPIFu(obj.id);
    } else object4AddAPIFu();
  }, [location, object4AddAPIFu, object4infoOutAPIFu]);
  // 点击返回
  const cancelFu = useCallback(() => {
    history.push({
      pathname: `/object/4`,
      state: { k: urlParam.k ? urlParam.k : "1", d: urlParam.d },
    });
  }, [urlParam.d, urlParam.k]);

  // 点击提交
  const submitFu = useCallback(async () => {
    if (results.length === 0)
      return MessageFu.warning("至少需要添加一条藏品信息!");

    const objLength = Object.keys(inputInfoRef.current).length;
    if (objLength < results.length) return MessageFu.warning("请输入出库位置!");

    const obj = {
      description: addInfoTop.description,
      id: addInfoTop.id,
      outType: addInfoTop.outType,
      goodsIds: results.map((v: any) => v.id).join(","),
      location: inputInfoRef.current,
    };

    const res: any = await object4AddAPI(obj);
    if (res.code === 0) {
      MessageFu.success("操作成功!");
      cancelFu();
    }
  }, [
    addInfoTop.description,
    addInfoTop.id,
    addInfoTop.outType,
    cancelFu,
    results,
  ]);

  // 点击添加或者编辑出来页面
  const [addPage, setAddPage] = useState(false);

  // 选中的表格数据
  const [tableSelectList, setTableSelectList] = useState([]);

  // 表格的勾选状态
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);

  // 表格的多选
  const rowSelection = {
    selectedRowKeys,
    onChange: (selectedRowKeys: any, selectedRows: any) => {
      setTableSelectList(selectedRows);
      setSelectedRowKeys(selectedRowKeys);
    },
  };

  // 点击添加
  const addPageFu = useCallback((id?: any) => {
    setAddPage(true);
  }, []);

  // 点击删除
  const delTableListFu = useCallback(() => {
    console.log("多个删除", tableSelectList);
    const data = _.differenceBy(results, tableSelectList, "id");
    dispatch({ type: "object4/getGoodsTableList", payload: data });
    setTableSelectList(data);

    // 清除表格的勾选状态
    setSelectedRowKeys([]);

    // 同时删除出库位置信息
    tableSelectList.forEach((v: any) => {
      delete inputInfoRef.current[v.id];
    });
  }, [dispatch, results, tableSelectList]);

  // 控制弹窗的显示隐藏
  const [show, setShow] = useState(false);
  // 点击表格里面的查看
  const lookIdRef = useRef(-1);
  const lookGoods = useCallback((id: number) => {
    lookIdRef.current = id;
    setShow(true);
  }, []);

  // 表格数据
  const columns = useMemo(() => {
    return [
      {
        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: "出库位置",
        width: 200,
        render: (item: any) => (
          <Input
            defaultValue={item.outLocation}
            onChange={(e) => inputChangeFu(e, item.id)}
            maxLength={15}
            showCount
            placeholder="请输入"
          />
        ),
      },
      {
        title: "操作",
        render: (item: any) => (
          <>
            <Button type="text" danger onClick={() => lookGoods(item.id)}>
              查看
            </Button>
          </>
        ),
      },
    ];
  }, [inputChangeFu, lookGoods]);

  // 出库类型下拉框变化

  const options = useSelector(
    (state: RootState) => state.object4Store.typeSelectList
  );

  const typeChangeFu = useCallback(
    (value: string) => {
      setAddInfoTop({ ...addInfoTop, outType: value });
    },
    [addInfoTop]
  );

  return (
    <div className={styles.AddObject4}>
      <div className="breadTit">
        <BreadTit>
          <div className="breadTitRow">出库管理</div>
          <div className="splitStr">/</div>
          <div className="breadTitRow active">
            {urlParam.id ? "编辑" : "新增"}
          </div>
        </BreadTit>
      </div>
      <div className="objectSonMain">
        {/* 上面的信息展示 */}
        <div className="addInfoTop">
          <div className="row">
            <div>
              <span className="bs">出库编号：</span>
              <Input style={{ width: 300 }} value={addInfoTop.num} disabled />
            </div>
            <div>
              <span className="bs">登记人员：</span>
              <Input
                style={{ width: 300 }}
                value={addInfoTop.creatorName}
                disabled
              />
            </div>
            <div>
              <span className="bs">出库类型：</span>
              <Select
                style={{ width: 300 }}
                placeholder="请选择"
                value={addInfoTop.outType}
                onChange={typeChangeFu}
                options={options}
              />
            </div>
          </div>
          <div className="rowAll">
            <span>出库说明：</span>
            <TextArea
              value={addInfoTop.description}
              onChange={(e) =>
                setAddInfoTop({ ...addInfoTop, description: e.target.value })
              }
              rows={3}
              placeholder="请输入"
              showCount
              maxLength={255}
            />
          </div>
        </div>
        {/* 下面的表格 */}
        <div className="addTableBox">
          <div className="addTableBox_Tit">
            <div className="addTableBox_TitL">藏品信息</div>
            <div className="addTableBox_TitR">
              <Button onClick={() => addPageFu(null)}>添加</Button>
              &emsp;
              <Popconfirm
                disabled={tableSelectList.length === 0}
                title="确定删除吗?"
                okText="确定"
                cancelText="取消"
                onConfirm={delTableListFu}
              >
                <Button disabled={tableSelectList.length === 0}>删除</Button>
              </Popconfirm>
            </div>
          </div>

          {/* 表格主体 */}
          <div className="addTableBox_table">
            <Table
              size="small"
              scroll={{ y: 355 }}
              rowSelection={{
                type: "checkbox",
                ...rowSelection,
              }}
              dataSource={results}
              columns={columns}
              rowKey="id"
              pagination={false}
            />
          </div>

          {/* 返回按钮 */}
          <div className="addTableBox_btn">
            <Button type="primary" onClick={submitFu}>
              提交
            </Button>
            &emsp;
            <Button onClick={cancelFu}>返回</Button>
          </div>
        </div>
      </div>
      {/* 点击添加或者编辑出来的页面 */}
      {addPage ? <GoodsAll colsePage={() => setAddPage(false)} /> : null}

      {/* 点击查看出来的对话框 */}
      {show ? (
        <LookModal
          id={lookIdRef.current}
          show={show}
          closeShow={() => setShow(false)}
        />
      ) : null}
    </div>
  );
}

const MemoAddObject4 = React.memo(AddObject4);

export default MemoAddObject4;
