import React from "react";
import { inject, observer } from "mobx-react";
import { toJS } from "mobx";
import { WeaDropdown, WeaHelpfulTip, WeaLocaleProvider, WeaTab, WeaTop } from "ecCom";
import { Button, Dropdown, Menu, message } from "antd";
import "./index.less";
import { getQueryString } from "../../../util/url";
import { getSearchs, renderLoading } from "../../../util";
import CustomPaginationTable from "../../../components/customPaginationTable";
import PayrollPartTable from "./payrollPartTable";
import { genPdfBeforeExport, getPayrollIssuanceProgressBar } from "../../../apis/payroll";
import ProgressModal from "../../../components/progressModal";
import PayrollPreviewDialog from "./components/payrollPreviewDialog";

const getLabel = WeaLocaleProvider.getLabel;
const { ButtonSelect } = WeaDropdown;

@inject("payrollStore")
@observer
export default class PayrollGrant extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedRowKeys: [],
      currentId: "",
      selectedKey: "0",
      progressVisible: false,
      progress: 0,
      showFeedbackColumn: false,
      payrollPartModalParams: {
        visible: false,
        title: "工资单发放",
        grantType: "",
        salarySendId: ""
      },
      payrollPreviewDialog: {
        visible: false, title: getLabel(111, "工资单预览"),
        salaryInfoId: "", recipient: ""
      }
    };
    this.pageInfo = { current: 1, pageSize: 10 };
    this.timer = null;
  }

  componentWillMount() {
    const { selectedKey } = this.state;
    let id = getQueryString("id");
    this.setState({
      currentId: id,
      showFeedbackColumn: getQueryString("ackFeedbackStatus") === "1"
    });
    const {
      payrollStore: { getPayrollInfo, getInfoList, getPaySa }
    } = this.props;
    getPayrollInfo(id);
    getInfoList({
      salarySendId: id,
      isGranted: selectedKey !== "0"
    });
    getPaySa();
  }

  // 撤回
  handleWithdraw = (record) => {
    const { payrollStore } = this.props;
    const { currentId, selectedKey } = this.state;
    const { withdrawPayroll, getInfoList } = payrollStore;
    withdrawPayroll({
      ...record,
      salarySendId: currentId
    }).then(() => {
      getInfoList({
        salarySendId: this.state.currentId,
        isGranted: selectedKey !== "0",
        current: this.pageInfo.current,
        pageSize: this.pageInfo.pageSize
      });
      this.handleClose();
    });
  };

  // 发放
  handleGrant = (record) => {
    this.setState({ progress: 0 });
    const { payrollStore } = this.props;
    const { currentId, selectedKey } = this.state;
    const { grantPayroll, getInfoList } = payrollStore;
    grantPayroll({
      ...record,
      salarySendId: currentId
    }).then(() => {
      this.setState({ progressVisible: true });
      if (this.timer) clearInterval(this.timer);
      this.timer = setInterval(() => {
        getPayrollIssuanceProgressBar(currentId).then(({ data, status }) => {
          let progress = data.progress;
          if (progress === 1 && this.timer) {
            clearInterval(this.timer);
            this.timer = null;
            this.setState({
              progressVisible: false,
              progress: 0
            });
            message.success(data.message);
            getInfoList({
              salarySendId: currentId,
              isGranted: selectedKey !== "0",
              current: this.pageInfo.current,
              pageSize: this.pageInfo.pageSize

            });
            this.handleClose();
          } else if (!data.status) {
            clearInterval(this.timer);
            this.timer = null;
            this.setState({
              progressVisible: false,
              progress: 0
            });
            message.error(data.message);
          }
          this.setState({ progress: Number(progress) * 100 });
        });
      }, 1000);
    });
  };

  /*
   * Author: 黎永顺
   * Description:工资单发放
   * Params:
   * Date: 2022/12/2
   */
  sendPayroll = (key) => {
    const { selectedRowKeys, currentId, payrollPartModalParams } = this.state;
    switch (key) {
      case "ALL":
        this.handleGrantAll();
        break;
      case "SELECT":
        if (selectedRowKeys.length === 0) {
          message.warning("未选择发放条目");
          return;
        }
        this.fetchGrantPayRoll({
          ids: selectedRowKeys,
          salarySendId: currentId
        });
        break;
      case "PART":
        this.setState({
          payrollPartModalParams: {
            ...payrollPartModalParams,
            salarySendId: currentId,
            grantType: "grant",
            visible: true
          }
        });
        break;
      default:
        break;
    }
  };
  /*
 * Author: 黎永顺
 * Description:工资单撤回
 * Params:
 * Date: 2022/12/2
 */
  withdrawalPayroll = (key) => {
    const { selectedRowKeys, currentId, payrollPartModalParams } = this.state;
    switch (key) {
      case "withdrawAll":
        this.handleWithdrawAll();
        break;
      case "recallSelected":
        if (selectedRowKeys.length === 0) {
          message.warning("未选择撤回条目");
          return;
        }
        this.fetchWithdrawPayroll({
          ids: selectedRowKeys,
          salarySendId: currentId
        });
        break;
      case "partialWithdrawal":
        this.setState({
          payrollPartModalParams: {
            ...payrollPartModalParams,
            visible: true,
            title: "工资单撤回",
            salarySendId: currentId,
            grantType: "withdraw"
          }
        });
        break;
      default:
        break;
    }
  };
  // 全部发送
  handleGrantAll = () => {
    this.setState({ progress: 0 });
    const { payrollStore } = this.props;
    const { currentId, selectedKey } = this.state;
    const { grantPayroll, getInfoList } = payrollStore;
    grantPayroll({
      ids: [],
      salarySendId: currentId
    }).then(() => {
      this.setState({ progressVisible: true });
      if (this.timer) clearInterval(this.timer);
      this.timer = setInterval(() => {
        getPayrollIssuanceProgressBar(currentId).then(({ data, status }) => {
          let progress = data.progress;
          if (progress === 1 && this.timer) {
            clearInterval(this.timer);
            this.timer = null;
            this.setState({
              progressVisible: false,
              progress: 0
            });
            message.success(data.message);
            getInfoList({
              salarySendId: currentId,
              isGranted: selectedKey !== "0"
            });
          } else if (!data.status) {
            clearInterval(this.timer);
            this.timer = null;
            this.setState({
              progressVisible: false,
              progress: 0
            });
            message.error(data.message);
          }
          this.setState({ progress: Number(progress) * 100 });
        });
      }, 1000);
    });
  };
  // 发放所选
  fetchGrantPayRoll = (payload) => {
    this.setState({ progress: 0 });
    const { selectedKey, currentId } = this.state;
    const { payrollStore: { grantPayroll, getInfoList } } = this.props;
    grantPayroll(payload).then(() => {
      this.setState({ progressVisible: true });
      if (this.timer) clearInterval(this.timer);
      this.timer = setInterval(() => {
        getPayrollIssuanceProgressBar(currentId).then(({ data, status }) => {
          let progress = data.progress;
          if (progress === 1 && this.timer) {
            clearInterval(this.timer);
            this.timer = null;
            this.setState({
              progressVisible: false,
              progress: 0
            });
            message.success(data.message);
            getInfoList({
              salarySendId: currentId,
              isGranted: selectedKey !== "0"
            });
            this.setState({ selectedRowKeys: [] });
          } else if (!data.status) {
            clearInterval(this.timer);
            this.timer = null;
            this.setState({
              progressVisible: false,
              progress: 0
            });
            message.error(data.message);
          }
          this.setState({ progress: Number(progress) * 100 });
        });
      }, 1000);
    });
  };

  // 全部撤回
  handleWithdrawAll() {
    const { payrollStore } = this.props;
    const { currentId, selectedKey } = this.state;
    const { withdrawPayroll, getInfoList } = payrollStore;
    withdrawPayroll({
      ids: [],
      salarySendId: currentId
    }).then(() => {
      getInfoList({
        salarySendId: currentId,
        isGranted: selectedKey !== "0"
      });
    });
  }

  // 撤回所选
  fetchWithdrawPayroll = (payload) => {
    const { payrollStore: { withdrawPayroll, getInfoList } } = this.props;
    const { currentId, selectedKey } = this.state;
    withdrawPayroll(payload).then(() => {
      getInfoList({
        salarySendId: currentId,
        isGranted: selectedKey !== "0"
      });
      this.setState({ selectedRowKeys: [] });
    });
  };

  getColumns = () => {
    const { selectedKey, showFeedbackColumn, payrollPreviewDialog } = this.state;
    const { payrollStore } = this.props;
    const { salaryGrantTableStore: columns, salarySendDetailBaseInfo } = payrollStore;
    return _.map([
      ..._.filter(toJS(columns), it => ((selectedKey === "0" && it.dataIndex !== "billReadStatus" && it.dataIndex !== "billConfirmStatus") || (selectedKey === "1" && !showFeedbackColumn && it.dataIndex !== "billReadStatus" && it.dataIndex !== "billConfirmStatus") || (selectedKey === "1" && showFeedbackColumn))),
      {
        title: "操作",
        key: "",
        dataIndex: "",
        display: true,
        render: (text, record) => {
          if (record.sendStatus === "1") {
            if (salarySendDetailBaseInfo.canSend) {
              return (
                <React.Fragment>
                  <a
                    href="javascript:void(0);" style={{ marginRight: 10 }}
                    onClick={() => this.handleWithdraw({ ids: [record.id] })}>
                    撤回
                  </a>
                  <a href="javascript:void(0);" style={{ marginRight: 10 }}
                     onClick={() => this.setState({
                       payrollPreviewDialog: {
                         ...payrollPreviewDialog,
                         visible: true, salaryInfoId: record.id, recipient: record.employeeId
                       }
                     })}>
                    {getLabel(111, "查看")}
                  </a>
                  {
                    salarySendDetailBaseInfo.showPdfBtn &&
                    <a
                      href="javascript:void(0);"
                      onClick={() => {
                        genPdfBeforeExport({ id: record.id, salarySendId: getQueryString("id") })
                          .then(({ status, errormsg }) => {
                            if (status) {
                              window.open(`${window.ecologyContentPath || ""}/api/bs/hrmsalary/salaryBill/exportPdf?id=${record.id}&salarySendId=${getQueryString("id")}`, "_blank");
                            } else {
                              message.error(errormsg);
                            }
                          });
                      }}>
                      {getLabel(111, "导出PDF")}
                    </a>
                  }
                </React.Fragment>
              );
            } else {
              return (
                <React.Fragment>
                  {
                    salarySendDetailBaseInfo.showPdfBtn &&
                    <a
                      href="javascript:void(0);"
                      onClick={() => {
                        genPdfBeforeExport({ id: record.id, salarySendId: getQueryString("id") })
                          .then(({ status, errormsg }) => {
                            if (status) {
                              window.open(`${window.ecologyContentPath || ""}/api/bs/hrmsalary/salaryBill/exportPdf?id=${record.id}&salarySendId=${getQueryString("id")}`, "_blank");
                            } else {
                              message.error(errormsg);
                            }
                          });
                      }}>
                      {getLabel(111, "导出PDF")}
                    </a>
                  }
                </React.Fragment>
              );
            }
          } else if (salarySendDetailBaseInfo.canSend) {
            return (
              <React.Fragment>
                <a
                  href="javascript:void(0);" style={{ marginRight: 10 }}
                  onClick={() => this.handleGrant({ ids: [record.id] })}>
                  发放
                </a>
                <a href="javascript:void(0);" onClick={() => this.setState({
                  payrollPreviewDialog: {
                    ...payrollPreviewDialog,
                    visible: true, salaryInfoId: record.id, recipient: record.employeeId
                  }
                })}>
                  {getLabel(111, "查看")}
                </a>
              </React.Fragment>
            );
          }
        }
      }
    ], item => {
      if (item.dataIndex === "sendStatus") {
        return {
          ...item,
          render: (text, record) => {
            return <span>{record.sendStatus === "0" ? getLabel(111, "未发放") : record.sendStatus === "1" ? getLabel(111, "已发放") : getLabel(111, "已撤回")}</span>;
          }
        };
      }
      return { ...item };
    });
  };

  getSearchsAdQuick() {
    const { payrollStore } = this.props;
    const { salarySendDetailBaseInfo, btnLoading } = payrollStore;
    const { selectedKey } = this.state;
    const handleMenuClick = e => {
      switch (e.key) {
        case "3":
          this.handleExportAll();
          break;
        case "4":
          this.handleExportSelect();
          break;
        case "5":
          window.open(`${window.ecologyContentPath || ""}/api/bs/hrmsalary/salaryBill/exportPdf?salarySendId=${getQueryString("id")}&id=`, "_blank");
          break;
        default:
          break;
      }
    };
    const menu = (
      <Menu onClick={handleMenuClick}>
        <Menu.Item key="3">全部导出</Menu.Item>
        <Menu.Item key="4">导出选中</Menu.Item>
        {/*{*/}
        {/*  selectedKey === "1" && salarySendDetailBaseInfo.showPdfBtn &&*/}
        {/*  <Menu.Item key="5">{getLabel(111, "导出PDF")}</Menu.Item>*/}
        {/*}*/}
      </Menu>
    );
    let btnDom = [
      <Dropdown.Button overlay={menu}>
        更多
      </Dropdown.Button>
    ];
    if (selectedKey === "0" && salarySendDetailBaseInfo.canSend) {
      btnDom = [
        <ButtonSelect
          datas={[
            { key: "ALL", show: "全部发放", selected: true },
            { key: "SELECT", show: "发放所选", selected: false },
            { key: "PART", show: "部分发放", selected: false }
          ]}
          btnProps={{ loading: btnLoading }}
          btnOnClick={this.sendPayroll}
          menuOnClick={(key) => this.sendPayroll(key)}
        />,
        ...btnDom
      ];
    } else if (selectedKey === "1" && salarySendDetailBaseInfo.canSend) {
      btnDom = [
        <ButtonSelect
          datas={[
            { key: "withdrawAll", show: "全部撤回", selected: true },
            { key: "recallSelected", show: "撤回所选", selected: false },
            { key: "partialWithdrawal", show: "部分撤回", selected: false }
          ]}
          btnProps={{ loading: btnLoading }}
          btnOnClick={this.withdrawalPayroll}
          menuOnClick={(key) => this.withdrawalPayroll(key)}
        />,
        ...btnDom
      ];
    }
    return btnDom;
  }

  handleExportAll = () => {
    const { selectedKey } = this.state;
    const { payrollStore: { exportPayroll } } = this.props;
    exportPayroll({
      salarySendId: this.state.currentId,
      isGranted: selectedKey !== "0"
    });
  };
  handleExportSelect = () => {
    const { selectedRowKeys, currentId, selectedKey } = this.state;
    const { payrollStore: { exportPayroll } } = this.props;
    if (selectedRowKeys.length === 0) {
      message.warning("未选择条目");
      return;
    }
    exportPayroll({
      ids: selectedRowKeys,
      salarySendId: currentId,
      isGranted: selectedKey !== "0"
    });
  };
  // 分页
  handleDataPageChange = (value) => {
    const { payrollStore: { getInfoList } } = this.props;
    const { currentId, selectedKey } = this.state;
    getInfoList({
      salarySendId: currentId,
      isGranted: selectedKey !== "0",
      ...this.pageInfo
    });
  };

  handleShowSizeChange(pageInfo) {
    const { payrollStore: { getInfoList } } = this.props;
    const { currentId, selectedKey } = this.state;
    getInfoList({
      salarySendId: currentId,
      isGranted: selectedKey !== "0",
      ...pageInfo
    });
  }

  handleSearch = () => {
    const { payrollStore: { getInfoList, setGrantListShowSearchAd } } = this.props;
    const { currentId, selectedKey } = this.state;
    setGrantListShowSearchAd(false);
    getInfoList({
      salarySendId: currentId,
      isGranted: selectedKey !== "0",
      ...this.pageInfo,
      current: 1
    });
  };

  onSelectChange = value => {
    this.setState({
      selectedRowKeys: value
    });
  };

  handleClose = () => {
    const { payrollPartModalParams } = this.state;
    this.setState({
      payrollPartModalParams: {
        ...payrollPartModalParams,
        visible: false,
        title: "工资单发放",
        grantType: "",
        salarySendId: ""
      }
    });
  };

  render() {
    const { payrollStore } = this.props;
    const {
      salarySendDetailBaseInfo,
      salaryGrantDataSource,
      grantListShowSearchAd,
      grantListConditionForm,
      grantListCondition,
      setGrantListShowSearchAd,
      salaryGrantPageInfo,
      getInfoList,
      loading
    } = payrollStore;
    const { selectedRowKeys, selectedKey, currentId, payrollPartModalParams, payrollPreviewDialog } = this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange
    };
    const adBtn = [
      // 高级搜索内部按钮
      <Button type="primary" onClick={() => this.handleSearch()}>
        搜索
      </Button>,
      <Button type="ghost" onClick={() => grantListConditionForm.resetForm()}>
        重置
      </Button>,
      <Button type="ghost" onClick={() => setGrantListShowSearchAd(false)}>
        取消
      </Button>
    ];
    const topTab = [
      {
        title: "未发送",
        viewcondition: "0"
      },
      {
        title: "已发送",
        viewcondition: "1"
      }
    ];
    return (
      <div className="payrollGrant_new">
        <WeaTop title="工资单发放" icon={<i className="icon-coms-meeting"/>} iconBgcolor="#F14A2D"
                showDropIcon={true} buttons={this.getSearchsAdQuick()}/>
        <WeaTab
          datas={topTab} keyParam="viewcondition" selectedKey={selectedKey} searchType={["base", "advanced"]}
          onChange={v => this.setState({ selectedKey: v }, () => {
            this.pageInfo = { current: 1, pageSize: 10 };
            getInfoList({ salarySendId: currentId, isGranted: v !== "0" });
          })}
          searchsBasePlaceHolder="请输入姓名" showSearchAd={grantListShowSearchAd} buttonsAd={adBtn}
          setShowSearchAd={bool => setGrantListShowSearchAd(bool)}
          searchsAd={getSearchs(grantListConditionForm, toJS(grantListCondition), 2)}
          onSearch={() => this.handleSearch()}
          onSearchChange={v => grantListConditionForm.updateFields({ username: v })}
          searchsBaseValue={grantListConditionForm.getFormParams().username}
        />
        <div className="titleBar">
          <div className="titleBarLeft">
            <span>
              薪资所属月：{salarySendDetailBaseInfo.salaryMonth}
            </span>
            <WeaHelpfulTip
              style={{ marginLeft: "1rem", marginRight: "1rem" }}
              width={200}
              title={<TitleHelp salarySobCycle={salarySendDetailBaseInfo.salarySobCycle}/>}
              placement="topLeft"
            />
            <span>
              工资单模板：{salarySendDetailBaseInfo.template}
            </span>
          </div>

          <div className="titleBarRight">
            <span>
              已发放：{salarySendDetailBaseInfo.sendNum}/<span
              style={{ color: "red" }}>
                {salarySendDetailBaseInfo.sendTotal}
              </span>
            </span>
          </div>
        </div>
        <div className="tableWrapper">
          {
            !loading ?
              <CustomPaginationTable
                rowKey="id"
                rowSelection={rowSelection}
                dataSource={salaryGrantDataSource}
                columns={this.getColumns()}
                total={salaryGrantPageInfo.total}
                current={salaryGrantPageInfo.pageNum}
                pageSize={this.pageInfo.pageSize}
                onPageChange={value => {
                  this.pageInfo.current = value;
                  this.handleDataPageChange(value);
                }}
                onShowSizeChange={(current, pageSize) => {
                  this.pageInfo = { current, pageSize };
                  this.handleShowSizeChange(this.pageInfo);
                }}
                scroll={{ y: `calc(100vh - 255px)` }}
              /> : renderLoading()
          }
        </div>
        <PayrollPartTable
          {...payrollPartModalParams}
          onCancel={this.handleClose}
          onWithdraw={this.handleWithdraw}
          onGrant={this.handleGrant}
        />
        {
          this.state.progressVisible &&
          <ProgressModal
            title={getLabel(111, "正在发放中,请稍后...")}
            visible={this.state.progressVisible}
            onCancel={() => {
              this.setState({ progressVisible: false, progress: 0 });
              clearInterval(this.timer);
              this.timer = null;
            }}
            progress={this.state.progress}
          />
        }
        {/*工资单预览*/}
        <PayrollPreviewDialog {...payrollPreviewDialog}
                              onCancel={() => this.setState({
                                payrollPreviewDialog: {
                                  ...payrollPreviewDialog,
                                  visible: false
                                }
                              })}/>
      </div>
    );
  }
}

export const TitleHelp = (props) => {
  const { salarySobCycle } = props;
  const { salaryCycle = {}, attendCycle = {} } = salarySobCycle;
  return <div>
    <div>
      <p>薪资周期</p>
      <p>{salaryCycle.fromDate}<span style={{ margin: "0 4px" }}>至</span>{salaryCycle.endDate}</p>
    </div>
    <div>
      <p>税款所属期</p>
      <p>{salarySobCycle.taxCycle}</p>
    </div>
    <div>
      <p>考勤取值周期</p>
      <p>{attendCycle.fromDate}<span style={{ margin: "0 4px" }}>至</span>{attendCycle.endDate}</p>
    </div>
    <div>
      <p>福利台账月份</p>
      <p>{`引用${salarySobCycle.socialSecurityCycle}的福利台账数据`}</p>
    </div>
  </div>;
};
