import React from "react";
import { inject, observer } from "mobx-react";
import { toJS } from "mobx";
import { Button, Dropdown, Menu, message, Modal, Popover } from "antd";
import { WeaCheckbox, WeaHelpfulTip, WeaLocaleProvider, WeaNewScroll, WeaSlideModal, WeaTab, WeaTop } from "ecCom";
import { getSearchs, renderLoading } from "../../../util";
import BaseForm from "./baseForm";
import SlideModalTitle from "../../../components/slideModalTitle";
import SocialSecurityForm from "./socialSecurityForm";
import AccumulationFundForm from "./accumulationFundForm";
import OtherForm from "./otherForm";
import { tabCondition } from "./config";
import * as API from "../../../apis/welfareArchive";
import ImportModal from "../../../components/importModal";
import TipLabel from "../../../components/TipLabel";
import UnifiedTable from "../../../components/UnifiedTable";
import { convertToUrlString, getURLParameters } from "../../../util/url";
import { salaryArchiveDelete } from "../../../apis/payrollFiles";
import ImportDialog from "../../../components/importDialog";
import OperateLogDialog from "../welfareArchive/components/logDialog";
import "./index.less";
import { sysinfo } from "../../../apis/ruleconfig";

const getLabel = WeaLocaleProvider.getLabel;
const APILIST = {
  runStatuses: API["queryList"],
  extWelArchiveList: API["getExtTable"]
};
@inject("archivesStore", "taxAgentStore")
@observer
export default class Archives extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: "",
      selectedKey: "pending",
      selectedTab: 0,
      editSlideVisible: false,
      employeeId: "",
      importVisible: false,
      runStatus: "1",//导入的tab状态
      modalParam: {},
      step: 0,
      selectedRowKeys: [],
      dataSource: [],
      columns: [],
      loading: {
        query: false,
        add: false,
        update: false
      },
      tabCount: {
        stayAdd: 0,
        paying: 0,
        stayDel: 0,
        stopPay: 0,
        ext: 0
      },
      pageInfo: {
        current: 1,
        pageSize: 10,
        total: 0
      },
      salaryArchiveDelete: "", //待定薪、停薪员工 是否允许删除薪资档案 0： 否， 1： 是
      importDialog: {
        visible: false, title: "", nextloading: false,
        link: "", importResult: {}, imageId: "",
        previewUrl: "/api/bs/hrmsalary/scheme/preview"
      },
      extEmpsWitch: "1", //非系统人员开关， 1： 开启， 0：关闭
      logDialog: { visible: false }
    };
    this.record = {};
  }

  componentDidMount() {
    const { archivesStore: { doInit } } = this.props;
    doInit();
    this.salaryArchiveDelete();
    this.getSysinfo();
    this.queryList({ runStatuses: ["1"] });
  }

  /*
     * Author: 黎永顺
     * Description: 非系统人员开关查询
     * Params:
     * Date: 2023/7/14
     */
  getSysinfo = () => {
    sysinfo().then(({ status, data }) => {
      if (status) this.setState({ extEmpsWitch: data.extEmpsWitch });
    });
  };
  queryInsuranceTabTotal = () => {
    API.queryInsuranceTabTotal().then(({ data = {}, status }) => {
      if (status) {
        this.setState({ tabCount: { ...this.state.tabCount, ...data } });
      }
    });
  };
  queryList = (params) => {
    const { loading, pageInfo } = this.state;
    const { archivesStore: { form } } = this.props;
    const formParams = form.getFormParams() || {};
    const payload = { ...pageInfo };
    this.setState({ loading: { ...loading, query: true } });
    APILIST[_.keys(params)[0]]({ ...formParams, ...payload, ...params }).then(({ data, status }) => {
      this.setState({ loading: { ...loading, query: false } });
      if (status) {
        const { pageInfo: paganition, columns, datas: dataSource } = data;
        const { total, pageNum: current, pageSize } = paganition;
        this.setState({
          dataSource: _.map(dataSource, it => ({ ...it, id: it.employeeId })),
          columns,
          pageInfo: {
            ...pageInfo,
            total,
            current,
            pageSize
          }
        });
        this.queryInsuranceTabTotal();
      }
    });
  };
  salaryArchiveDelete = () => {
    salaryArchiveDelete().then(({ status, data }) => {
      if (status) {
        this.setState({
          salaryArchiveDelete: data
        });
      }
    });
  };

  handleEdit = (record) => {
    this.record = record;
    this.setState({ employeeId: record.employeeId, editSlideVisible: true });
  };

  setStep = (step) => {
    this.setState({ step });
  };

  getColumns = () => {
    const { columns, salaryArchiveDelete, selectedKey } = this.state;
    const { taxAgentStore: { showOperateBtn } } = this.props;
    let tmpV = _.map(columns.filter(item => item.display === "TRUE"), item => {
      return {
        ...item,
        dataIndex: item.column,
        title: item.text,
        render: (text) => {
          return <span className="ellipsis" title={text}>{text}</span>;
        }
      };
    });
    return tmpV.length > 0 ? [
      ...tmpV, {
        title: "操作",
        width: 150,
        dataIndex: "operate",
        render: (text, record) => {
          return (
            <div className="optWrapper">
              <a href="javascript:void(0);" className="mr10"
                 onClick={() => this.handleEdit(record)}>{(showOperateBtn && selectedKey !== "stop") ? "编辑" : "查看"}</a>
              {
                showOperateBtn && selectedKey === "pending" &&
                <a href="javascript:void(0);" className="mr10"
                   onClick={() => this.stayAddToPay([record.baseInfo])}>增员</a>
              }
              {
                showOperateBtn && selectedKey === "suspend" &&
                <a href="javascript:void(0);" className="mr10"
                   onClick={() => this.stayDelToStop([record.baseInfo])}>减员</a>
              }
              {
                showOperateBtn && selectedKey === "stop" && salaryArchiveDelete === "1" &&
                <a href="javascript:void(0);" className="mr10"
                   onClick={() => this.deleteSocialArchive([record.baseInfo])}>删除档案</a>
              }
              {
                showOperateBtn && selectedKey === "stop" && salaryArchiveDelete !== "1" &&
                <a href="javascript:void(0);"
                   onClick={() => this.cancelStopPayment([record.baseInfo])}>取消停缴</a>
              }
              {
                showOperateBtn && selectedKey === "pending" &&
                <Popover
                  overlayClassName="moreIconWrapper"
                  placement="bottomRight"
                  content={
                    salaryArchiveDelete === "1" ?
                      <Menu onClick={({ key }) => {
                        if (key === "deleteAchives") {
                          this.deleteSocialArchive([record.baseInfo]);
                        } else {
                          Modal.warning({
                            title: "信息确认",
                            content: `确定要删除该条待办人员吗？`,
                            onOk: () => this.deleteTodoList({ runStatus: "4", ids: [record.baseInfo] })
                          });
                        }
                      }}>
                        <Menu.Item key="deleteAchives">删除档案</Menu.Item>
                        <Menu.Item key="stopSalary">删除待办</Menu.Item>
                      </Menu> :
                      <Menu onClick={({ key }) => {
                        if (key === "deleteAchives") {
                          this.deleteSocialArchive([record.baseInfo]);
                        } else {
                          Modal.warning({
                            title: "信息确认",
                            content: `确定要删除该条待办人员吗？`,
                            onOk: () => this.deleteTodoList({ runStatus: "4", ids: [record.baseInfo] })
                          });
                        }
                      }}>
                        <Menu.Item key="stopSalary">删除待办</Menu.Item>
                      </Menu>
                  } title="">
                  <i className="icon-coms-more"/>
                </Popover>
              }
              {
                showOperateBtn && selectedKey === "suspend" &&
                <Popover
                  overlayClassName="moreIconWrapper"
                  placement="bottomRight"
                  content={<Menu onClick={({ key }) => {
                    if (key === "stopSalary") {
                      Modal.confirm({
                        title: "信息确认",
                        content: `确定要删除该条待办人员吗？`,
                        onOk: () => this.cancelStayDel({ runStatus: "3", ids: [record.baseInfo] })
                      });
                    }
                  }}>
                    <Menu.Item key="stopSalary">删除待办</Menu.Item>
                  </Menu>} title="">
                  <i className="icon-coms-more"/>
                </Popover>
              }
              {
                showOperateBtn && selectedKey === "stop" && salaryArchiveDelete === "1" &&
                <Popover
                  overlayClassName="moreIconWrapper"
                  placement="bottomRight"
                  content={<Menu onClick={({ key }) => {
                    if (key === "stopPaying") this.cancelStopPayment([record.baseInfo]);
                  }}>
                    <Menu.Item key="stopPaying">取消停缴</Menu.Item>
                  </Menu>} title="">
                  <i className="icon-coms-more"/>
                </Popover>
              }
            </div>
          );
        }
      }] : [];
  };

  // 保存
  handleEditSlideSave = () => {
    if (!this.handleSave) {
      this.handleSave = _.debounce(() => {
        const { selectedTab } = this.state;
        const { archivesStore: { save, socialSecurityForm, accumulationFundForm, otherForm } } = this.props;
        if (selectedTab == 1) {
          const { data } = socialSecurityForm;
          const { socialSchemeId, socialStartTime } = data;
          if (socialSchemeId && !socialStartTime) {
            Modal.warning({
              title: "信息确认",
              content: "必要信息不完整，红色*为必填项！"
            });
            return;
          }
          save("SOCIAL_SECURITY", this.record.paymentOrganization).then(() => {
            this.query();
          });
        } else if (selectedTab == 2) {
          const { data } = accumulationFundForm;
          const { fundSchemeId, fundStartTime } = data;
          if (fundSchemeId && !fundStartTime) {
            Modal.warning({
              title: "信息确认",
              content: "必要信息不完整，红色*为必填项！"
            });
            return;
          }
          save("ACCUMULATION_FUND", this.record.paymentOrganization).then(() => {
            this.query();
          });
        } else if (selectedTab == 3) {
          const { data } = otherForm;
          const { otherSchemeId, otherStartTime } = data;
          if (otherSchemeId && !otherStartTime) {
            Modal.warning({
              title: "信息确认",
              content: "必要信息不完整，红色*为必填项！"
            });
            return;
          }
          save("OTHER", this.record.paymentOrganization).then(() => {
            this.query();
          });
        }
      }, 500);
    }
    this.handleSave();
  };

  // 导入
  handleBtnImport = (runStatus) => {
    this.setState({ importVisible: true, runStatus });
  };

  // 模板点击
  handleTemplateLinkClick = (exportData) => {
    const { archivesStore: { form } } = this.props;
    const formParams = form.getFormParams() || {};
    const { selectedKey } = this.state;
    let url = `/api/bs/hrmsalary/scheme/template/export?exportData=${exportData}&runStatuses=${selectedKey === "pending" ? "1" : "2,3"}&${convertToUrlString(formParams)}`;
    window.open(`${window.location.origin}${url}`);
  };

  // 导入预览
  handlePreviewImport = (params) => {
    const { archivesStore: { previewCurData } } = this.props;
    previewCurData(params);
  };

  // 导入
  handleImport = (params) => {
    const { archivesStore: { importBatch } } = this.props;
    const { runStatus, importDialog } = this.state;
    this.setState(({
      importDialog: {
        ...importDialog, nextloading: true, ...params
      }
    }));
    importBatch({ ...params, runStatus }).then(({ status, data }) => {
      this.setState(({
        importDialog: {
          ...importDialog, nextloading: false, importResult: data, ...params
        }
      }));
    });
  };

  // 导入完成
  handleFinish = () => {
    const { archivesStore: { initImportParams } } = this.props;
    initImportParams();
    this.setState({ importVisible: false, step: 0 }, () => {
      this.query();
    });
  };

  // 初始化导入参数
  handleInitModal = () => {
    const { archivesStore: { setPreviewCurDataColumns, setPreviewCurDataDataSource, setImportResult } } = this.props;
    setPreviewCurDataColumns([]);
    setPreviewCurDataDataSource([]);
    setImportResult({});
  };

  // 选项设置
  onSelectChange = selectedRowKeys => {
    this.setState({ selectedRowKeys });
  };

  // 关闭导入框
  handleImportCancel = () => {
    const { archivesStore: { initImportParams, getTableDatas } } = this.props;

    initImportParams();
    if (this.state.step == 2) {
      getTableDatas();
    }
    this.setState({ importVisible: false, step: 0 });
  };

  //切换tab
  handleChangeTab = (selectedKey) => {
    const { pageInfo } = this.state;
    this.setState({
      selectedKey,
      selectedRowKeys: [],
      editSlideVisible: false,
      pageInfo: {
        ...pageInfo,
        current: 1,
        pageSize: 10
      }
    }, () => {
      this.query();
    });
  };

  query = () => {
    const { selectedKey } = this.state;
    switch (selectedKey) {
      case "pending":
        this.queryList({ runStatuses: ["1"] });
        break;
      case "fixed":
        this.queryList({ runStatuses: ["2", "3"] });
        break;
      case "suspend":
        this.queryList({ runStatuses: ["3"] });
        break;
      case "stop":
        this.queryList({ runStatuses: ["4", "5"] });
        break;
      default:
        this.queryList({ extWelArchiveList: true });
        break;
    }
  };
  handleMenuBtnClick = () => {
    const { selectedKey } = this.state;
    if (selectedKey === "pending") {
      // 带增员----全量增员
      API.allStayAddToPay().then(({ status, data, errormsg }) => {
        if (status) {
          const { msg, type } = data;
          if (type === "fail") {
            message.error(msg || "操作失败");
          } else if (type === "success") {
            message.success(msg || "操作成功!");
            this.query();
          }
        } else {
          message.error(errormsg || "操作失败!");
        }
      });
    } else if (selectedKey === "suspend") {
      // 带减员----全量减员
      API.allStayDelToStop().then(({ status, data, errormsg }) => {
        if (status) {
          const { msg, type } = data;
          if (type === "fail") {
            message.error(msg || "操作失败");
          } else if (type === "success") {
            message.success(msg || "操作成功!");
            this.query();
          }
        } else {
          message.error(errormsg || "操作失败!");
        }
      });
    }
  };
  handleMenuItemClick = ({ key }) => {
    const { selectedRowKeys, selectedKey } = this.state;
    if (selectedRowKeys.length === 0) {
      message.warning("未选择任何条目", 1);
      return;
    }
    switch (selectedKey) {
      case "pending":
        if (key === "4") {
          const payload = {
            runStatus: key,
            ids: selectedRowKeys
          };
          this.deleteTodoList(payload);
        } else {
          this.stayAddToPay(selectedRowKeys);
        }
        break;
      case "suspend":
        if (key === "1") {
          this.stayDelToStop(selectedRowKeys);
        } else if (key === "2") {
          this.cancelStayDel({ runStatus: "3", ids: selectedRowKeys });
        }
        break;
      default:
        break;
    }
  };
  //增员
  stayAddToPay = (payload) => {
    API.stayAddToPay(payload).then(({ status, data, errormsg }) => {
      if (status) {
        const { msg, type } = data;
        if (type === "fail") {
          message.error(msg || "操作失败");
        } else if (type === "success") {
          message.success(msg || "操作成功");
          this.query();
          this.onSelectChange([]);
        }
      } else {
        message.error(errormsg || "操作失败");
      }
    });
  };
  //减员
  stayDelToStop = (payload) => {
    API.stayDelToStop(payload).then(({ status, data, errormsg }) => {
      if (status) {
        const { msg, type } = data;
        if (type === "fail") {
          message.error(msg || "操作失败");
        } else if (type === "success") {
          message.success(msg || "操作成功");
          this.query();
          this.onSelectChange([]);
        }
      } else {
        message.error(errormsg || "操作失败");
      }
    });
  };
  //删除社保档案
  deleteSocialArchive = (params) => {
    Modal.confirm({
      title: getLabel(131329, "信息确认"),
      content: getLabel(388758, "确认要删除吗?"),
      onOk: () => {
        API.deleteArchive(params).then(({ status, errormsg }) => {
          if (status) {
            message.success(getLabel(30700, "操作成功"));
            this.query();
          } else {
            message.error(errormsg || getLabel(30651, "操作失败"));
          }
        });
      }
    });
  };
  //取消停缴
  cancelStopPayment = (payload) => {
    API.cancelStopPayment(payload).then(({ status, errormsg }) => {
      if (status) {
        message.success("操作成功");
        this.query();
        this.onSelectChange([]);
      } else {
        message.error(errormsg || "操作失败");
      }
    });
  };
  //删除待办-待增员
  deleteTodoList = (payload) => {
    API.updateRunStatus(payload).then(({ status, errormsg }) => {
      if (status) {
        message.success("操作成功");
        this.query();
        this.onSelectChange([]);
      } else {
        message.error(errormsg || "操作失败");
      }
    });
  };
  //删除待办-待减员
  cancelStayDel = (payload) => {
    API.cancelStayDel(payload).then(({ status, errormsg }) => {
      if (status) {
        message.success("操作成功");
        this.query();
        this.onSelectChange([]);
      } else {
        message.error(errormsg || "操作失败");
      }
    });
  };

  getTipChildren = () => {
    const { selectedKey } = this.state;
    let dom = null;
    switch (selectedKey) {
      case "pending":
        dom = <div>
          {/*<div>1、新入职人员、返聘人员和个税扣缴义务人发生变更从【待减员】中减员操作的会进入【待增员】；</div>*/}
          {/*<div>2、返聘人员默认返聘前的社保福利缴纳方案、缴纳账号、缴纳组织数据，其他数据会清空；</div>*/}
          <div>1、个税扣缴义务人变更进入【待增员】的，保留所有最新版本数据；若修改了数据再增员则修改的数据作为新版本保存；</div>
          <div>2、维护好员工的社保福利档案数据后，点击【增员】，数据会进入【在缴员工】；</div>
          <div>3、若不需给该员工缴纳，可点击【删除待办】进入【停缴员工】；进入【停缴员工】后，可以点击【取消停缴】再次进入【待增员】；</div>
          <div>4、不管起始缴纳月维护到哪个月，都可以进行增员，不影响核算判断；若维护了最后缴纳月，且小于等于当前月，则增员失败；</div>
          <div>5、增员失败情况：①终止缴纳月小于等于当前月；②方案或起始缴纳月未维护；</div>
          {/*  ②其他的个税扣缴义务人下的在缴员工中存在该员工，在缴员工未进入停缴员工；*/}
        </div>;
        break;
      case "fixed":
        dom = <div>
          <div>1、需缴纳社保福利的员工维护在【在缴员工】；</div>
          <div>2、可使用更新导入，调整档案数据；</div>
          <div>3、若维护了最后缴纳月且小于等于当前月，则自动进入【待减员】；</div>
          <div>4、核算人员范围为，【在缴员工】中的起始缴纳月和最后缴纳月区间包含当前月的人员；</div>
        </div>;
        break;
      case "suspend":
        dom = <div>
          {/*④某员工分权时在原个税扣缴义务人下处于【在缴员工】里但又将该员工添加到其他的个税扣缴义务人下的情况；*/}
          <div>1、数据进入【待减员】规则：①员工的人事状态属性从在职变成非在职，且在【在缴员工】里；②【在缴员工】里档案维护了缴纳终止月且小于等于当前月；③个税扣缴义务人发生调整；</div>
          <div>2、【待减员】为是否不再缴纳的待办状态，数据是从【在缴员工】中复制的，若不处理列表中的待办数据，也不影响社保福利核算；【待减员】维护的数据和【在缴员工】数据是同步的；</div>
          <div>3、点击【减员】前先维护最后缴纳月，所有有起始缴纳月的福利项的最后缴纳月都小于等于当前月且无未归档的核算数据的档案才能减员成功，减员成功后数据进入【停缴员工】；</div>
          {/*<div>4、数据进入【待减员】规则的第四种情况下，若还需要在当前个税扣缴义务人下进行缴纳的话，当前该员工的【待减员】数据进行【删除待办】操作即可；若不在该个税扣缴义务人下继续缴纳，维护好最后缴纳月后进行【减员】操作，员工进入【停缴员工】；</div>*/}
        </div>;
        break;
      case "stop":
        dom = <div>
          <div>1、不需要缴纳社保福利的员工，保存在【停缴员工】；</div>
          {/*<div>2、【停缴员工】点击取消停缴，数据会回退到上次的位置（从【待减员】减员到停缴员工的，点击停缴返回到【在缴员工】，不返回到【待减员】）；</div>*/}
          {/*<div>3、若员工的社保福利从一个个税扣缴义务人下转到另一个个税扣缴义务人下去缴纳，则在转后的个税扣缴义务人的【待增员】中进行增员操作成功后，员工进入待【在缴员工】，而在原个税扣缴义务人下的【停缴员工】中，该员工数据将会被删除；是否开启分权员工的档案数据都只保存一份；</div>*/}
        </div>;
        break;
      default:
        break;
    }
    return dom;
  };

  render() {
    const { archivesStore, taxAgentStore: { showOperateBtn } } = this.props;
    const {
      selectedTab,
      selectedRowKeys,
      selectedKey,
      dataSource: dataSourceActive,
      pageInfo,
      tabCount,
      loading,
      importDialog,
      extEmpsWitch,
      logDialog
    } = this.state;
    const {
      form, condition, showSearchAd, setShowSearchAd,
      previewCurDataColumns, previewCurDataDataSource, importResult
    } = archivesStore;
    if (_.isEmpty(this.getColumns())) return renderLoading();
    const adBtn = [ // 高级搜索内部按钮
      <Button type="primary" onClick={() => {
        setShowSearchAd(false);
        this.setState({
          pageInfo: {
            ...pageInfo,
            current: 1,
            pageSize: 10
          }
        }, () => {
          this.query();
        });
      }}>搜索</Button>,
      <Button type="ghost" onClick={() => form.resetForm()}>重置</Button>,
      <Button type="ghost" onClick={() => setShowSearchAd(false)}>取消</Button>
    ];

    // 导出全部
    const handleButtonClick = () => {
      const { selectedKey } = this.state;
      let url = `${window.location.origin}/api/bs/hrmsalary/scheme/export?ids=`;
      switch (selectedKey) {
        case "pending":
          url = `${url}&runStatuses=1&${convertToUrlString(form.getFormParams())}`;
          break;
        case "fixed":
          url = `${url}&runStatuses=2,3&${convertToUrlString(form.getFormParams())}`;
          break;
        case "suspend":
          url = `${url}&runStatuses=3&${convertToUrlString(form.getFormParams())}`;
          break;
        default:
          url = `${url}&runStatuses=4,5&${convertToUrlString(form.getFormParams())}`;
          break;
      }
      window.open(url, "_self");
    };

    // 导出选中
    const handleMenuClick = () => {
      const { selectedRowKeys } = this.state;
      if (selectedRowKeys.length == 0) {
        message.warning("未选择任何条目", 1);
        return;
      }
      let ids = selectedRowKeys.join(",");
      let url = `${window.location.origin}/api/bs/hrmsalary/scheme/export?ids=${ids}`;
      switch (selectedKey) {
        case "pending":
          url = `${url}&runStatuses=1`;
          break;
        case "fixed":
          url = `${url}&runStatuses=2,3`;
          break;
        case "suspend":
          url = `${url}&runStatuses=3`;
          break;
        default:
          url = `${url}&runStatuses=4,5`;
          break;
      }
      window.open(url, "_self");
    };

    const btns = selectedKey === "fixed" ? [
      <Button type="primary" onClick={() => {
        this.handleBtnImport("2");
      }}>导入</Button>,
      <Dropdown.Button onClick={handleButtonClick} overlay={
        <Menu onClick={handleMenuClick}>
          <Menu.Item key="1">导出选中</Menu.Item>
        </Menu>
      } type="ghost">
        导出全部
      </Dropdown.Button>
    ] : selectedKey === "pending" ? [
      <WeaHelpfulTip
        width={300}
        title={<div>提示：缴纳月份区间包含起始缴纳月，不包含最后缴纳月； 若员工离职时还未增员进入在缴员工，则数据会自动清除，
          因此若确认缴纳，请及时维护档案数据并增员操作。若清除后还需缴纳，需先在个税扣缴义务人菜单将员工按离职状态添加回来，会重新出现在待增员。</div>}
        placement="topLeft"
      />,
      <Dropdown.Button
        onClick={this.handleMenuBtnClick}
        overlay={
          <Menu onClick={this.handleMenuItemClick}>
            <Menu.Item key="1">批量增员</Menu.Item>
            <Menu.Item key="4">批量删除待办</Menu.Item>
          </Menu>
        } type="ghost"
      >
        全量增员
      </Dropdown.Button>,
      <Button type="primary" onClick={() => {
        this.handleBtnImport("1");
      }}>导入</Button>,
      <Dropdown.Button onClick={handleButtonClick} overlay={
        <Menu onClick={handleMenuClick}>
          <Menu.Item key="1">导出选中</Menu.Item>
        </Menu>
      } type="ghost">
        导出全部
      </Dropdown.Button>
    ] : selectedKey === "suspend" ? [
      <WeaHelpfulTip
        width={300}
        title={<HelpfulDiv/>}
        placement="topLeft"
      />,
      <Dropdown.Button
        onClick={this.handleMenuBtnClick}
        overlay={
          <Menu onClick={this.handleMenuItemClick}>
            <Menu.Item key="1">批量减员</Menu.Item>
            <Menu.Item key="2">批量删除待办</Menu.Item>
          </Menu>
        }
        type="primary"
      >
        全量减员
      </Dropdown.Button>,
      <Dropdown.Button onClick={handleButtonClick} overlay={
        <Menu onClick={handleMenuClick}>
          <Menu.Item key="1">导出选中</Menu.Item>
        </Menu>
      } type="ghost">
        导出全部
      </Dropdown.Button>
    ] : selectedKey === "stop" ? [
      <WeaHelpfulTip
        width={300}
        title={<CancelHelpfulDiv/>}
        placement="topLeft"
      />,
      <Button type="primary" onClick={() => this.cancelStopPayment(selectedRowKeys)}>批量取消停缴</Button>,
      <Dropdown.Button onClick={handleButtonClick} overlay={
        <Menu onClick={handleMenuClick}>
          <Menu.Item key="1">导出选中</Menu.Item>
        </Menu>
      } type="ghost">
        导出全部
      </Dropdown.Button>
    ] : [<Button type="primary"
                 onClick={() => this.setState(({
                   runStatus: "2",
                   importDialog: {
                     ...importDialog,
                     visible: true, title: getLabel(111, "非系统人员导入"),
                     link: "/api/bs/hrmsalary/scheme/template/export?extWelArchiveList=true"
                   }
                 }))}>导入</Button>
    ];

    const pagination = {
      current: pageInfo.current,
      pageSize: pageInfo.pageSize,
      total: pageInfo.total,
      showTotal: total => `共 ${total} 条`,
      showQuickJumper: true,
      showSizeChanger: true,
      pageSizeOptions: ["10", "20", "50", "100"],
      onShowSizeChange: (current, pageSize) => {
        this.setState({ pageInfo: { ...pageInfo, current, pageSize } }, () => {
          this.query();
        });
      },
      onChange: current => {
        this.setState({ pageInfo: { ...pageInfo, current } }, () => {
          this.query();
        });
      }
    };

    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange
    };
    return (
      <div className="mySalaryBenefitsWrapper">
        <WeaTop
          title="社保福利档案" icon={<i className="icon-coms-fa"/>} iconBgcolor="#F14A2D" showDropIcon={true}
          dropMenuDatas={[
            {
              key: "log",
              icon: <i className="iconfont icon-caozuorizhi32"/>,
              content: getLabel(111, "操作日志"),
              onClick: key => this.setState({ logDialog: { ...logDialog, visible: true } })
            }
          ]}
        >
          <WeaTab
            datas={(extEmpsWitch === "0" || !extEmpsWitch) ? _.dropRight(tabCondition) : tabCondition}
            buttons={showOperateBtn ? btns : []}
            counts={tabCount}
            countParam="groupid" //数量
            keyParam="viewcondition" //主键
            selectedKey={selectedKey}
            onChange={this.handleChangeTab}
            autoCalculateWidth
            searchType={["base", "advanced"]} // base：基础搜索框 advanced：显示高级搜索按钮
            showSearchAd={showSearchAd} // 是否展开高级搜索面板
            setShowSearchAd={bool => setShowSearchAd(bool)} //高级搜索面板受控
            searchsAd={getSearchs(form, toJS(condition), 2)} // 高级搜索内部数据
            buttonsAd={adBtn} // 高级搜索内部按钮
            searchsBasePlaceHolder={"请输入姓名"}
            onSearch={() => {
              this.setState({
                pageInfo: {
                  ...pageInfo,
                  current: 1,
                  pageSize: 10
                }
              }, () => {
                this.query();
              });
            }} // 点搜索按钮时的回调
            onSearchChange={v => form.updateFields({ username: v })} // 在搜索框中输入的文字改变时的回调: 这里需要同步高级搜索和外部搜索框的值
            searchsBaseValue={form.getFormParams().username} // 外部input搜索值受控: 这里和高级搜索的requestname同步
          />
          <div className="tableWrapper">
            <WeaNewScroll height="100%">
              <UnifiedTable
                loading={loading.query}
                rowKey="baseInfo"
                columns={this.getColumns()}
                dataSource={dataSourceActive}
                pagination={pagination}
                rowSelection={rowSelection}
                xWidth={this.getColumns().length * 120}
              />
              {
                !_.isEmpty(this.getColumns()) && selectedKey !== "ext" &&
                <TipLabel>{this.getTipChildren()}</TipLabel>
              }
            </WeaNewScroll>
          </div>
        </WeaTop>
        {/*操作日志*/}
        <OperateLogDialog {...logDialog}
                          onCancel={() => this.setState({ logDialog: { ...logDialog, visible: false } })}
        />
        {
          this.state.editSlideVisible &&
          <WeaSlideModal
            className="slideOuterWrapper"
            visible={this.state.editSlideVisible}
            top={0}
            measureT="%"
            width={800}
            measureX="px"
            height={100}
            measureY="%"
            direction="right"
            title={
              <SlideModalTitle
                subtitle={"员工福利档案"}
                tabs={[
                  { title: "基础设置", key: 0 }, { title: "社保", key: 1 },
                  { title: "公积金", key: 2 }, { title: "企业年金及其他福利", key: 3 }]
                }
                editable={false}
                selectedTab={selectedTab}
                showOperateBtn={showOperateBtn}
                customOperate={
                  (showOperateBtn && selectedKey !== "stop" && selectedTab != 0) ?
                    [<Button type="primary" onClick={() => this.handleEditSlideSave()}>保存</Button>] : []
                }
                subItemChange={selectedTab => this.setState({ selectedTab })}
              />
            }
            content={<div>
              {
                selectedTab == 0 && <BaseForm employeeId={this.state.employeeId} record={this.record}/>
              }
              {
                selectedTab == 1 &&
                <SocialSecurityForm employeeId={this.state.employeeId} record={this.record}
                                    onChangeRecordSchemeId={(siSchemeId) => this.record = {
                                      ...this.record,
                                      siSchemeId
                                    }}/>
              }
              {
                selectedTab == 2 &&
                <AccumulationFundForm employeeId={this.state.employeeId} record={this.record}
                                      onChangeRecordFundSchemeId={(fundSchemeId) => this.record = {
                                        ...this.record,
                                        fundSchemeId
                                      }}/>
              }
              {
                selectedTab == 3 && <OtherForm employeeId={this.state.employeeId} record={this.record}
                                               onChangeRecordOtherSchemeId={(otherSchemeId) => this.record = {
                                                 ...this.record,
                                                 otherSchemeId
                                               }}/>
              }
            </div>}
            onClose={() => this.setState({ editSlideVisible: false }, () => {
              this.setState({ selectedTab: "0" });
            })}
            showMask={true}
            closeMaskOnClick={() => this.setState({ editSlideVisible: false }, () => {
              this.setState({ selectedTab: "0" });
            })}/>
        }
        <ImportDialog
          {...importDialog}
          onCancel={(isFresh) => this.setState({
            importDialog: {
              ...importDialog,
              visible: false, title: "", nextloading: false,
              link: "", importResult: {}, imageId: ""
            }
          }, () => isFresh && this.query())}
          onResetImportResult={() => this.setState(({
            importDialog: { ...importDialog, importResult: {}, imageId: "" }
          }))}
          exportDataDom={
            <WeaCheckbox content={getLabel(543208, "导出现有数据")}
                         value={getURLParameters(importDialog.link).exportData === "true" ? "1" : "0"}
                         helpfulTip={getLabel(111, "提示：建议先导出现有最新数据，修改后再导入")}
                         onChange={val => {
                           const formParams = form.getFormParams() || {};
                           const payload = { exportData: val === "1", ...formParams };
                           this.setState(({
                             importDialog: {
                               ...importDialog,
                               link: `/api/bs/hrmsalary/scheme/template/export?extWelArchiveList=true&${convertToUrlString(payload)}`
                             }
                           }));
                         }}
            />
          }
          nextCallback={imageId => this.setState({ importDialog: { ...importDialog, imageId } })}
          nextUplaodCallback={imageId => this.handleImport({ imageId })}
        />
        {
          this.state.importVisible && <ImportModal
            init={() => {
              this.handleInitModal();
            }}
            params={this.state.modalParam}
            columns={previewCurDataColumns}
            step={this.state.step}
            setStep={this.setStep.bind(this)}
            isInit
            slideDataSource={previewCurDataDataSource}
            importResult={importResult}
            onFinish={() => {
              this.handleFinish();
            }}
            previewImport={(params) => {
              this.handlePreviewImport(params);
            }}
            importFile={(params) => {
              this.handleImport(params);
            }}
            templateLink={(exportData) => {
              this.handleTemplateLinkClick(exportData);
            }}
            visiable={this.state.importVisible}
            onCancel={() => {
              this.handleImportCancel();
            }}
          />
        }
      </div>
    );
  }
}

const HelpfulDiv = () => {
  return <div className="helpWrapper">
    <span>1、缴纳月份区间包含起始缴纳月，不包含最后缴纳月;</span>
    <span>2、维护的所有的最后缴纳月都大于当前月，则该待办数据自动清除，不显示在待减员列表；</span>
    <span>3、减员失败情况：①有起始缴纳月却未维护最后缴纳月；②员工存在未归档的核算数据；</span>
  </div>;
};

const CancelHelpfulDiv = () => {
  return <div className="helpWrapper">
    <span>1、缴纳月份区间包含起始缴纳月，不包含最后缴纳月;</span>
    <span>2、若员工当前不在停缴档案的个税扣缴义务人下，则不可取消停缴；</span>
    <span>3、若员工当前在其他个税扣缴义务人下正在缴纳，也不可取消停缴；</span>
  </div>;
};
