import React, { FC, useEffect, useState } from "react";
import { exceptStr, paginationFun } from "@/utils/common";
import { defaultPage, ILoading, IPage } from "@/common/types/page";
import { Button, message, Spin, Table, Typography } from "antd";
import { LockOutlined, UnlockOutlined } from "@ant-design/icons";
import API from "@/api";
import styles from "./index.less";

const { Text } = Typography;

interface ITableProps {
}

const AntdTable: FC<ITableProps> = (props) => {
  const [selected, setSelected] = useState<Array<string>>([]); //列表选中的数据
  const [tab, setTab] = useState<string>(""); //顶部TAB变量
  const [usertab, setUsertab] = useState<string>(""); //底部TAB变量
  const [pageParams, setPageParams] = useState<IPage>(defaultPage); //分页变量
  const [loading, setLoading] = useState<ILoading>({});
  const [columns, setColumns] = useState<any[]>([]);
  const [dataSource, setDataSource] = useState<any[]>([]);
  const [i18n, setI18n] = useState<Partial<{}>>({});
  const [sumRow, setSumRow] = useState<Partial<{}>>({});//薪资核算总计行数据
  const [showSumrow, setShowSumrow] = useState<boolean>(false);//薪资核算总计行是否隐藏
  useEffect(() => {
    window.parent.postMessage(
      {
        type: "PC",
        data: { id: "SA" }
      },
      "*"
    );
    window.addEventListener("message", receiveMessageFromIndex, false);
    return () => {
      setSumRow({});
      window.removeEventListener("message", receiveMessageFromIndex, false);
    };
  }, []);

  const getPCDataList = (params: any = {}) => {
    let { type, listType, hasOperate = true, i18n: newI18n, ...extraParams } = params;
    setLoading({ query: true });
    setTab(type);
    setUsertab(listType);
    API.CalculateService.getPCDataList(extraParams).then(async ({ success, data, errorMsg }) => {
      setLoading({ query: false });
      if (success) {
        const { data: dataCopy } = data;
        if (type === "PC") {
          if (listType === "SA") {
            const { columns = [], list = [], total, pageSize: size, pageNum } = dataCopy;
            setColumns(getUserListColumns(columns, newI18n));
            setDataSource(list);
            setPageParams({ ...pageParams, total, size, pageNum });
          } else if (listType === "MA") {
            const { columns = [], list = [], total, pageSize: size, pageNum } = dataCopy;
            setColumns(columns);
            setDataSource(list);
            setPageParams({ ...pageParams, total, size, pageNum });
          }
        } else {
          const { columns = [], pageInfo = {} } = dataCopy;
          const { list = [], total, pageSize: size, pageNum } = pageInfo;
          setColumns(getColumns(columns, hasOperate, newI18n));
          setDataSource(list);
          setPageParams({ ...pageParams, total, size, pageNum });
          const confCode: any = await API.CalculateService.getSysconfcode({ code: "OPEN_ACCT_RESULT_SUM" });
          setShowSumrow(confCode.data.status && confCode.data.data === "1");
          if (confCode.data.status && confCode.data.data === "1") {
            const sumRowlist: any = await API.CalculateService.getAcctresultsum({ ...extraParams["queryParams"] });
            if (sumRowlist.data.status && !_.isEmpty(sumRowlist.data.data.sumRow)) {
              setSumRow(sumRowlist.data.data.sumRow);
            }
            if (sumRowlist.data.status && _.isNil(sumRowlist.data.data.sumRow)) {
              setSumRow({ [new Date().getTime()]: new Date().getTime() });
            }
          }
        }
      } else {
        message.error(errorMsg || "");
      }
    });
  };
  const getUserListColumns = (acctemployeeListColumns: any, newI18n:any) => {
    let tmpColumns = [...acctemployeeListColumns, {
      key: "cz",
      title: newI18n["操作"],
      render: (text: string, record: any) => {
        return (
          <Button type="link" style={{ padding: "0" }}
                  onClick={() => {
                    window.parent.postMessage(
                      {
                        type: "PC",
                        data: { id: "DELETE", data: record }
                      },
                      "*"
                    );
                  }}
          >
            {newI18n["删除"]}
          </Button>
        );
      }
    }];
    tmpColumns = _.map(tmpColumns, (item) => {
      if (item.dataIndex === "costCenter") {
        return {
          ...item,
          ellipsis: true,
          width: 110,
          render: (text: string, r: any) => {
            const { costCenter } = r;
            return (
              <a href="javascript: void(0);" onClick={() => {
                window.parent.postMessage(
                  {
                    type: "PC",
                    data: { id: "COSTCENTER", data: costCenter }
                  },
                  "*"
                );
              }}>{costCenter.name || ""}</a>
            );
          }
        };
      }
      return { ...item, ellipsis: true };
    });
    return tmpColumns;
  };
  //薪资核算页面列表
  const getColumns = (column: any, hasOperate: boolean = true, newI18n: any) => {
    let tmpColumns = [...column];
    tmpColumns = tmpColumns.filter(item => item.hide == "FALSE").map((item, index) => {
      let result = { ...item };
      result.title = <span className={styles.titleWrapper}>
        <span onClick={() => {
          window.parent.postMessage(
            {
              type: "PR",
              data: { id: "COLUMNINDEX", data: item.column }
            },
            "*"
          );
        }}>{item.text}</span>
        {
          item.lockStatus && <span className={styles.titleIcon}>
            {
              item.lockStatus === "UNLOCK" && <LockOutlined
                title={newI18n["点击锁定所有解锁的项目值"]}
                onClick={() => {
                  window.parent.postMessage(
                    {
                      type: "PR",
                      data: { id: "COLUMNINDEX", data: item.column, extraId: "LOCK" }
                    },
                    "*"
                  );
                }}
              />
            }
            {
              item.lockStatus !== "UNLOCK" && <UnlockOutlined
                title={newI18n["点击解锁所有锁定的项目值"]}
                onClick={() => {
                  window.parent.postMessage(
                    {
                      type: "PR",
                      data: { id: "COLUMNINDEX", data: item.column, extraId: "UNLOCK" }
                    },
                    "*"
                  );
                }}
              />
            }
          </span>
        }
      </span>;
      result.dataIndex = item.column;
      result.oldWidth = result.width;
      result.width = "150px";
      result.ellipsis = true;
      result.render = (text: string, r: any) => {
        if (item.column === "costCenter") {
          const { costCenter } = r;
          return <a href="javascript: void(0);" onClick={() => {
            window.parent.postMessage(
              {
                type: "PR",
                data: { id: "COSTCENTER", data: costCenter }
              },
              "*"
            );
          }}>{!_.isEmpty(costCenter) ? costCenter.name : ""}</a>;
        }
        return <span className={styles.contentSpan}>
              <span title={text} className={styles.contentTitle}>{text}</span>
          {
            result.lockStatus === "LOCK" ? <LockOutlined title={newI18n["锁定的项目值"]}/> : null
          }
        </span>;
      };
      if (result.children) {
        result.width = (result.children.length * 150) + "px";
        result.children.map((child: any) => {
          child.title = <span className={styles.titleWrapper}>
            <span title={child.text} onClick={() => {
              window.parent.postMessage(
                {
                  type: "PR",
                  data: { id: "COLUMNINDEX", data: child.column }
                },
                "*"
              );
            }}>{child.text}</span>
            {
              child.lockStatus &&
              <span className={styles.titleIcon}>
                {
                  child.lockStatus === "UNLOCK" &&
                  <LockOutlined
                    title={newI18n["点击锁定所有解锁的项目值"]}
                    onClick={() => {
                      window.parent.postMessage(
                        {
                          type: "PR",
                          data: { id: "COLUMNINDEX", data: child.column, extraId: "LOCK" }
                        },
                        "*"
                      );
                    }}
                  />
                }
                {
                  child.lockStatus !== "UNLOCK" &&
                  <UnlockOutlined
                    title={newI18n["点击解锁所有锁定的项目值"]}
                    onClick={() => {
                      window.parent.postMessage(
                        {
                          type: "PR",
                          data: { id: "COLUMNINDEX", data: child.column, extraId: "UNLOCK" }
                        },
                        "*"
                      );
                    }}
                  />
                }
            </span>
            }
          </span>;
          child.dataIndex = child.column;
          child.width = "150px";
          child.ellipsis = true;
          child.render = (text: string) => {
            return <span className={styles.contentSpan}>
              <span title={text} className={styles.contentTitle}>{text}</span>
              {
                child.lockStatus === "LOCK" ? <LockOutlined title={newI18n["锁定的项目值"]}/> : null
              }
            </span>;
          };
        });
      }

      if (index < 3) {
        result.fixed = "left";
        result.render = (text: string) => {
          return <span title={text}>{text}</span>;
        };
      }

      return result;
    });
    hasOperate && tmpColumns.push({
      title: newI18n["操作"],
      key: "cz",
      width: "100px",
      fixed: "right",
      render: (text: string, record: any) => {
        return <Button type="link" style={{ padding: "0" }} onClick={() => {
          window.parent.postMessage(
            {
              type: "PR",
              data: { id: "EDIT", data: record }
            },
            "*"
          );
        }}>{newI18n["编辑"]}</Button>;
      }
    });
    return tmpColumns;
  };
  const receiveMessageFromIndex = (event: any) => {
    setDataSource([]);
    const data: any = exceptStr(event.data);
    if (!_.isEmpty(data)) {
      const { selectedRowKeys, i18n, ...extraData } = data;
      setI18n(i18n);
      getPCDataList({ ...extraData, ...pageParams, i18n });
      if (selectedRowKeys) setSelected(selectedRowKeys);
    }
  };

  const sizeChange = (pageobj: IPage) => {
  };
  const onChange = (pageobj: IPage) => {
    setPageParams({ ...pageParams, ...pageobj });
    window.parent.postMessage(
      {
        type: tab,
        data: { id: "PAGEINFO", extraId: usertab, data: { ...pageParams, ...pageobj } }
      },
      "*"
    );
  };
  const rowSelection = {
    selectedRowKeys: selected,
    onChange: (selectedRowKeys: Array<any>) => {
      setSelected(selectedRowKeys);
      window.parent.postMessage(
        {
          type: tab,
          data: { id: "BATCHDELETE", extraId: usertab, data: selectedRowKeys }
        },
        "*"
      );
    }
  };
  return <Table
    rowKey="id"
    loading={loading.query}
    className={styles.tableWrapper}
    columns={columns}
    dataSource={dataSource}
    size="small"
    bordered
    // rowSelection={tab === "PC" && usertab === "SA" ? rowSelection : undefined}
    rowSelection={rowSelection}
    pagination={{
      ...paginationFun(pageParams, sizeChange, onChange, i18n),
      size: "default"
    }}
    scroll={{
      x: "calc(700px + 50%)",
      y: tab !== "PR" ? "calc(100vh - 96px)" : !_.isEmpty(sumRow) ? "calc(100vh - 192px)" : "calc(100vh - 156px)"
    }}
    summary={() => {
      if (tab !== "PR" || !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>
            {
              _.isEmpty(sumRow) ? <Spin tip={i18n["加载中"]}/> :
                _.map([{}, ...totalColumns], (item, index) => {
                  if (index === 0) {
                    return <Table.Summary.Cell index={0} align="center"><Text
                      type="danger">{i18n["总计"]}</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 AntdTable;
