import BreadTit from "@/components/BreadTit";
import history, { urlParameter } from "@/utils/history";
import { Input, Select, Table, Popconfirm, Button } 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 styles from "./index.module.scss";
import ObjectAdd from "@/components/ObjectAdd";
import ImageLazy from "@/components/ImageLazy/index";
import { useDispatch, useSelector } from "react-redux";
import { RootState } from "@/store";
import {
  delInTablesAPI,
  getObj1InfoTableAPI,
  object1AddAPI,
  object1infoOutAPI,
} from "@/store/action/object1";
import _ from "lodash";
import { MessageFu } from "@/utils/message";
function AddObject1() {
  const dispatch = useDispatch();

  // 从仓库中获取藏品来源下拉数据
  const options = useSelector(
    (state: RootState) => state.loginStore.selectAll["文物来源"]
  );
  // 顶部数据
  const [addInfoTop, setAddInfoTop] = useState<any>({});

  // 进入页面新增请求函数
  const object1AddAPIFu = useCallback(async () => {
    const res = await object1AddAPI();
    setAddInfoTop({
      ...res.data,
      sourceName:null
      // sourceName: options[0].name ? options[0].name : "",
    });
  }, []);

  // 通过id获取详情函数
  const object1infoOutAPIFu = useCallback(
    async (id: number) => {
      const res = await object1infoOutAPI(id);
      setAddInfoTop(res.data);
      // 获取表格详情信息
      dispatch(getObj1InfoTableAPI(id));
    },
    [dispatch]
  );

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

    if (obj.id) {
      // 如果是编辑
      object1infoOutAPIFu(obj.id);
    } else object1AddAPIFu();
  }, [location, object1AddAPIFu, object1infoOutAPIFu]);

  // 藏品来源下拉框
  const handleChange = (value: string) => {
    setAddInfoTop({ ...addInfoTop, sourceName: value });
  };

  // 表格数据

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

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

  // 前端删除成功的id集合，用于点击存入草稿或者提交成功之后 传入后端删除
  const delIds = useRef<any>([]);

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

    // 删除的id存起来
    tableSelectList.forEach((v: any) => {
      delIds.current.push(v.id);
    });
  }, [dispatch, results, tableSelectList]);

  const delOne = useCallback(
    (id: number) => {
      const data = results.filter((v: any) => v.id !== id);
      dispatch({ type: "login/setGoodsSonList", payload: data });
      console.log("单个删除", id);
      // 删除的id存起来
      delIds.current.push(id);
    },

    [dispatch, results]
  );

  const rowSelection = {
    onChange: (selectedRowKeys: any, selectedRows: any) => {
      setTableSelectList(selectedRows);
    },
  };

  // 点击添加或者编辑

  const addId = useRef<any>(null);

  const addPageFu = useCallback((id?: any) => {
    addId.current = id;
    setAddPage(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={() => addPageFu(item.id)}>
              编辑
            </Button>
            <Popconfirm
              title="确定删除吗?"
              okText="确定"
              cancelText="取消"
              onConfirm={() => delOne(item.id)}
            >
              <Button type="text" danger>
                删除
              </Button>
            </Popconfirm>
          </>
        ),
      },
    ];
  }, [addPageFu, delOne]);

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

  // 点击提交
  const submitFu = useCallback(
    async (val: number) => {
      if (!addInfoTop.sourceName) return MessageFu.warning("请选择藏品来源!");

      if (results.length === 0)
        return MessageFu.warning("至少需要添加一条藏品信息!");
      const obj = {
        ...addInfoTop,
        status: val,
      };
      const res: any = await object1AddAPI(obj);
      if (res.code === 0) {
        // 真正进行删除
        if (delIds.current.length) {
          const res2: any = await delInTablesAPI(delIds.current.join(","));
          if (res2.code === 0) {
            MessageFu.success("操作成功!");
            cancelFu();
          }
        } else {
          MessageFu.success("操作成功!");
          cancelFu();
        }
      }
    },
    [addInfoTop, cancelFu, results.length]
  );

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

  return (
    <div className={styles.AddObject1}>
      <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="row">
            <div>
              <span className="bs">藏品来源：</span>
              <Select
                placeholder="请选择"
                style={{ width: 400 }}
                value={addInfoTop.sourceName}
                onChange={handleChange}
                options={options.map((v: any) => ({
                  label: v.name,
                  value: v.name,
                }))}
              />
            </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: 300 }}
              rowSelection={{
                type: "checkbox",
                ...rowSelection,
              }}
              dataSource={results}
              columns={columns}
              rowKey="id"
              pagination={false}
            />
          </div>
          <div className="addTableBox_btn">
            <Button onClick={() => submitFu(0)}>存入草稿</Button>
            &emsp;
            <Button type="primary" onClick={() => submitFu(1)}>
              提交
            </Button>
            &emsp;
            <Button onClick={cancelFu}>返回</Button>
          </div>
        </div>
      </div>
      {/* 点击添加或者编辑出来的页面 */}
      {addPage ? (
        <ObjectAdd
          id={addId.current}
          colsePage={() => setAddPage(false)}
          dirCode={addInfoTop.id}
        />
      ) : null}
    </div>
  );
}

const MemoAddObject1 = React.memo(AddObject1);

export default MemoAddObject1;
