/*
 * Author: 黎永顺
 * name: 社保福利档案页面重构
 * Description:
 * Date: 2023/10/31
 */
import React, { Component } from "react";
import { WeaLoadingGlobal, WeaLocaleProvider, WeaReqTop, WeaTab } from "ecCom";
import { message } from "antd";
import { inject, observer } from "mobx-react";
import WelfareAdvanceSearchPannel from "./components/welfareAdvanceSearchPannel";
import WelfareTableList from "./components/welfareTableList";
import WelfareArchivesImportDialog from "./components/welfareArchivesImportDialog";
import WelfareTip from "./components/welfareTip";
import RecordDialog from "./components/logDialog";
import LogDialog from "../../../components/logViewModal";
import * as API from "../../../apis/welfareArchive";
import { sysinfo } from "../../../apis/ruleconfig";
import { optTypeEnum, renderDropMenuDatas, renderReqBtns, tabList, welfareTipList } from "./config";
import { convertToUrlString } from "../../../util/url";
import cs from "classnames";
import "./index.less";

const getLabel = WeaLocaleProvider.getLabel;
const APILIST = {
  fullStaffIncrease: API.allStayAddToPay,
  fullReduction: API.allStayDelToStop
};

@inject("taxAgentStore")
@observer
class Index extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedKey: "1", showSearchAd: false, isQuery: false, logDialogVisible: false,
      topTabCount: { stayAdd: 0, paying: 0, stayDel: 0, stopPay: 0, ext: 0 },
      welfareImpDialog: { visible: false, title: getLabel(24023, "数据导入"), runStatuses: "" },
      showExtEmpsWitch: false, recordDialogVisible: false, filterConditions: "[]"
    };
  }

  async componentDidMount() {
    // extEmpsWitch //非系统人员开关， 1： 开启， 0：关闭
    const [{ data: { extEmpsWitch } }] = await Promise.all([sysinfo()]);
    this.setState({ showExtEmpsWitch: extEmpsWitch === "1" });
  }

  queryInsuranceTabTotal = (active, total, init) => {
    const key = _.find(tabList, o => o.viewcondition === active).groupid;
    if (init) {
      API.queryInsuranceTabTotal().then(({ status, data }) => {
        if (status) {
          this.setState({
            topTabCount: { ...this.state.topTabCount, ...data, [key]: total }
          });
        }
      });
    } else {
      this.setState({
        topTabCount: { ...this.state.topTabCount, [key]: total }
      });
    }
  };
  handleOpenAdvanceSearch = () => this.setState({ showSearchAd: true });
  handleAdvanceSearch = () => this.setState({ isQuery: !this.state.isQuery });
  handleImport = () => {
    this.setState({
      welfareImpDialog: {
        ...this.state.welfareImpDialog, visible: true,
        runStatuses: this.state.selectedKey
      }
    });
  };
  onDropMenuClick = (key, targetid = "") => {
    switch (key) {
      case "import":
        this.setState({
          welfareImpDialog: {
            ...this.state.welfareImpDialog, visible: true,
            runStatuses: this.state.selectedKey
          }
        });
        break;
      case "fullStaffIncrease":
      case "fullReduction":
        this.handleFullOptions(key);
        break;
      case "batchStaffIncrease":
      case "batchDeleteTodolist":
      case "batchReduction":
      case "batchCancellationOfSuspended":
      case "batchDeleteTodolistStayDel":
        const type = _.find(optTypeEnum, o => o.key === key).type;
        const payload = _.find(optTypeEnum, o => o.key === key).payload;
        this.welfareListRef.wrappedInstance.handleBatchOpt(type, payload);
        break;
      case "exportAll":
      case "exportSelected":
        this.handleExport(key);
        break;
      case "record":
        this.setState({ recordDialogVisible: true });
        break;
      case "log":
        this.setState({
          logDialogVisible: true,
          filterConditions: targetid ? `[{\"connectCondition\":\"AND\",\"columIndex\":\"targetid\",\"type\":\"=\",\"value\":\"${targetid}\"}]` : "[]"
        });
        break;
      default:
        break;
    }
  };
  onAdSearch = () => this.setState({ showSearchAd: false, isQuery: !this.state.isQuery });
  handleFullOptions = (key) => {
    WeaLoadingGlobal.start();
    APILIST[key]().then(({ status, data, errormsg }) => {
      WeaLoadingGlobal.destroy();
      if (status) {
        const { type, msg } = data;
        if (type === "fail") {
          message.error(msg);
        } else {
          message.success(msg);
          this.onAdSearch();
        }
      } else {
        message.error(errormsg);
      }
    }).catch(() => WeaLoadingGlobal.destroy());
  };
  handleExport = (key) => {
    const {
        state: { selectedRowKeys },
        props: { archivesStore: { welfareForm } }
      } = this.welfareListRef.wrappedInstance,
      { selectedKey: runStatuses } = this.state;
    let payload = { runStatuses };
    if (key.indexOf("Selected") !== -1 && _.isEmpty(selectedRowKeys)) {
      message.warning(getLabel(543303, "请选择表格数据"));
      return;
    }
    payload = { ...payload, ids: selectedRowKeys.join(",") };
    key.indexOf("Selected") === -1 && (payload = { ...payload, ids: "", ...welfareForm.getFormParams() });
    window.open(`/api/bs/hrmsalary/scheme/export?${convertToUrlString(payload)}`, "_blank");
  };

  render() {
    const {
      selectedKey, topTabCount, showSearchAd, isQuery, recordDialogVisible,
      logDialogVisible, filterConditions, welfareImpDialog, showExtEmpsWitch
    } = this.state;
    const { taxAgentStore: { showOperateBtn } } = this.props;
    const tipList = _.find(welfareTipList, o => o.viewcondition === selectedKey).list;
    const tabs = _.map(tabList, o => ({ ...o, title: getLabel(o.lanId, o.title) }));
    return (
      <div className="salary-welfare-archive">
        <WeaReqTop
          title={getLabel(538001, "社保福利档案")} buttonSpace={10} icon={<i className="icon-coms-fa"/>}
          iconBgcolor="#F14A2D" showDropIcon onDropMenuClick={this.onDropMenuClick}
          dropMenuDatas={renderDropMenuDatas(selectedKey, getLabel, showOperateBtn)}
          buttons={renderReqBtns(selectedKey, getLabel, this.handleOpenAdvanceSearch, this.handleAdvanceSearch, this.onDropMenuClick, 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-welfare-archive-content">
            <div
              className={cs("searchAdvanced-condition-container", { "searchAdvanced-condition-hide": !showSearchAd })}>
              <WelfareAdvanceSearchPannel
                onCancel={() => this.setState({ showSearchAd: false })}
                onAdSearch={this.onAdSearch}
              />
            </div>
            {/*列表*/}
            <WelfareTableList isQuery={isQuery} ref={dom => this.welfareListRef = dom}
                              runStatuses={selectedKey} showOperateBtn={showOperateBtn}
                              onChangeTopTabCount={this.queryInsuranceTabTotal}
                              onFilterLog={(type, targetid) => this.onDropMenuClick(type, targetid)}
            />
            {/*提示*/}
            {!_.isEmpty(tipList) && <WelfareTip dataSource={tipList}/>}
            {/*基数调整记录*/}
            <RecordDialog visible={recordDialogVisible} onCancel={() => this.setState({ recordDialogVisible: false })}/>
            {/*操作日志*/}
            <LogDialog visible={logDialogVisible} logFunction="siarchives" filterConditions={filterConditions}
                       onCancel={() => this.setState({ logDialogVisible: false })}/>
            {/*  导入*/}
            <WelfareArchivesImportDialog {...welfareImpDialog}
                                         onCancel={(isFresh) => {
                                           this.setState({
                                             isQuery: isFresh ? !isQuery : isQuery,
                                             welfareImpDialog: {
                                               ...this.state.welfareImpDialog, visible: false,
                                               runStatuses: ""
                                             }
                                           });
                                         }}/>
          </div>
        </WeaReqTop>
      </div>
    );
  }
}

export default Index;
