import React, { FC, useEffect, useState } from "react";
import { exceptStr, paginationFun } from "@/utils/common";
import { defaultPage, ILoading, IPage } from "@/common/types/page";
import { Menu, Popover, Table, Typography } from "antd";
import { MoreOutlined } from "@ant-design/icons";
import styles from "@/pages/atdTable/components/index.less";

const { Text } = Typography;

interface ITableProps {
}

const FileTable: FC<ITableProps> = (props) => {
  const [selected, setSelected] = useState<Array<string>>([]); //列表选中的数据
  const [pageInfo, setPageInfo] = useState<IPage>(defaultPage);
  const [loading, setLoading] = useState<ILoading>({});
  const [columns, setColumns] = useState<any[]>([]);
  const [dataSource, setDataSource] = useState<any[]>([]);
  const [sumRow, setSumRow] = useState<Partial<{}>>({});//薪资核算总计行数据
  useEffect(() => {
    window.parent.postMessage({ type: "init" }, "*");
    window.addEventListener("message", receiveMessageFromIndex, false);
    return () => {
      window.removeEventListener("message", receiveMessageFromIndex, false);
    };
  }, []);

  const receiveMessageFromIndex = (event: any) => {
    const data: any = exceptStr(event.data);
    if (!_.isEmpty(data)) {
      const { columns, dataSource, pageInfo, showOperateBtn, selectedRowKeys, selectedKey } = data;
      const { current: pageNum, pageSize: size, total } = pageInfo;
      setColumns(getColumns(columns, selectedKey, showOperateBtn));
      setDataSource(_.filter(dataSource, it => !!it.id));
      setSelected(selectedRowKeys);
      // @ts-ignore
      setSumRow(_.last(dataSource));
      setPageInfo({ pageNum, size, total });
    }
  };
  const getColumns = (columns: any, selectedKey: string, showOperateBtn: boolean) => {
    let tmpV = _.map(columns.filter((item: any) => item.display === "TRUE"), (item: any, index: number) => {
      return {
        ...item,
        ellipsis: true,
        dataIndex: item.column,
        title: item.text
      };
    });
    return tmpV.length > 0 ? [
      ...tmpV, {
        title: "操作",
        dataIndex: "operate",
        fixed: "right",
        width: 120,
        render: (text: string, record: any) => {
          return (
            record.id ?
              <div className={styles.optWrapper}>
                <a className={styles.mr10}
                   onClick={() => handleEditFile(record)}
                >{(showOperateBtn && selectedKey !== "stop") ? "编辑" : "查看"}</a>
                {
                  showOperateBtn && selectedKey === "pending" &&
                  <Popover
                    overlayClassName={styles.moreIconWrapper}
                    placement="bottomRight"
                    content={<Menu onClick={menu => handleFileMenu(menu, record)}>
                      <Menu.Item key="addMember">增员</Menu.Item>
                      <Menu.Item key="stopSalary">删除待办</Menu.Item>
                    </Menu>} title="">
                    <MoreOutlined/>
                  </Popover>
                }
                {
                  showOperateBtn && selectedKey === "suspend" &&
                  <Popover
                    overlayClassName={styles.moreIconWrapper}
                    placement="bottomRight"
                    content={<Menu onClick={menu => handleSuspendFileMenu(menu, record)}>
                      <Menu.Item key="stayDelToStop">减员</Menu.Item>
                      <Menu.Item key="stopSalary">删除待办</Menu.Item>
                    </Menu>} title="">
                    <MoreOutlined/>
                  </Popover>
                }
                {
                  showOperateBtn && selectedKey === "stop" &&
                  <Popover
                    overlayClassName={styles.moreIconWrapper}
                    placement="bottomRight"
                    content={<Menu onClick={menu => handleStopFileMenu(menu, record)}>
                      <Menu.Item key="stopPaying">取消停缴</Menu.Item>
                    </Menu>} title="">
                    <MoreOutlined/>
                  </Popover>
                }
              </div> :
              <div></div>
          );
        }
      }] : [];
  };
  const handleEditFile = (record: any) => {
    window.parent.postMessage({ type: "turn", payload: { id: "EDIT", params: { ...record } } }, "*");
  };
  const handleFileMenu = ({ key }: any, record: any) => {
    if (key === "addMember") {
      window.parent.postMessage({ type: "turn", payload: { id: "ADDMEMBER", params: { ...record } } }, "*");
    } else {
      window.parent.postMessage({ type: "turn", payload: { id: "STOPSALARY", params: { ...record } } }, "*");
    }
  };
  const handleSuspendFileMenu = ({ key }: any, record: any) => {
    if (key === "stopSalary") {
      window.parent.postMessage({ type: "turn", payload: { id: "STOPSUSPENDSALARY", params: { ...record } } }, "*");
    } else {
      window.parent.postMessage({ type: "turn", payload: { id: "STAYDELTOSTOP", params: { ...record } } }, "*");
    }
  };
  const handleStopFileMenu = ({ key }: any, record: any) => {
    if (key === "stopPaying") {
      window.parent.postMessage({ type: "turn", payload: { id: "STOPPAYING", params: { ...record } } }, "*");
    }
  };
  const sizeChange = (pageobj: IPage) => {
  };
  const onChange = (pageobj: IPage) => {
    setPageInfo({ ...pageInfo, ...pageobj });
    window.parent.postMessage(
      {
        type: "turn",
        payload: { id: "PAGEINFO", params: { ...pageInfo, ...pageobj } }
      },
      "*"
    );
  };
  const rowSelection = {
    selectedRowKeys: selected,
    onChange: (selectedRowKeys: Array<any>) => {
      setSelected(selectedRowKeys);
      window.parent.postMessage(
        {
          type: "turn",
          payload: { id: "ROWSELECT", params: { selectedRowKeys } }
        },
        "*"
      );
    }
  };
  return <Table
    rowKey="baseInfo"
    loading={loading.query}
    className={styles.tableWrapper}
    columns={columns}
    dataSource={dataSource}
    size="small"
    rowSelection={rowSelection}
    pagination={{
      ...paginationFun(pageInfo, sizeChange, onChange),
      size: "default"
    }}
    scroll={{ x: 1200, y: `calc(100vh - 138px)` }}
    summary={() => {
      if (_.isEmpty(columns) || _.isEmpty(sumRow)) return;
      return (
        <Table.Summary fixed>
          <Table.Summary.Row>
            {
              _.map(columns, (item: any, index) => {
                if (index === 0) {
                  return <Table.Summary.Cell key={index} index={0} colSpan={2}><Text
                    type="danger">总计</Text></Table.Summary.Cell>;
                }
                return <Table.Summary.Cell index={index} key={index}>
                  <Text type="danger">{sumRow[item.dataIndex] || "-"}</Text>
                </Table.Summary.Cell>;
              })
            }
          </Table.Summary.Row>
        </Table.Summary>
      );
    }}
  />;
};

export default FileTable;
