/*
 * Author: 黎永顺
 * name: 薪资核算-列表数据
 * Description:
 * Date: 2023/9/14
 */
import React, { Component } from "react";
import { WeaLocaleProvider, WeaTools } from "ecCom";
import { message, Modal, Spin } from "antd";
import { inject, observer } from "mobx-react";
import {
  acctResultList,
  updateLockEmpCellStatus,
  updateLockEmpStatus,
  updateLockStatus
} from "../../../../../apis/calculate";
import ProgressModal from "../../../../../components/progressModal";
import BatchUpdateSalaryItemValDialog from "./batchUpdateSalaryItemValDialog";
import EditSalaryCalcSlide from "./editSalaryCalcSlide";
import { batchUpdateConditions } from "./condition";

const getLabel = WeaLocaleProvider.getLabel;
const getKey = WeaTools.getKey;

@inject("calculateStore")
@observer
class EditCalcTable extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false, pageInfo: { current: 1, pageSize: 10, total: 0 },
      selectedRowKeys: [], progressVisible: false, progress: 0,
      salaryCalcSlide: { visible: false, id: "", viewAttr: 2 }, originPayloadData: {},
      batchUpdateDialog: {
        visible: false, salaryAcctRecordId: "", idList: [], salaryItemId: "",
        conditions: [], pattern: 0, dataType: ""
      }
    };
    this.timerLock = null;
  }

  componentDidMount() {
    window.addEventListener("message", this.handleReceive, false);
  }

  handleReceive = async ({ data }) => {
    const { type, payload: { id, params } = {} } = data;
    if (type === "init") {
      this.queryCalcResultList();
    } else if (type === "turn") {
      switch (id) {
        case "PAGEINFO":
          const { size: pageSize, pageNum: current } = params;
          this.setState({ pageInfo: { ...this.state.pageInfo, current, pageSize } }, () => this.queryCalcResultList());
          break;
        case "CHECKBOX":
          const { selectedRowKeys } = params;
          this.setState({ selectedRowKeys });
          break;
        case "FORMULA":
          const { dataIndex } = params;
          this.props.onShowFormulaTd(dataIndex);
          break;
        case "LOCKING":
          const { salaryItemId, lockType } = params;
          if (lockType === "BATCHUPDATE") {
            this.batchUpdateSalaryItemVal(params);
            return;
          }
          this.updateLockStatus({ lockStatus: lockType, salaryItemId });
          break;
        case "LOCKEMP":
          this.updateEmpLockStatus({ ...params });
          break;
        case "EDIT":
          const { id: salaryCalcId, showSee } = params;
          this.setState({
            salaryCalcSlide: { visible: true, id: salaryCalcId, viewAttr: showSee ? 1 : 2 }
          });
          break;
        case "DIAGRAM":
          const { salarySobId } = this.props;
          const { salaryItemId: itemid, acctEmpId } = params;
          window.open(`/spa/hrmSalary/static/index.html#/main/hrmSalary/topologyView/${salarySobId}/${itemid}?acctEmpId=${acctEmpId}`, "_blank");
          break;
        default:
          break;
      }
    }
  };
  updateLockStatus = (payload) => {
    const { salarySobId } = this.props;
    const { lockStatus, salaryItemId } = payload;
    if (lockStatus === "DIAGRAM") {
      window.open(`/spa/hrmSalary/static/index.html#/main/hrmSalary/topologyView/${salarySobId}/${salaryItemId}`, "_blank");
      return;
    }
    Modal.confirm({
      title: getLabel(131329, "信息确认"),
      content: <div>
        <div style={{ textAlign: "center" }}>
          {lockStatus === "LOCK" ? getLabel(543554, "确定要批量锁定项目值吗？") : getLabel(543556, "确定要批量解锁项目值吗？")}
        </div>
        <div style={{ textAlign: "center" }}>
          {lockStatus === "LOCK" ? getLabel(543555, "确定后，则项目输入值锁定，项目公式失效；点击核算将按锁定的输入值重新核算!") :
            getLabel(543557, "确定后，则项目公式生效，页面仍显示手动修改的项目值；点击核算将按公式重新核算，不再显示解锁标识!")}
        </div>
      </div>,
      onOk: () => {
        this.setState({
          progressVisible: true
        }, () => {
          this.timerLock = setInterval(() => {
            if (this.state.progress !== 100) {
              this.setState({
                progress: this.state.progress + 1
              });
            } else {
              clearInterval(this.timerLock);
              this.setState({
                progressVisible: false,
                progress: 0
              });
            }
          }, 500);
        });
        const { routeParams: { salaryAcctRecordId } } = this.props;
        updateLockStatus({ ...payload, salaryAcctRecordId }).then(({ status, errormsg }) => {
          if (status) {
            clearInterval(this.timerLock);
            this.setState({
              progressVisible: false,
              progress: 0
            }, () => this.queryCalcResultList());
          } else {
            message.error(errormsg);
          }
        });
      }
    });
  };
  updateEmpLockStatus = (payload) => {
    const { lockStatus, salaryItemId } = payload;
    Modal.confirm({
      title: getLabel(131329, "信息确认"),
      content: <div>
        <div style={{ textAlign: "center" }}>
          {lockStatus === "LOCK" ? getLabel(111, "确定要锁定该人员核算数据吗？") : getLabel(111, "确定要解锁该人员核算数据吗？")}
        </div>
        <div style={{ textAlign: "center" }}>
          {lockStatus === "LOCK" ? getLabel(111, "确定后，核算数据锁定，项目公式失效；点击核算将跳过该人员已核算的项目!") :
            getLabel(111, "确定后，则项目公式生效，页面仍显示手动修改的项目值；点击核算将按公式重新核算，不再显示解锁标识!")}
        </div>
      </div>,
      onOk: () => {
        this.setState({
          progressVisible: true
        }, () => {
          this.timerLock = setInterval(() => {
            if (this.state.progress !== 100) {
              this.setState({
                progress: this.state.progress + 1
              });
            } else {
              clearInterval(this.timerLock);
              this.setState({
                progressVisible: false,
                progress: 0
              });
            }
          }, 500);
        });
        const { routeParams: { salaryAcctRecordId } } = this.props;
        const params = salaryItemId ? payload : { ...payload, salaryAcctRecordId };
        const APIFunction = salaryItemId ? updateLockEmpCellStatus : updateLockEmpStatus;
        APIFunction(params).then(({ status, errormsg }) => {
          clearInterval(this.timerLock);
          this.setState({
            progressVisible: false,
            progress: 0
          });
          if (status) {
            this.queryCalcResultList();
          } else {
            message.error(errormsg);
          }
        });
      }
    });
  };
  batchUpdateSalaryItemVal = (payload) => {
    Modal.confirm({
      title: getLabel(131329, "信息确认"),
      content: <div>
        <div style={{ textAlign: "center" }}>{getLabel(111, "确认编辑所有人员（所选人员）薪资核算记录？")}</div>
      </div>,
      onOk: () => {
        const { salaryItemId, salaryItemName, dataType, pattern } = payload;
        const { routeParams: { salaryAcctRecordId }, calculateStore: { batchUpdateForm } } = this.props;
        const { selectedRowKeys: idList } = this.state;
        this.setState({
          batchUpdateDialog: {
            ...this.state.batchUpdateDialog, visible: true, salaryAcctRecordId, salaryItemId,
            idList, pattern, dataType, conditions: _.map(batchUpdateConditions, item => ({
              ...item, items: _.map(item.items, o => {
                if (getKey(o) === "value") {
                  const otherParams = dataType === "number" ? { precision: pattern } : {};
                  return {
                    ...o, ...otherParams, label: getLabel(o.lanId, o.label),
                    conditionType: dataType === "number" ? "INPUTNUMBER" : "INPUT"
                  };
                }
                return { ...o, label: getLabel(o.lanId, o.label) };
              })
            }))
          }
        }, () => {
          batchUpdateForm.initFormFields(this.state.batchUpdateDialog.conditions);
          batchUpdateForm.updateFields({ salaryItemName });
        });
      }
    });
  };

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

  postMessageToChild = (payload = {}) => {
    const i18n = {
      "操作": getLabel(30585, "操作"), "编辑": getLabel(501169, "编辑"),
      "点击锁定所有解锁的项目值": getLabel(543649, "点击锁定所有解锁的项目值"),
      "点击解锁所有锁定的项目值": getLabel(543648, "点击解锁所有锁定的项目值"),
      "锁定的项目值": getLabel(543647, "锁定的项目值"),
      "当前状态锁定，右击解锁": getLabel(111, "当前状态锁定，右击解锁"),
      "当前状态未锁定，右击锁定": getLabel(111, "当前状态未锁定，右击锁定"),
      "共": getLabel(18609, "共"), "条": getLabel(18256, "条"),
      "总计": getLabel(523, "总计"), "批量解锁": getLabel(111, "批量解锁"),
      "批量锁定": getLabel(111, "批量锁定"), "批量更新": getLabel(111, "批量更新"),
      "查看拓扑图": getLabel(111, "查看拓扑图"), "锁定": getLabel(111, "锁定"),
      "解锁": getLabel(111, "解锁"), "查看": getLabel(111, "查看")
    };
    this.setState({ originPayloadData: { ...payload, i18n } });
    const childFrameObj = document.getElementById("atdTable");
    childFrameObj.contentWindow.postMessage(JSON.stringify({ ...payload, i18n }), "*");
  };
  queryCalcResultList = () => {
    const { pageInfo } = this.state;
    const {
      calculateStore: { ECSearchForm, otherConditions }, routeParams: { salaryAcctRecordId },
      calcDetail = false
    } = this.props;
    const { subcompanyIds, departmentIds, positionIds, statuses, ...extra } = ECSearchForm.getFormParams();
    const payload = {
      salaryAcctRecordId, ...pageInfo, ...extra, otherConditions,
      departmentIds: !_.isEmpty(departmentIds) ? departmentIds.split(",") : [],
      positionIds: !_.isEmpty(positionIds) ? positionIds.split(",") : [],
      subcompanyIds: !_.isEmpty(subcompanyIds) ? subcompanyIds.split(",") : [],
      statuses: !_.isEmpty(statuses) ? statuses.split(",") : []
    };
    this.setState({ loading: true });
    acctResultList(payload).then(({ status, data }) => {
      this.setState({ loading: false });
      if (status) {
        const { columns, pageInfo: list } = data;
        const { list: dataSource, pageNum: current, pageSize, total } = list;
        this.setState({ pageInfo: { ...pageInfo, current, pageSize, total } }, () => {
          const { pageInfo, selectedRowKeys } = this.state;
          const sumRowlistUrl = this.props.showTotalCell ? "/api/bs/hrmsalary/salaryacct/acctresult/sum" : "";
          this.postMessageToChild({
            dataSource, pageInfo, selectedRowKeys, showTotalCell: this.props.showTotalCell, sumRowlistUrl, payload,
            calcDetail, showSee: calcDetail,
            columns: _.every(traverse(columns, calcDetail), (it, idx) => !it.fixed) ? _.map(traverse(columns, calcDetail), (it, idx) => ({
              ...it,
              fixed: idx < 2 ? "left" : false
            })) : traverse(columns, calcDetail)
          });
        });
      }
    }).catch(() => this.setState({ loading: false }));
  };
  handleQuery = () => {
    this.setState({ pageInfo: { ...this.state.pageInfo, current: 1 } }, () => this.queryCalcResultList());
  };
  handleBatchEditing = () => {
  };


  render() {
    const { loading, progressVisible, progress, salaryCalcSlide, batchUpdateDialog } = this.state;
    return (
      <div className="editCalcTable-layout">
        <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"
          />
          <BatchUpdateSalaryItemValDialog {...batchUpdateDialog}
                                          onCancel={(isRefresh) => this.setState({
                                            batchUpdateDialog: { ...batchUpdateDialog, visible: false }
                                          }, () => isRefresh && this.queryCalcResultList())}
          />
          <EditSalaryCalcSlide {...salaryCalcSlide}
                               onClose={(isFresh) => this.setState({
                                 salaryCalcSlide: { visible: false, id: "", viewAttr: 2 }
                               }, () => isFresh === "true" && this.queryCalcResultList())}/>
          {
            progressVisible &&
            <ProgressModal
              title={getLabel(543558, "正在加锁/解锁请稍后")} visible={progressVisible} progress={progress}
              onCancel={() => {
                this.setState({ progressVisible: false, progress: 0 }, () => {
                  clearInterval(this.timerLock);
                });
              }}
            />
          }
        </Spin>
      </div>
    );
  }
}

export default EditCalcTable;

const traverse = (arr, calcDetail) => {
  return _.map(arr, item => {
    if (!_.isEmpty(item.children)) {
      return {
        title: item.text, width: item.width + "px", ellipsis: true, calcDetail,
        dataIndex: item.column, children: traverse(item.children, calcDetail),
        fixed: item.fixed || false, dataType: item.dataType, align: "center"
      };
    } else {
      return {
        title: item.text, width: item.width + "px", fixed: item.fixed || false,
        dataIndex: item.column, ellipsis: true, lockStatus: item.lockStatus, calcDetail,
        pattern: item.pattern, dataType: item.dataType, align: "center"
      };
    }
  });
};
