/*
 * Author: 黎永顺
 * name: 薪资档案页面-重构
 * Description:
 * Date: 2024/1/8
 */
import React, { Component } from "react";
import { WeaLoadingGlobal, WeaLocaleProvider, WeaReqTop, WeaTab } from "ecCom";
import { message, Modal } from "antd";
import { inject, observer } from "mobx-react";
import { renderDropMenuDatas, renderReqBtns, tabList } from "./config";
import SalaryFileAdvanceSearchPannel from "./components/salaryFileAdvanceSearchPannel";
import SalaryFileImportDialog from "./components/salaryFileImportDialog";
import SalaryFileList from "./components/salaryFileList";
import * as API from "../../apis/payrollFiles";
import { sysinfo } from "../../apis/ruleconfig";
import { convertToUrlString } from "../../util/url";
import LogDialog from "../../components/logViewModal";
import cs from "classnames";
import "./index.less";

const getLabel = WeaLocaleProvider.getLabel;

@inject("payrollFilesStore", "taxAgentStore")
@observer
class SalaryFiles extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedKey: "pending", showSearchAd: false, isQuery: false, showDelSalaryFileBtn: false,
      topTabCount: { PENDING: 0, FIXED: 0, SUSPEND: 0, STOP: 0, EXT: 0 }, showExtEmpsWitch: false,
      salaryFileImpDialog: { visible: false, title: getLabel(24023, "数据导入"), importType: "", isExtEmp: false },
      salaryImportTypes: [], logDialogVisible: false, filterConditions: ""
    };
    this.salaryFileListRef = null;
  }

  async componentDidMount() {
    // salaryArchiveDelete, //待定薪、停薪员工 是否允许删除薪资档案 0： 否， 1： 是，
    // extEmpsWitch //非系统人员开关， 1： 开启， 0：关闭
    const [{ data: salaryFileDelFlag }, { data: { extEmpsWitch } }, { data: salaryImportTypes }] =
      await Promise.all([API.salaryArchiveDelete(), sysinfo(), API.getImportTypes()]);
    this.setState({
      showDelSalaryFileBtn: salaryFileDelFlag === "1", showExtEmpsWitch: extEmpsWitch === "1",
      salaryImportTypes: _.filter(salaryImportTypes, it => it.id !== "taxAgentAdjust")
    });
  }

  handleOpenAdvanceSearch = () => this.setState({ showSearchAd: true });
  handleAdvanceSearch = () => this.setState({ isQuery: !this.state.isQuery });
  onAdSearch = () => this.setState({ showSearchAd: false, isQuery: !this.state.isQuery });
  onDropMenuClick = (key, targetid = "") => {
    const { state, handleSalaryOpts } = this.salaryFileListRef.wrappedInstance || {};
    switch (key) {
      case "log":
        this.setState({
          logDialogVisible: true,
          filterConditions: targetid ? `[{\"connectCondition\":\"AND\",\"columIndex\":\"targetid\",\"type\":\"=\",\"value\":\"${targetid}\"}]` : "[]"
        });
        break;
      case "custom_cols":
        const { payrollFilesStore: { tableStore } } = this.props;
        tableStore.setColSetVisible(true);
        tableStore.tableColSet(true);
        break;
      case "FULL-SALARY-SUSPENSION":
        this.allGotoStop();
        break;
      case "ADD-TO-SALARYPAYMENT":
      case "DEL-PENDITNG-TO-DO":
      case "SALARY-SUSPENSION":
      case "DEL-SUSPEND-TO-DO":
        const { selectedRowKeys = [] } = state;
        if (_.isEmpty(selectedRowKeys)) {
          message.warning(getLabel(543303, "请选择表格数据！"));
          return;
        }
        handleSalaryOpts && handleSalaryOpts(_.camelCase(key), selectedRowKeys);
        break;
      case "exportAll":
      case "exportSelected":
        this.handleExport(key);
        break;
      default:
        break;
    }
  };
  queryInsuranceTabTotal = (active, total, init) => {
    const key = _.find(tabList, o => o.viewcondition === active).groupid;
    if (init) {
      API.queryTabTotal().then(({ status, data }) => {
        if (status) {
          this.setState({
            topTabCount: { ...this.state.topTabCount, ...data, [key]: total }
          });
        }
      });
    } else {
      this.setState({
        topTabCount: { ...this.state.topTabCount, [key]: total }
      });
    }
  };
  handleReqBtnsCLick = (type, importType) => {
    const { state, handleSalaryOpts } = this.salaryFileListRef.wrappedInstance || {};
    switch (type) {
      case "OPEN":
        this.handleOpenAdvanceSearch();
        break;
      case "SEARCH":
        this.handleAdvanceSearch();
        break;
      case "IMPORT":
        this.setState({
          salaryFileImpDialog: {
            ...this.state.salaryFileImpDialog, visible: true,
            importType: importType || _.upperCase(this.state.selectedKey),
            isExtEmp: this.state.selectedKey === "ext"
          }
        });
        break;
      case "ALL-GO-TO-FIXED":
        this.allGotoFixed();
        break;
      case "CANCEL-SALARY-SUSPENSION":
        const { selectedRowKeys = [] } = state;
        if (_.isEmpty(selectedRowKeys)) {
          message.warning(getLabel(543303, "请选择表格数据！"));
          return;
        }
        handleSalaryOpts && handleSalaryOpts(_.camelCase(type), selectedRowKeys);
        break;
      case "ADD-TO-SALARYPAYMENT":
      case "DEL-PENDITNG-TO-DO":
      case "FULL-SALARY-SUSPENSION":
      case "SALARY-SUSPENSION":
      case "DEL-SUSPEND-TO-DO":
        this.onDropMenuClick(type);
        break;
      default:
        break;
    }
  };
  /*
   * Author: 黎永顺
   * Description: 全部设为发薪员工
   * Params:
   * Date: 2024/1/9
   */
  allGotoFixed = () => {
    const { state } = this.salaryFileListRef.wrappedInstance || {};
    const { pageInfo } = state;
    if (pageInfo && pageInfo.total === 0) {
      message.warning(getLabel(543300, "您没有需要处理的待定薪人员！"));
      return;
    }
    Modal.warning({
      title: getLabel(131329, "信息确认"),
      content: `${getLabel(543301, "确定要将所有待定薪人员")}(${getLabel(18609, "共")}${pageInfo.total}${getLabel(30690, "条数据")}）${getLabel(543302, "设为发薪人员吗")}？`,
      onOk: () => {
        WeaLoadingGlobal.start();
        API.allGotoFixed({}).then(({ status, data, errormsg }) => {
          WeaLoadingGlobal.destroy();
          if (status) {
            const { msg } = data;
            message.info(msg || getLabel(30700, "操作成功！"));
            this.handleAdvanceSearch();
          } else {
            message.error(errormsg || getLabel(30651, "操作失败！"));
          }
        });
      }
    });
  };
  /*
   * Author: 黎永顺
   * Description: 全部停薪
   * Params:
   * Date: 2024/1/9
   */
  allGotoStop = () => {
    const { state } = this.salaryFileListRef.wrappedInstance || {};
    const { pageInfo } = state;
    if (pageInfo && pageInfo.total === 0) {
      message.warning(getLabel(543325, "您没有需要处理的待停薪人员！"));
      return;
    }
    Modal.warning({
      title: getLabel(131329, "信息确认"),
      content: `${getLabel(543723, "确定要将所有待停薪人员")}（${getLabel(18609, "共")}${pageInfo.total}${getLabel(30690, "条数据")}）${getLabel(543327, "设为停薪人员吗")}？`,
      onOk: () => {
        WeaLoadingGlobal.start();
        API.allGotoStop({}).then(({ status, data, errormsg }) => {
          WeaLoadingGlobal.destroy();
          if (status) {
            const { msg } = data;
            message.info(msg || getLabel(30700, "操作成功！"));
            this.handleAdvanceSearch();
          } else {
            message.error(errormsg || getLabel(30651, "操作失败！"));
          }
        });
      }
    });
  };
  /*
   * Author: 黎永顺
   * Description: 导出薪资档案文件
   * Params:
   * Date: 2024/1/9
   */
  handleExport = (type) => {
    const { payrollFilesStore: { salaryFileQueryForm } } = this.props;
    const { selectedKey } = this.state;
    let url = `${window.location.origin}/api/bs/hrmsalary/salaryArchive/exportList`;
    let payload = {}, runStatusList = _.upperCase(selectedKey);
    const { state } = this.salaryFileListRef.wrappedInstance || {};
    const { selectedRowKeys = [] } = state;
    switch (selectedKey) {
      case "pending":
      case "suspend":
        runStatusList = _.upperCase(selectedKey);
        break;
      case "fixed":
        runStatusList = "FIXED,SUSPEND";
        break;
      case "stop":
        runStatusList = "STOP_FROM_PENDING,STOP_FROM_SUSPEND";
        break;
      default:
        break;
    }
    if (type === "exportAll") {
      payload = { ids: "", runStatusList, ...salaryFileQueryForm.getFormParams() };
    } else {
      if (selectedRowKeys.length === 0) {
        message.warning(getLabel(543345, "请选择需要导出的数据！"));
        return;
      }
      payload = { ids: selectedRowKeys.join(","), runStatusList };
    }
    window.open(`${url}?${convertToUrlString(payload)}`, "_blank");
  };

  render() {
    const {
      selectedKey, topTabCount, showSearchAd, isQuery, showDelSalaryFileBtn, showExtEmpsWitch,
      salaryFileImpDialog, salaryImportTypes, logDialogVisible, filterConditions
    } = this.state;
    const { taxAgentStore: { showOperateBtn } } = this.props;
    const tabs = _.map(tabList, o => ({ ...o, title: getLabel(o.lanId, o.title) }));
    return (
      <div className="salary-files-wrapper">
        <WeaReqTop
          title={getLabel(538004, "薪资档案")} buttonSpace={10} icon={<i className="icon-coms-fa"/>}
          iconBgcolor="#F14A2D" showDropIcon dropMenuDatas={renderDropMenuDatas(selectedKey, showOperateBtn)}
          onDropMenuClick={this.onDropMenuClick}
          buttons={renderReqBtns(selectedKey, salaryImportTypes, this.handleReqBtnsCLick, showOperateBtn)}
          replaceTab={
            <WeaTab
              datas={!showExtEmpsWitch ? _.dropRight(tabs) : tabs} autoCalculateWidth
              keyParam="viewcondition" selectedKey={selectedKey} counts={topTabCount} countParam="groupid"
              onChange={key => this.setState({ selectedKey: key })}
            />
          }
        >
          <div className="salary-files-content">
            <div
              className={cs("searchAdvanced-condition-container", { "searchAdvanced-condition-hide": !showSearchAd })}>
              <SalaryFileAdvanceSearchPannel
                onCancel={() => this.setState({ showSearchAd: false })}
                onAdSearch={this.onAdSearch}
              />
            </div>
            {/*列表*/}
            <SalaryFileList isQuery={isQuery} ref={dom => this.salaryFileListRef = dom}
                            selectedKey={selectedKey} showOperateBtn={showOperateBtn}
                            showDelSalaryFileBtn={showDelSalaryFileBtn}
                            onChangeTopTabCount={this.queryInsuranceTabTotal}
                            onFilterLog={(type, targetid) => this.onDropMenuClick(type, targetid)}
            />
            {/*操作日志*/}
            <LogDialog visible={logDialogVisible} logFunction="salaryarchive" filterConditions={filterConditions}
                       onCancel={() => this.setState({ logDialogVisible: false })}/>
            {/*  导入*/}
            <SalaryFileImportDialog {...salaryFileImpDialog}
                                    onCancel={(isFresh) => {
                                      this.setState({
                                        isQuery: isFresh ? !isQuery : isQuery,
                                        salaryFileImpDialog: {
                                          ...salaryFileImpDialog, visible: false,
                                          importType: "", isExtEmp: false
                                        }
                                      });
                                    }}/>
          </div>
        </WeaReqTop>
      </div>
    );
  }
}

export default SalaryFiles;
