/*
 * Author: 黎永顺
 * name: 工资单发放撤回弹框列表
 * Description:
 * Date: 2022/12/2
 */
import React, { Component } from "react";
import { Button, message, Modal } from "antd";
import { WeaButtonIcon, WeaDialog, WeaInputSearch, WeaTable } from "ecCom";
import { sendRangeDelete, sendRangeList } from "../../../apis/payroll";
import { calcPageNo } from "../../../util";
import PayrollPartModal from "./payrollPartModal";

class PayrollPartTable extends Component {
  constructor(props) {
    super(props);
    this.state = {
      searchValue: "",
      dialogVisible: false,
      loading: {
        query: false
      },
      dataSource: [],
      columns: [],
      selectedRowKeys: [],
      pageInfo: {
        current: 1,
        pageSize: 10,
        total: 0
      }
    };
  }

  componentWillReceiveProps(nextProps, nextContext) {
    if (nextProps.visible !== this.props.visible && nextProps.visible) this.sendRangeList(nextProps);
    if (nextProps.visible !== this.props.visible && !nextProps.visible) this.setState({
      selectedRowKeys: [], pageInfo: { current: 1, pageSize: 10, total: 0 }
    });
  }

  sendRangeList = (props) => {
    const { grantType, salarySendId, pageCurrent = {} } = props;
    const { pageInfo, loading, searchValue: targetName } = this.state;
    const payload = {
      grantType,
      salarySendId,
      targetName,
      ...pageInfo,
      ...pageCurrent
    };
    this.setState({ loading: { ...loading, query: true } });
    sendRangeList(payload).then(({ status, data }) => {
      this.setState({ loading: { ...loading, query: false } });
      if (status) {
        const { pageNum: current, total, columns, list: dataSource } = data;
        this.setState({
          pageInfo: { ...pageInfo, current, total },
          dataSource: _.map(dataSource, it => ({
            ...it,
            includeObj: _.map(it.includeObj, child => child.targetName || child.targetTypeName).join(","),
            excludeObj: _.map(it.excludeObj, child => child.targetName || child.targetTypeName).join(",")
          })),
          columns
        });
      }
    });
  };
  sendRangeDelete = () => {
    const { selectedRowKeys, pageInfo } = this.state;
    const { grantType, salarySendId } = this.props;
    Modal.confirm({
      title: "信息确认",
      content: "确认要删除吗?",
      onOk: () => {
        sendRangeDelete(selectedRowKeys).then(({ status, errormsg }) => {
          if (status) {
            message.success("刪除成功");
            this.setState({ selectedRowKeys: [] }, () => {
              this.sendRangeList({
                grantType, salarySendId,
                pageCurrent: {
                  current: calcPageNo(pageInfo.total, pageInfo.current, 10, selectedRowKeys.length)
                }
              });
            });
          } else {
            message.error(errormsg || "刪除失败");
          }
        });
      },
      onCancel: () => {
      }
    });
  };
  handleOperate = () => {
    const { grantType, salarySendId, onWithdraw, onGrant } = this.props;
    const { selectedRowKeys } = this.state;
    if (_.isEmpty(selectedRowKeys)) {
      message.warning("您没有需要处理的对象！");
      return;
    }
    Modal.confirm({
      title: "信息确认",
      content: `您共选择${selectedRowKeys.length}个对象，确定要${grantType === "grant" ? "发放" : "撤回"}吗？`,
      onCancel: () => {
      },
      onOk: () => {
        if (grantType === "grant") {
          onGrant({ ids: [salarySendId], salarySendRangeIds: selectedRowKeys });
        } else if (grantType === "withdraw") {
          onWithdraw({ ids: [salarySendId], salarySendRangeIds: selectedRowKeys });
        }
      }
    });
  };

  render() {
    const { dataSource, columns, pageInfo, loading, selectedRowKeys, dialogVisible, searchValue } = this.state;
    const { onCancel, visible, grantType, salarySendId, title } = this.props;
    const pagination = {
      ...pageInfo,
      showTotal: total => `共 ${total} 条`,
      showQuickJumper: true,
      pageSizeOptions: ["10", "20", "50", "100"],
      onChange: current => {
        this.setState({
          pageInfo: { ...pageInfo, current }
        }, () => this.sendRangeList({ grantType, salarySendId }));
      }
    };
    const rowSelection = {
      selectedRowKeys,
      onChange: (selectedRowKeys) => this.setState({ selectedRowKeys })
    };
    return (
      <WeaDialog
        initLoadCss
        className="payrollPartTableModalWrapper"
        onCancel={() => this.setState({ selectedRowKeys: [] }, () => onCancel())}
        title={
          <RenderTitle
            title={title}
            selectedRowKeys={selectedRowKeys}
            onAdd={() => this.setState({ dialogVisible: true })}
            onDelete={this.sendRangeDelete}
            onSave={this.handleOperate}
          />
        }
        visible={visible}
        style={{ width: 700, height: 600 }}
        hasScroll
      >
        <div style={{ display: "flex", justifyContent: "flex-end", margin: "10px 10px 10px 0" }}>
          <WeaInputSearch
            style={{ width: 220 }}
            searchValue={searchValue}
            onChange={(searchValue) => this.setState({ searchValue })}
            onSearch={() => this.sendRangeList({ grantType, salarySendId })}
            placeholder="请输入方案名称"
          />
        </div>
        <WeaTable
          rowKey="id"
          rowSelection={rowSelection}
          dataSource={dataSource}
          pagination={pagination}
          loading={loading.query}
          columns={columns}
        />
        <PayrollPartModal
          grantType={grantType}
          salarySendId={salarySendId}
          visible={dialogVisible}
          onCancel={() => this.setState({ dialogVisible: false }, () => {
            this.sendRangeList({ grantType, salarySendId });
          })}
        />
      </WeaDialog>
    );
  }
}

export default PayrollPartTable;

const RenderTitle = (props) => {
  const { title, selectedRowKeys, onAdd, onDelete, onSave } = props;
  return <div className="titleWrapper">
    <div>{title}</div>
    <div className="rightBtnlist">
      <Button type="primary" onClick={onSave}>{title.slice(-2)}</Button>
      <WeaButtonIcon
        buttonType="del"
        type="primary"
        disabled={_.isEmpty(selectedRowKeys)}
        onClick={onDelete}
      />
      <WeaButtonIcon buttonType="add" type="primary" onClick={onAdd}/>
    </div>
  </div>;
};
