/*
 * Author: 黎永顺
 * name: 工资单发放-重构页面
 * Description:
 * Date: 2023/10/12
 */
import React, { Component } from "react";
import { inject, observer } from "mobx-react";
import { WeaLocaleProvider, WeaReqTop } from "ecCom";
import GrantQuery from "./components/reqQuery/grantQuery";
import TemplateQuery from "./components/reqQuery/templateQuery";
import GrantTableList from "./components/grantTableList";
import PayrollTemplateTableList from "./components/payrollTemplateTableList";
import TemplateBaseSettings from "../payroll/templateBaseSettings";
import LogDialog from "../../components/logViewModal";
import * as API from "../../apis/payroll";
import { Button, Dropdown, Icon, Menu, message } from "antd";
import moment from "moment";
import "./index.less";

const getLabel = WeaLocaleProvider.getLabel;

@inject("taxAgentStore")
@observer
class Index extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedKey: "grant", isRefresh: false, baseSetSaveLoading: false, selectedRowKeys: [],
      queryParams: {
        salarySobId: "", name: "",
        dateRange: [
          moment(new Date()).subtract(1, "year").startOf("year").format("YYYY-MM"),
          moment(new Date()).endOf("year").format("YYYY-MM")
        ]
      }, logDialogVisible: false, filterConditions: "[]"
    };
    this.templateRef = null;
    this.baseSetRef = null;
  }

  renderReqBtns = () => {
    const { taxAgentStore: { showOperateBtn } } = this.props;
    const { selectedKey, isRefresh, queryParams } = this.state;
    const menu = (
      <Menu onClick={({ key }) => this.onDropMenuClick(key)}>
        <Menu.Item key="batWithdrawn"
                   disabled={_.isEmpty(this.state.selectedRowKeys)}>{getLabel(111, "全部撤回")}</Menu.Item>
      </Menu>
    );
    let reqBtns = [];
    switch (selectedKey) {
      case "grant":
        reqBtns = [
          <React.Fragment>
            <Button type="primary" onClick={() => this.onDropMenuClick("batDistributed")} className="cust-dropdown-btn"
                    disabled={_.isEmpty(this.state.selectedRowKeys)}>{getLabel(111, "全部发放")}</Button>
            <Dropdown overlay={menu}>
              <Button type="primary" disabled={_.isEmpty(this.state.selectedRowKeys)} className="cust-dropdown-btnIcon"><Icon
                type="down"/></Button>
            </Dropdown>
          </React.Fragment>,
          <GrantQuery queryParams={queryParams}
                      onChange={v => this.setState({
                        isRefresh: !isRefresh,
                        queryParams: { ...queryParams, ...v }
                      })}/>
        ];
        !showOperateBtn && reqBtns.slice(1);
        break;
      case "template":
        const loading = this.templateRef ? this.templateRef.wrappedInstance.state.delLoading : false;
        const delDisabled = !this.templateRef || _.isEmpty(this.templateRef.wrappedInstance.state.selectedRowKeys);
        const btns = [
          <Button type="primary" onClick={() => {
            this.templateRef.wrappedInstance.handleOpts({ key: "edit" }, {});
          }}>{getLabel(365, "新建")}</Button>,
          <Button type="ghost" loading={loading} disabled={delDisabled} onClick={() => {
            this.templateRef.wrappedInstance.handleOpts({ key: "del" }, {});
          }}>{getLabel(32136, "批量删除")}</Button>
        ];
        const queryBtns = [
          <TemplateQuery queryParams={queryParams} onSearch={() => this.setState({ isRefresh: !isRefresh })}
                         onChange={v => this.setState({
                           isRefresh: _.keys(v)[0] === "name" ? isRefresh : !isRefresh,
                           queryParams: { ...queryParams, ...v }
                         })}/>
        ];
        reqBtns = showOperateBtn ? [...btns, ...queryBtns] : [...queryBtns];
        break;
      case "watermark":
        const { baseSetSaveLoading } = this.state;
        reqBtns = [
          <Button type="primary" loading={baseSetSaveLoading}
                  onClick={() => this.baseSetRef.salaryBillBaseSetSave()}>{getLabel(537558, "保存")}</Button>
        ];
        break;
      default:
        break;
    }
    return reqBtns;
  };
  renderContent = () => {
    const { selectedKey, queryParams, isRefresh, selectedRowKeys } = this.state;
    let dom = null;
    switch (selectedKey) {
      case "grant":
        dom = <GrantTableList queryParams={queryParams} isRefresh={isRefresh} selectedRowKeys={selectedRowKeys}
                              onUpdateTemp={(id) => this.setState({ selectedKey: "template" }, () => {
                                this.templateRef.wrappedInstance.handleOpts({ key: "edit" }, { id });
                              })}
                              onChangeSelectedRowKeys={v => this.setState({ selectedRowKeys: v })}
                              onFilterLog={(type, targetid) => this.onDropMenuClick(type, targetid)}/>;
        break;
      case "template":
        dom = <PayrollTemplateTableList ref={dom => this.templateRef = dom} queryParams={queryParams}
                                        isRefresh={isRefresh} forceUpdate={() => this.forceUpdate()}
                                        onFilterLog={(type, targetid) => this.onDropMenuClick(type, targetid)}/>;
        break;
      case "watermark":
        dom = <TemplateBaseSettings
          ref={dom => this.baseSetRef = dom}
          onChangeLoading={loading => this.setState({ baseSetSaveLoading: loading })}
        />;
        break;
      default:
        break;
    }
    return dom;
  };
  onDropMenuClick = (key, targetid = "") => {
    switch (key) {
      case "batDistributed":
        API.batGrantPayroll({ ids: [], salarySendIds: this.state.selectedRowKeys })
          .then(({ status, errormsg }) => {
            if (status) {
              message.success(getLabel(111, "操作成功！"));
              this.setState({ isRefresh: !this.state.isRefresh });
            } else {
              message.error(errormsg);
            }
          });
        break;
      case "batWithdrawn":
        API.batWithdrawPayroll({ ids: [], salarySendIds: this.state.selectedRowKeys })
          .then(({ status, errormsg }) => {
            if (status) {
              message.success(getLabel(111, "操作成功！"));
              this.setState({ isRefresh: !this.state.isRefresh });
            } else {
              message.error(errormsg);
            }
          });
        break;
      case "log":
        this.setState({
          logDialogVisible: true,
          filterConditions: targetid ? `[{\"connectCondition\":\"AND\",\"columIndex\":\"targetid\",\"type\":\"=\",\"value\":\"${targetid}\"}]` : "[]"
        });
        break;
      default:
        break;
    }
  };

  render() {
    const { selectedKey, queryParams, logDialogVisible, filterConditions } = this.state;
    const tabs = [
      { key: "grant", title: getLabel(538012, "工资单发放") },
      { key: "template", title: getLabel(543575, "工资单模板设置") },
      { key: "watermark", title: getLabel(545285, "工资单基础设置") }
    ];
    return (
      <div className="salary-payroll-main-page">
        <WeaReqTop
          title={getLabel(538012, "工资单发放")} tabDatas={tabs} selectedKey={selectedKey}
          buttonSpace={10} icon={<i className="icon-coms-fa"/>} iconBgcolor="#F14A2D"
          onChange={key => this.setState({
            selectedKey: key,
            queryParams: { ...queryParams, name: "", salarySobId: "" }
          })}
          buttons={this.renderReqBtns()} showDropIcon={selectedKey !== "watermark"}
          onDropMenuClick={this.onDropMenuClick}
          dropMenuDatas={[
            {
              key: "log", icon: <i className="iconfont icon-caozuorizhi32"/>,
              content: getLabel(545781, "操作日志")
            }
          ]}
        >
          <div className="salary-payroll-content">{this.renderContent()}</div>
          {/*操作日志*/}
          <LogDialog visible={logDialogVisible} logFunction={selectedKey === "grant" ? "salarysend" : "salarytemplate"}
                     onCancel={() => this.setState({ logDialogVisible: false })} filterConditions={filterConditions}/>
        </WeaReqTop>
      </div>
    );
  }
}

export default Index;
