/*
  *  浮动薪酬
  * 薪资档案列表
  * @Author:    黎永顺
  * @Date:      2024/8/8
  * @Wechat:
  * @Email:     971387674@qq.com
  * @description:
*/
import React, { Component } from "react";
import { inject, observer } from "mobx-react";
import { WeaLocaleProvider, WeaTools } from "ecCom";
import { WeaTableNew } from "comsMobx";
import { message, Modal, Spin } from "antd";
import * as API from "../../../../apis/variableSalary";
import { getSearchs } from "../../../../util";
import { extraConditions } from "../../conditions";
import AdvanceInputBtn from "../advanceInputBtn";
import SearchPannel from "../searchPannel";
import { toJS } from "mobx";
import cs from "classnames";

const WeaTableComx = WeaTableNew.WeaTable;
const getLabel = WeaLocaleProvider.getLabel;
const getKey = WeaTools.getKey;

@inject("baseTableStore") @observer
class Index extends Component {
  constructor(props) {
    super(props);
    this.state = {
      pageInfo: { current: 1, pageSize: 10, total: 0 },
      loading: false,
      dataSource: [],
      columns: [],
      selectedRowKeys: [],
      condtions: [],
      showSearchAd: false
    };
  }

  async componentDidMount() {
    const { data: taxAgentOption } = await API.getAdminTaxAgentList();
    this.setState({
      condtions: _.map(extraConditions, item => {
        return {
          ...item, items: _.map(item.items, child => {
            if (getKey(child) === "taxAgentIds") {
              return {
                ...child,
                label: getLabel(child.lanId, child.label),
                options: _.map(taxAgentOption, o => ({ key: o.id, showname: o.content }))
              };
            }
            return { ...child, label: getLabel(child.lanId, child.label) };
          })
        };
      })
    }, () => {
      const { baseTableStore: { VExtraSalryForm } } = this.props;
      VExtraSalryForm.initFormFields(this.state.condtions);
    });
    window.addEventListener("message", this.handleReceive, false);
    window.addEventListener("resize", this.handleResize, false);
    this.getVariableSalaryList();
  }

  componentWillUnmount() {
    window.removeEventListener("message", this.handleReceive, false);
    window.removeEventListener("resize", this.handleResize, false);
  }

  componentWillReceiveProps(nextProps, nextContext) {
    if (nextProps.isQuery !== this.props.isQuery) this.setState({
      pageInfo: { ...this.state.pageInfo, current: 1 }
    }, () => this.getVariableSalaryList());
  }

  handleReceive = async ({ data }) => {
    const { type, payload: { id, params } = {} } = data;
    if (type === "init") {
      this.getColumns();
    } else if (type === "turn") {
      switch (id) {
        case "PAGEINFO":
          this.setState({
            pageInfo: { ...this.state.pageInfo, ...params }
          }, () => this.getVariableSalaryList());
          break;
        case "CHECKBOX":
          const { selectedRowKeys } = params;
          this.setState({ selectedRowKeys });
          break;
        case "DEL":
          this.handleDelete([params.id]);
          break;
        case "EDIT":
          this.handleView(params.id);
          break;
        default:
          break;
      }
    }
  };
  getVariableSalaryList = () => {
    const { baseTableStore: { VSalryForm, VExtraSalryForm, getVariableSalaryList } } = this.props;
    const { pageInfo } = this.state;
    const { taxAgentIds } = VExtraSalryForm.getFormParams(), { departmentIds } = VSalryForm.getFormParams();
    this.setState({ loading: true });
    getVariableSalaryList({
      ...pageInfo, ...VSalryForm.getFormParams(), ...VExtraSalryForm.getFormParams(),
      departmentIds: !_.isEmpty(departmentIds) ? departmentIds.split(",") : [],
      taxAgentIds: _.isEmpty(taxAgentIds) ? [] : taxAgentIds.split(",")
    }).then(({ status, data }) => {
      this.setState({ loading: false });
      if (status) {
        const { pageInfo: result } = data;
        const { list: dataSource, pageNum: current, pageSize, total } = result;
        this.setState({
          pageInfo: { ...pageInfo, current, pageSize, total }, dataSource
        });
      }
    });
  };
  handleView = (id) => {
    API.getVariableSalaryDetail({ id }).then(({ status, data }) => {
      if (status) this.props.onViewSalaryFile(data.data);
    });
  };
  handleDelete = (ids) => {
    Modal.confirm({
      title: getLabel(111, "信息确认"), content: getLabel(111, "确认删除吗?"), onOk: () => {
        API.deleteVariableSalary({ ids }).then(({ status, errormsg }) => {
          if (status) {
            message.success(getLabel(111, "删除成功"));
            this.setState({ selectedRowKeys: [] }, () => this.getVariableSalaryList());
          } else {
            message.error(errormsg);
          }
        });
      }
    });
  };
  getColumns = () => {
    const { baseTableStore: { SFTableStore }, showOperateBtn } = this.props;
    const columns = _.map(_.filter(toJS(SFTableStore.columns), (item) => item.display === "true"), (it, idx) => ({
      dataIndex: it.dataIndex, title: it.title, align: "left", width: 150, ellipsis: true
    }));
    if (!_.isEmpty(columns)) {
      this.postMessageToChild({
        columns,
        showOperateBtn,
        dataSource: this.state.dataSource,
        scrollHeight: 95,
        pageInfo: this.state.pageInfo,
        unitTableType: "variableSalary",
        selectedRowKeys: this.state.selectedRowKeys
      });
    }
    return columns;
  };
  postMessageToChild = (payload = {}) => {
    const i18n = {
      "操作": getLabel(30585, "操作"),
      "编辑": getLabel(111, "编辑"),
      "共": getLabel(18609, "共"),
      "条": getLabel(18256, "条"),
      "删除": getLabel(111, "删除")
    };
    const childFrameObj = document.getElementById("unitTable");
    childFrameObj && childFrameObj.contentWindow.postMessage(JSON.stringify({ ...payload, i18n }), "*");
  };
  openAdvanceSearch = () => this.setState({ showSearchAd: !this.state.showSearchAd });

  render() {
    const { loading, dataSource, condtions, showSearchAd } = this.state;
    const { baseTableStore: { SFTableStore, VExtraSalryForm } } = this.props;
    const dom = document.querySelector(".wea-new-top-req-content");
    let height = 280;
    if (dom && dataSource.length > 0) {
      height = (parseFloat(dom.style.height) > 620 && dataSource.length === 10) ? dataSource.length * 46 + 108 : dataSource.length < 10 ? dataSource.length * 46 + 108 : parseFloat(dom.style.height) - 62;
    }
    return (<React.Fragment>
      <div className="extraFormQuery form-dialog-layout">
        {getSearchs(VExtraSalryForm, condtions, 2, false, () => this.getVariableSalaryList())}
        <AdvanceInputBtn searchType="advance" onOpenAdvanceSearch={() => this.openAdvanceSearch()}
                         onAdvanceSearch={this.getVariableSalaryList}/>
      </div>
      <div className={cs("searchAdvanced-condition-container", { "searchAdvanced-condition-hide": !showSearchAd })}>
        <SearchPannel onCancel={() => this.setState({ showSearchAd: false })}
                      onAdSearch={() => {
                        this.openAdvanceSearch();
                        this.getVariableSalaryList();
                      }}/>
      </div>
      <div style={{ height: height + "px" }}>
        <Spin spinning={loading}>
          <iframe
            style={{ border: 0, width: "100%", height: "100%" }}
            // src="http://localhost:7607/#/unitTable"
            src="/spa/hrmSalary/hrmSalaryCalculateDetail/index.html#/unitTable"
            id="unitTable"
          />
        </Spin>
      </div>
      <WeaTableComx style={{ display: "none" }} comsWeaTableStore={SFTableStore} needScroll={true}
                    columns={this.getColumns()}/>
    </React.Fragment>);
  }
}

export default Index;
