import React from "react";
import { WeaHelpfulTip, WeaSlideModal } from "ecCom";
import { message, Modal } from "antd";
import WarningModal from "./warningModal";
import EditSalaryDetail from "./editSalaryDetail";
import SlideModalTitle from "../../components/slideModalTitle";
import { getQueryString } from "../../util/url";
import { inject, observer } from "mobx-react";
import ProgressModal from "../../components/progressModal";
import { SalaryMonthTip } from "./userSure";
import { toJS } from "mobx";
import "./index.less";

@inject("calculateStore", "taxAgentStore")
@observer
export default class SalaryDetail extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      progressVisible: false,
      progress: 0,
      columnIndex: "",
      visible: false,
      slideVisiable: false,
      columns: []
    };
    this.recordId = "";
    this.id = "";
    this.pageInfo = { current: 1, pageSize: 10 };
  }

  componentWillMount() {
    let id = getQueryString("id");
    this.id = id;
    const { calculateStore: { getSalarySobCycle } } = this.props;
    getSalarySobCycle(id);
  }

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

  componentWillUnmount() {
    window.removeEventListener("message", this.handleClick, false);
    this.timer && clearTimeout(this.timer);
    this.timerLock && clearTimeout(this.timerLock);
  }

  handleClick = ({ data }) => {
    const childFrameObj = document.getElementById("atdTable");
    const salaryAcctRecordId = getQueryString("id");
    const { type, data: { id, data: record, extraId = "" } = {} } = data;
    if (type === "PR") {
      if (id === "EDIT") {
        this.handleEdit(record);
      } else if (id === "COSTCENTER") {
        window.open(record ? record.url : "", "_blank");
      } else if (id === "COLUMNINDEX") {
        if (!extraId) {
          this.setState({ columnIndex: record });
        } else if (extraId === "LOCK") {
          Modal.confirm({
            title: "信息确认",
            content: <div>
              <div style={{ textAlign: "center" }}>确定要批量锁定项目值吗？</div>
              <div
                style={{ textAlign: "center" }}>确定后，则项目输入值锁定，项目公式失效；点击核算将按锁定的输入值重新核算!
              </div>
            </div>,
            onOk: () => this.updateLockStatus("LOCK", record),
            onCancel: () => {
            }
          });
        } else if (extraId === "UNLOCK") {
          Modal.confirm({
            title: "信息确认",
            content: <div>
              <div style={{ textAlign: "center" }}>确定要批量解锁项目值吗？</div>
              <div
                style={{ textAlign: "center" }}>确定后，则项目公式生效，页面仍显示手动修改的项目值；点击核算将按公式重新核算，不再显示解锁标识!
              </div>
            </div>,
            onOk: () => this.updateLockStatus("UNLOCK", record),
            onCancel: () => {
            }
          });
        }
      } else if (id === "PAGEINFO") {
        const { pageNum: current, size: pageSize } = record;
        this.pageInfo = { current, pageSize };
        const payload = {
          type: "PR",
          listType: "",
          url: "/api/bs/hrmsalary/salaryacct/acctresult/list",
          queryParams: {
            salaryAcctRecordId,
            ...this.props.employeeName,
            current, pageSize
          }
        };
        childFrameObj.contentWindow.postMessage(JSON.stringify(payload), "*");
      } else if (id === "BATCHDELETE") {
        this.props.onChangeAccountIds(record);
      }
    } else {
      const payload = {
        type: "PR",
        listType: "",
        url: "/api/bs/hrmsalary/salaryacct/acctresult/list",
        queryParams: {
          salaryAcctRecordId,
          ...this.props.employeeName
        }
      };
      type && childFrameObj.contentWindow.postMessage(JSON.stringify(payload), "*");
    }
  };

  //列头解锁和锁定
  updateLockStatus = (lockStatus, salaryItemId) => {
    const { calculateStore: { updateLockStatus } } = this.props;
    const salaryAcctRecordId = getQueryString("id");
    const module = {
      lockStatus,
      salaryItemId,
      salaryAcctRecordId
    };
    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
          }, () => {
            message.success("操作成功");
          });
        }
      }, 500);
    });
    updateLockStatus(module).then(({ status, errormsg }) => {
      if (status) {
        clearInterval(this.timerLock);
        this.setState({
          progressVisible: false,
          progress: 0
        }, () => {
          const { current, pageSize } = this.pageInfo;
          const childFrameObj = document.getElementById("atdTable");
          const payload = {
            type: "PR",
            listType: "",
            url: "/api/bs/hrmsalary/salaryacct/acctresult/list",
            queryParams: {
              salaryAcctRecordId,
              ...this.props.employeeName,
              current, pageSize
            }
          };
          childFrameObj.contentWindow.postMessage(JSON.stringify(payload), "*");
        });
      } else {
        message.error(errormsg || "操作失败");
      }
    });
  };

  // 编辑时间回调
  handleEdit(record) {
    this.recordId = record.id;
    this.setState({
      slideVisiable: true
    });
  }

  // 侧边栏保存
  handleEditSlideSave = () => {
    const { calculateStore } = this.props;
    const { saveAcctResult } = calculateStore;
    this.setState({ loading: true });
    saveAcctResult(this.recordId).then(() => {
      this.setState({ loading: false });
      const childFrameObj = document.getElementById("atdTable");
      const salaryAcctRecordId = getQueryString("id");
      const { current, pageSize } = this.pageInfo;
      const payload = {
        type: "PR",
        listType: "",
        url: "/api/bs/hrmsalary/salaryacct/acctresult/list",
        queryParams: {
          salaryAcctRecordId,
          ...this.props.employeeName,
          current, pageSize
        }
      };
      childFrameObj.contentWindow.postMessage(JSON.stringify(payload), "*");
      // acctResultList({ salaryAcctRecordId: this.id });
    });
  };


  render() {
    const { slideVisiable, columnIndex, loading } = this.state;
    const { calculateStore, taxAgentStore: { showOperateBtn } } = this.props;
    const { baseSalarySobCycle, columnDescList } = calculateStore;

    return (
      <div className="salaryDetail">
        <div className="salaryBarWrapper">
          <span>薪资所属月：{baseSalarySobCycle.salaryMonth}</span>
          <WeaHelpfulTip
            style={{ marginLeft: 10 }}
            title={!_.isEmpty(baseSalarySobCycle) ?
              <SalaryMonthTip baseSalarySobCycle={baseSalarySobCycle}/> : ""}
            placement="topLeft"
          />
          {/*暂时隐藏*/}
          {/*<span className="warningspan" onClick={() => {*/}
          {/*  this.setState({ visible: true });*/}
          {/*}}>校验异常：0</span>*/}
        </div>
        <div className="salaryBarWrapper" style={{ borderBottom: "1px solid #eee" }}>
          <span>公式=</span>
          <span>{toJS(columnDescList)[columnIndex] && toJS(columnDescList)[columnIndex].formulaContent}</span>
        </div>
        <div className="tableWrapper">
          <iframe
            style={{ border: 0, width: "100%", height: "100%" }}
            // src="http://localhost:7607/#/atdTable"
            src="/spa/hrmSalary/hrmSalaryCalculateDetail/index.html#/atdTable"
            id="atdTable"
          />
        </div>
        <WarningModal visible={this.state.visible} onCancel={() => {
          this.setState({ visible: false });
        }}/>
        {/*加锁解锁进度条*/}
        {
          this.state.progressVisible &&
          <ProgressModal
            title="正在加锁/解锁请稍后"
            visible={this.state.progressVisible}
            onCancel={() => {
              this.setState({ progressVisible: false, progress: 0 });
            }}
            progress={this.state.progress}
          />
        }
        {
          slideVisiable &&
          <WeaSlideModal
            className="slideOuterWrapper"
            visible={slideVisiable}
            top={0}
            width={60}
            height={100}
            direction={"right"}
            measure={"%"}
            title={
              <SlideModalTitle
                subtitle="编辑薪资"
                editable={true}
                showOperateBtn={showOperateBtn}
                onSave={this.handleEditSlideSave}
                loading={loading}
              />
            }
            content={<EditSalaryDetail id={this.recordId}/>}
            onClose={() => this.setState({ slideVisiable: false })}
            showMask={true}
            closeMaskOnClick={() => this.setState({ slideVisiable: false })}/>
        }
      </div>
    );
  }
}
