/*
 * Author: 黎永顺
 * name:薪资明细列表
 * Description:
 * Date: 2024/3/26
 */
import React, { Component } from "react";
import { inject, observer } from "mobx-react";
import { WeaTableNew } from "comsMobx";
import { WeaLoadingGlobal, WeaLocaleProvider, WeaSelect } from "ecCom";
import { Button, message, Modal, Spin } from "antd";
import { getIframeParentHeight } from "../../../util";
import { sysConfCodeRule } from "../../../apis/ruleconfig";
import CustomTransferDialog from "../../../components/CustomBrowser/components/customTransferDialog";
import SalaryDetailsTempDialog from "./salaryDetailsTempDialog";
import SalaryTempMangerDialog from "./salaryTempMangerDialog";
import { MonthRangePicker } from "../../reportView/components/statisticalMicroSettingsSlide";
import AdvanceInputBtn from "../components/advanceInputBtn";
import SearchPannel from "../components/searchPannel";
import * as API from "../../../apis/statistics";
import cs from "classnames";
import "../index.less";

const WeaTableComx = WeaTableNew.WeaTable;
const { getLabel } = WeaLocaleProvider;

@inject("attendanceStore")
@observer
class SalaryDetails extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false, dataSource: [], columns: [], selectedRowKeys: [], tempPageList: [], sumRow: {},
      pageInfo: { current: 1, pageSize: 10, total: 0 }, payload: {}, templateId: "", tempManageQuery: false,
      showTotalCell: false, updateSum: true,
      tempDialog: { visible: false, setting: [], heads: [], id: "", template: {} },
      transferDialog: {
        visible: false, searchParamsKey: "name", saveLoading: false,
        dataParams: { page: "salary_details_report" },
        completeURL: "", convertDatasource: datas => {
          return {
            listDatas: _.map(datas.setting, o => ({ id: o.id || o.column, name: o.name || o.text })),
            checked: converCheckedCol(datas)
          };
        },
        dialogType: "temp"
      },
      tempManageDialog: { //模板管理
        visible: false, completeURL: "", dialogType: "table", dataParams: { page: "salary_details_report" }
      }
    };
  }

  async componentDidMount() {
    const [{ data: confCode }] = await Promise.all([sysConfCodeRule({ code: "OPEN_ACCT_RESULT_SUM" })]);
    this.setState({ showTotalCell: confCode === "1" });
    window.addEventListener("message", this.handleReceive, false);
    window.addEventListener("resize", () => this.forceUpdate(), false);
  }

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

  componentWillUnmount() {
    window.removeEventListener("message", this.handleReceive, false);
    window.removeEventListener("message", () => this.forceUpdate(), false);
    this.setState(({ selectedRowKeys: [] }));
  }

  getPageListTemplatelist = () => {
    API.getPageListTemplatelist({ page: "salary_details_report" }).then(({ status, data }) => {
      if (status) {
        this.setState({
          tempPageList: _.map(data, o => ({ ...o, key: String(o.id), showname: o.name })),
          templateId: !_.isEmpty(_.find(data, o => !!o.checked)) ? String(_.find(data, o => !!o.checked).id) : ""
        });
      }
    });
  };
  handleReceive = ({ data }) => {
    const { type, payload: { id, params } = {} } = data;
    const { pageInfo } = this.state;
    if (type === "init") {
      // this.getColumns();
      this.getSalaryList(this.props);
    } else if (type === "turn") {
      if (id === "PAGEINFO") {
        const { pageNum: current, size: pageSize } = params;
        this.setState({
          pageInfo: { ...pageInfo, current, pageSize }, updateSum: false
        }, () => this.getSalaryList(this.props));
      } else if (id === "CHECKBOX") {
        const { selectedRowKeys: checkBox } = params;
        this.setState({ selectedRowKeys: checkBox, updateSum: false });
      }
    }
  };
  postMessageToChild = (payload) => {
    const i18n = {
      "共": getLabel(18609, "共"), "条": getLabel(18256, "条"),
      "总计": getLabel(523, "总计")
    };
    const childFrameObj = document.getElementById("atdTable");
    childFrameObj && childFrameObj.contentWindow.postMessage(JSON.stringify({ ...payload, i18n }), "*");
  };
  getSalaryList = (props) => {
    const { attendanceStore: { salaryDetailSearchForm, tableStore }, dateRange } = props || this.props;
    const [startDateStr, endDateStr] = dateRange;
    const { taxAgentIds, subcompanyIds, departmentIds, employeeIds, ...extra } = salaryDetailSearchForm.getFormParams();
    const { pageInfo, transferDialog, updateSum } = this.state;
    const payload = {
      taxAgentIds: taxAgentIds ? taxAgentIds.split(",") : [],
      departmentIds: departmentIds ? departmentIds.split(",") : [],
      subcompanyIds: subcompanyIds ? subcompanyIds.split(",") : [],
      employeeIds: employeeIds ? employeeIds.split(",") : [],
      ...extra, ...pageInfo, startDateStr, endDateStr
    };
    this.setState({ loading: true });
    API.getSalaryList(payload).then(({ status, data }) => {
      if (updateSum) this.getSalaryListSum(payload);
      this.setState({ loading: false });
      if (status) {
        const { columns, dataKey, pageInfo: pageparams } = data;
        const { list: dataSource, pageNum: current, total, pageSize } = pageparams;
        this.setState({
          columns, dataSource, pageInfo: { ...pageInfo, current, total, pageSize }, payload
        }, () => {
          // tableStore.getDatas(dataKey.datas)
          this.getColumns();
        });
      }
    }).catch(() => this.setState({ loading: false }));
  };
  getSalaryListSum = (payload) => {
    API.getSalaryListSum(payload).then(({ status, data }) => {
      if (status) this.setState({ sumRow: data.sumRow }, () => this.getColumns());
    });
  };
  handleExportSalaryList = (key) => {
    // const { attendanceStore: { tableStore }, salaryDetailShowType } = this.props;
    let { selectedRowKeys, payload, columns: tempCols } = this.state;
    // const customCols = _.filter(toJS(tableStore.columns), (item) => item.display === "true" && item.dataIndex !== "acctTimes");
    // const columns = salaryDetailShowType === "1" ? _.filter(tempCols, o => o.column !== "acctTimes") : customCols;
    const columns = _.filter(tempCols, o => o.column !== "acctTimes");
    if (key === "SELECTED" && selectedRowKeys.length === 0) {
      message.warning(getLabel(543345, "请选择需要导出的数据！"));
      return;
    }
    WeaLoadingGlobal.start();
    const promise = API.exportSalaryList({
      ...payload, ids: key === "SELECTED" ? selectedRowKeys : [], columns: _.map(columns, o => o.column || o.dataIndex)
    });
  };
  getColumns = () => {
    // const { attendanceStore: { tableStore }, salaryDetailShowType } = this.props;
    const {
      columns: tempCols, dataSource, pageInfo, selectedRowKeys, showTotalCell, sumRow
    } = this.state;
    // const customCols = _.filter(toJS(tableStore.columns), (item) => item.display === "true" && item.dataIndex !== "acctTimes");
    // const columns = salaryDetailShowType === "1" ? _.filter(tempCols, o => o.column !== "acctTimes") : customCols;
    const columns = _.filter(tempCols, o => o.column !== "acctTimes");
    if (!_.isEmpty(columns)) {
      this.postMessageToChild({
        dataSource, pageInfo, selectedRowKeys, showTotalCell, calcDetail: true, tableScrollHeight: 154, sumRow,
        columns: _.map(columns, (it, idx) => ({
          dataIndex: it.column || it.dataIndex, title: it.text || it.title, calcDetail: true, showSee: false,
          width: (it.dataIndex === "taxAgent" || it.dataIndex === "salarySob") ? 176 : (it.width || it.oldWidth),
          fixed: (idx === 1 || idx === 0 || idx === 2) ? "left" : "",
          ellipsis: true
        }))
      });
    }
    return [];
  };
  handleSetDefCols = (params = {}) => this.setState({
    transferDialog: {
      ...this.state.transferDialog, visible: true, dataParams: { ...this.state.transferDialog.dataParams, ...params },
      completeURL: "/api/bs/hrmsalary/common/pageList/template/get", dialogType: "temp"
    }
  }, () => this.getPageListTemplatelist());

  savePageListSetting = (values) => {
    const { transferDialog } = this.state;
    const payload = {
      ...transferDialog.dataParams, setting: _.map(values, o => o.id)
    };
    this.setState({ transferDialog: { ...this.state.transferDialog, saveLoading: true } });
    API.savePageListSetting(payload).then(({ status, errormsg }) => {
      this.setState({ transferDialog: { ...this.state.transferDialog, saveLoading: false } });
      if (status) {
        message.success(getLabel(111, "操作成功！"));
        this.setState({
          transferDialog: { ...this.state.transferDialog, visible: false, dialogType: "temp" }
        }, () => this.getSalaryList());
      } else {
        message.error(errormsg);
      }
    });
  };
  handelAddTemp = (templateId = "") => {
    const { tempDialog, tempPageList } = this.state;
    if (_.isEmpty(this.transferRef.state.rightDatas)) {
      message.warning(getLabel(111, "请选择设置！"));
      return;
    }
    this.setState({
      tempDialog: {
        ...tempDialog, visible: true, setting: _.map(this.transferRef.state.rightDatas, o => o.id),
        heads: _.map(this.transferRef.state.rightDatas, o => o.name)
        // template: _.find(tempPageList, o => o.key === templateId)
      }
    });
  };
  changePageListTemplate = (templateId) => {
    this.setState({ templateId }, () => {
      API.changePageListTemplate({ page: "salary_details_report", templateId })
        .then(({ status, errormsg }) => {
          if (status) {
            message.success(getLabel(111, "操作成功！"));
            this.setState({
              transferDialog: {
                ...this.state.transferDialog,
                dataParams: { ...this.state.transferDialog.dataParams, id: templateId }
              }
            }, () => {
              this.transferRef.getData(true);
              this.getSalaryList();
            });
          } else {
            message.error(errormsg);
          }
        });
    });
  };
  handleDelTemp = (ids) => {
    Modal.confirm({
      title: getLabel(131329, "信息确认"),
      content: getLabel(111, "确认删除吗?"),
      onOk: () => {
        API.deleteTemplatePageList({ ids }).then(({ status, errormsg }) => {
          if (status) {
            message.success(getLabel(111, "操作成功！"));
            this.setState({ tempManageQuery: !this.state.tempManageQuery }, () => this.getPageListTemplatelist());
          } else {
            message.error(errormsg);
          }
        });
      }
    });
  };

  render() {
    const {
      loading, dataSource, transferDialog, tempDialog, tempPageList, templateId, tempManageDialog, tempManageQuery
    } = this.state;
    const { dateRange, showSearchAd } = this.props;
    const { dialogType } = transferDialog;
    return (<React.Fragment>
        <div className="query-div">
          <MonthRangePicker dateRange={dateRange} viewAttr={2} onChange={this.props.onChange}/>
          <AdvanceInputBtn onOpenAdvanceSearch={this.props.handleOpenAdvanceSearch}
                           onAdvanceSearch={this.props.handleAdvanceSearch}/>
        </div>
        <div className={cs("searchAdvanced-condition-container", { "searchAdvanced-condition-hide": !showSearchAd })}>
          <SearchPannel onCancel={this.props.onCancel} onAdSearch={this.props.onAdSearch}/>
        </div>
        <div className="table-layout"
             style={{ height: getIframeParentHeight(".wea-new-top-req-content", dataSource.length, 70) + "px" }}>
          <Spin spinning={loading}>
            <iframe
              style={{ border: 0, width: "100%", height: "100%" }}
              // src="http://localhost:7607/#/calcTable"
              src="/spa/hrmSalary/hrmSalaryCalculateDetail/index.html#/calcTable"
              id="atdTable"
            />
          </Spin>
          {/*<WeaTableComx*/}
          {/*  style={{ display: "none" }}*/}
          {/*  comsWeaTableStore={tableStore}*/}
          {/*  needScroll={true}*/}
          {/*  columns={this.getColumns()}*/}
          {/*/>*/}
          {/*默认显示列,薪资模板列表*/}
          <CustomTransferDialog {...transferDialog} ref={dom => this.transferRef = dom}
                                onCancel={() => this.setState({
                                  transferDialog: { ...transferDialog, completeURL: "", visible: false }
                                })}
                                buttons={
                                  dialogType === "temp" ? [
                                    <Button type="primary"
                                            onClick={this.handelAddTemp}>{getLabel(111, "存为模板")}</Button>,
                                    <Button type="ghost" onClick={() => this.setState({
                                      tempManageDialog: {
                                        ...tempManageDialog, visible: true,
                                        completeURL: "/api/bs/hrmsalary/common/pageList/template/pageList"
                                      }
                                    })}>{getLabel(111, "模板管理")}</Button>
                                  ] : []
                                }
                                titleOptsComs={
                                  dialogType === "temp" ?
                                    <WeaSelect style={{ width: 200 }} options={tempPageList}
                                               showSearch optionFilterProp="children"
                                               value={templateId}
                                               onChange={this.changePageListTemplate}/> : null
                                }/>
          {/*薪资明细模板设置*/}
          <SalaryDetailsTempDialog {...tempDialog}
                                   onCancel={callback => this.setState({
                                     tempDialog: { ...tempDialog, visible: false, setting: [], heads: [] }
                                   }, () => callback && callback())}
                                   onSuccess={this.getPageListTemplatelist}/>
          {/*薪资明细自定义列模板管理*/}
          <SalaryTempMangerDialog {...tempManageDialog} onDelete={this.handleDelTemp} isQuery={tempManageQuery}
                                  onSuccess={this.getPageListTemplatelist} onCancel={() => this.setState({
            tempManageDialog: { ...tempManageDialog, completeURL: "", visible: false }
          })}/>
        </div>
      </React.Fragment>
    );
  }
}

export default SalaryDetails;

export const converCheckedCol = (data) => {
  return _.reduce(data.checked || [], (pre, cur) => {
    const item = _.find(data.setting, k => k.column === cur.column);
    if (!_.isEmpty(item)) return [...pre, { ...item, id: item.id || item.column, name: item.name || item.text }];
    return pre;
  }, []);
};
