import React, { FC, useEffect, useState } from "react";
import { Button, Dropdown, Space, Spin, Table, Typography } from "antd";
import { MoreOutlined } from "@ant-design/icons";
import { convertColumns, exceptStr, paginationFun } from "@/utils/common";
import styles from "@/pages/atdTable/components/index.less";
import { defaultPage, IPage } from "@/common/types";
import cs from "classnames";

const { Text } = Typography;
const payrollFilesTable: FC = (props) => {
  const [columns, setColumns] = useState<Array<any>>([]);
  const [sumRow, setSumRow] = useState<any>({});
  const [pageInfo, setPageInfo] = useState<IPage>(defaultPage);
  const [dataSource, setDataSource] = useState<Array<any>>([]);
  const [showSumrow, setShowSumrow] = useState<boolean>(false);
  const [selected, setSelected] = useState<Array<string>>([]);
  const [i18n, setI18n] = 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,
        countResult,
        showSum,
        pageInfo,
        showOperateBtn,
        selectedKey,
        selectedRowKeys,
        salaryArchiveDelete,
        i18n
      } = data;
      const { current: pageNum, pageSize: size, total } = pageInfo;
      setDataSource(dataSource);
      setI18n(i18n);
      setColumns(_.map(columns, item => {
        if (item.dataIndex === "operate") {
          return {
            ...item,
            render: (text: string, r: { id?: string }) => {
              let dom = null;
              if (!showOperateBtn) {
                dom = <Button type="link" style={{ padding: "0" }}
                              onClick={() => window.parent.postMessage(
                                {
                                  type: "turn",
                                  payload: { id: "EDIT", params: { record: r } }
                                },
                                "*"
                              )}
                >
                  {i18n["查看"]}
                </Button>;
              } else {
                if (selectedKey === "pending") {
                  dom = <Space>
                    <Button type="link" style={{ padding: "0" }}
                            onClick={() => window.parent.postMessage(
                              {
                                type: "turn",
                                payload: { id: "EDIT", params: { record: r } }
                              },
                              "*"
                            )}
                    >
                      {i18n["编辑"]}
                    </Button>
                    <Button type="link" style={{ padding: "0" }}
                            onClick={() => handleMenuClick({ key: "payroll" }, r?.id)}
                    >
                      {i18n["设为发薪人员"]}
                    </Button>
                    <Dropdown
                      menu={{
                        items: salaryArchiveDelete === "1" ? [
                          {
                            key: "deletePendingTodo",
                            label: <a onClick={() => handleMenuClick({ key: "deletePendingTodo" }, r?.id)}>
                              {i18n["删除待办"]}
                            </a>
                          },
                          {
                            key: "deleteAchives",
                            label: <a onClick={() => handleMenuClick({ key: "deleteAchives" }, r?.id)}>
                              删除档案
                            </a>
                          }
                        ] : [
                          {
                            key: "deletePendingTodo",
                            label: <a onClick={() => handleMenuClick({ key: "deletePendingTodo" }, r?.id)}>
                              {i18n["删除待办"]}
                            </a>
                          }
                        ]
                      }} placement="bottomRight"
                      overlayClassName={styles.moreIconWrapper}
                    >
                      <MoreOutlined style={{ fontSize: 16 }}/>
                    </Dropdown>
                  </Space>;
                } else if (selectedKey === "fixed") {
                  dom = <Button type="link" style={{ padding: "0" }} onClick={() => window.parent.postMessage(
                    {
                      type: "turn",
                      payload: { id: "EDIT", params: { record: r } }
                    },
                    "*"
                  )}>
                    {i18n["调薪"]}
                  </Button>;
                } else if (selectedKey === "suspend") {
                  dom = <Space>
                    <Button type="link" style={{ padding: "0" }} onClick={() => window.parent.postMessage(
                      {
                        type: "turn",
                        payload: { id: "EDIT", params: { record: r } }
                      },
                      "*"
                    )}>
                      {i18n["编辑"]}
                    </Button>
                    <Button type="link" style={{ padding: "0", fontSize: 12 }}
                            onClick={() => handleMenuClick({ key: "stopSalary" }, r?.id)}
                    >
                      {i18n["停薪"]}
                    </Button>
                    <Dropdown
                      menu={{
                        items: [
                          {
                            key: "deleteSuspendTodo",
                            label: <a onClick={() => handleMenuClick({ key: "deleteSuspendTodo" }, r?.id)}>
                              {i18n["删除待办"]}
                            </a>
                          }
                        ]
                      }} placement="bottomRight"
                      overlayClassName={styles.moreIconWrapper}
                    >
                      <MoreOutlined style={{ fontSize: 16 }}/>
                    </Dropdown>
                  </Space>;
                } else {
                  dom = <Space>
                    <Button type="link" style={{ padding: "0" }} onClick={() => window.parent.postMessage(
                      {
                        type: "turn",
                        payload: { id: "CANCELSTOP", params: { id: r?.id } }
                      },
                      "*"
                    )}>
                      {i18n["取消停薪"]}
                    </Button>
                    <Button type="link" style={{ padding: "0" }}
                            onClick={() => handleMenuClick({ key: "view" }, r as string)}>
                      {i18n["查看"]}
                    </Button>
                    {
                      salaryArchiveDelete === "1" &&
                      <Dropdown placement="bottomRight" overlayClassName={styles.moreIconWrapper}
                                menu={{
                                  items: [
                                    {
                                      key: "deleteAchives",
                                      label: <a onClick={() => handleMenuClick({ key: "deleteAchives" }, r?.id)}>
                                        删除档案
                                      </a>
                                    }
                                  ]
                                }}
                      >
                        <MoreOutlined style={{ fontSize: 16 }}/>
                      </Dropdown>
                    }
                  </Space>;
                }
              }
              return dom;
            }
          };
        }
        return _.omitBy({ ...item }, item => !item);
      }));
      setShowSumrow(showSum);
      setSumRow(_.isEmpty(countResult) ? { [new Date().getTime()]: new Date().getTime() } : countResult);
      setPageInfo({ pageNum, size, total });
      setSelected(selectedRowKeys);
    }
  };
  const handleMenuClick = (event: any, id?: string) => {
    window.parent.postMessage(
      {
        type: "turn",
        payload: { id: "MOREOPT", params: { id, event } }
      },
      "*"
    );
  };
  const sizeChange = (pageobj: IPage) => {
  };
  const onChange = (pageobj: IPage) => {
    setPageInfo({ ...pageInfo, ...pageobj });
    window.parent.postMessage(
      {
        type: "turn",
        payload: { id: "PAGEINFO", params: { ...pageInfo, ...pageobj } }
      },
      "*"
    );
  };

  const rowSelection = {
    columnWidth: 50,
    selectedRowKeys: selected,
    onChange: (selectedRowKeys: Array<any>) => {
      setSelected(selectedRowKeys);
      window.parent.postMessage(
        {
          type: "turn",
          payload: { id: "ROWSELECTION", params: { selectedRowKeys } }
        },
        "*"
      );
    }
  };

  return <Table
    rowKey="id"
    className={cs({
      [styles.tableWrapper]: true,
      [styles.tableTotalWrapper]: true
    })}
    columns={!_.isEmpty(columns) && convertColumns(columns, _.findIndex(columns, ["dataIndex", "operate"]), Object.keys(columns).length)}
    dataSource={dataSource}
    size="small"
    rowSelection={rowSelection}
    scroll={{ x: 1200, y: !showSumrow ? `calc(100vh - 100px)` : "calc(100vh - 129px)" }}
    pagination={{
      ...paginationFun(pageInfo, sizeChange, onChange),
      size: "default"
    }}
    summary={() => {
      if (!showSumrow) return;
      let totalColumns: any[] = [];
      _.forEach(columns, it => {
        if (!it.children) {
          totalColumns.push(it);
        } else {
          totalColumns = [...totalColumns, ...it.children];
        }
      });
      return (
        <Table.Summary fixed>
          <Table.Summary.Row>
            {
              sumRow.loading ? <Spin tip={i18n["加载中"]}/> :
                _.map([{}, ...totalColumns], (item, index) => {
                  if (index === 0) {
                    return <Table.Summary.Cell index={0} key={index} align="center"><Text
                      type="danger">{i18n["总计"]}</Text></Table.Summary.Cell>;
                  }
                  return <Table.Summary.Cell index={index} key={index}>
                    <Text type="danger">{!_.isNil(sumRow[item.dataIndex]) ? sumRow[item.dataIndex] : "-"}</Text>
                  </Table.Summary.Cell>;
                })
            }
          </Table.Summary.Row>
        </Table.Summary>
      );
    }}
  />;
};

export default payrollFilesTable;
