import BreadTit from "@/components/BreadTit";
import { object6AddAPI, object6infoOutAPI } from "@/store/action/object6";
import history, { urlParameter } from "@/utils/history";
import { Button, Input, Popconfirm, 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 AddObject6() {
  const dispatch = useDispatch();

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

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

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

  // 通过id获取详情函数
  const object6infoOutAPIFu = useCallback(
    async (id: number) => {
      const res = await object6infoOutAPI(id);
      setAddInfoTop(res.data.entity);
      // 设置表格信息
      dispatch({
        type: "object6/getGoodsTableList",
        payload: res.data.child,
      });
    },
    [dispatch]
  );

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

    if (obj.id) {
      // 如果是编辑
      object6infoOutAPIFu(obj.id);
    } else object6AddAPIFu();
  }, [location, object6AddAPIFu, object6infoOutAPIFu]);
  // 点击返回
  const cancelFu = useCallback(() => {
    history.push({
      pathname: `/object/6`,
      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 obj = {
      description: addInfoTop.description,
      id: addInfoTop.id,
      goodsIds: results.map((v: any) => v.id).join(","),
    };

    const res: any = await object6AddAPI(obj);
    if (res.code === 0) {
      MessageFu.success("操作成功!");
      cancelFu();
    }
  }, [addInfoTop.description, addInfoTop.id, 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: "object6/getGoodsTableList", payload: data });
    setTableSelectList(data);

    // 清除表格的勾选状态
    setSelectedRowKeys([]);
  }, [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: "年代",
        dataIndex: "dictAge",
      },
      {
        title: "操作",
        render: (item: any) => (
          <>
            <Button type="text" danger onClick={() => lookGoods(item.id)}>
              查看
            </Button>
          </>
        ),
      },
    ];
  }, [lookGoods]);

  return (
    <div className={styles.AddObject6}>
      <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: 400 }} value={addInfoTop.num} disabled />
            </div>
            <div>
              <span className="bs">登记人员：</span>
              <Input
                style={{ width: 400 }}
                value={addInfoTop.creatorName}
                disabled
              />
            </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 MemoAddObject6 = React.memo(AddObject6);

export default MemoAddObject6;
