import React from "react";
import { inject, observer } from "mobx-react";
import { WeaHelpfulTip, WeaTab } from "ecCom";
import { Button, Spin } from "antd";
import { getQueryString } from "../../../util/url";
import { removePropertyCondition } from "../../../util/response";
import { getSearchs } from "../../../util";
import { getPayrollDetailList, getPayrollDetailSa, getPayrollInfo } from "../../../apis/payroll";
import "./index.less";

@inject("payrollStore")
@observer
export default class PayrollDetail extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      salarySendDetailBaseInfo: {}, loading: false,
      condition: [], dataSource: [], columns: [],
      pageInfo: { current: 1, pageSize: 10, total: 0 }
    };
  }

  componentWillMount() {
    this.getPayrollDetailList();
  }

  componentDidMount() {
    this.getPayrollInfo();
    this.getPayrollDetailSa();
    window.addEventListener("message", this.handleReceiveMessage, false);
  }

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

  handleReceiveMessage = async ({ data }) => {
    const { dataSource, columns, pageInfo } = this.state;
    const childFrameObj = document.getElementById("atdTable");
    const { type, payload } = data;
    if (type === "turn") {
      const { id, params: { size: pageSize, pageNum: current, total } } = payload;
      if (id && id === "PAGEINFO") {
        this.setState({
          pageInfo: {
            ...pageInfo,
            current,
            pageSize,
            total
          }
        }, () => this.getPayrollDetailList({ child: id }));
      }
    }
    if (type === "init") {
      childFrameObj.contentWindow.postMessage(JSON.stringify({
        dataSource,
        columns,
        pageInfo,
        sumpayload: { salarySendId: getQueryString("id") }
      }), "*");
      this.getPayrollDetailList({ child: type });
    }
  };
  getPayrollInfo = () => {
    const id = getQueryString("id");
    getPayrollInfo({ id }).then(({ status, data }) => {
      if (status) {
        this.setState({ salarySendDetailBaseInfo: data });
      }
    });
  };
  getPayrollDetailSa = () => {
    const { payrollStore } = this.props;
    const { detailListConditionForm } = payrollStore;
    getPayrollDetailSa().then(({ status, data }) => {
      if (status) {
        const condition = removePropertyCondition(data.condition);
        this.setState({ condition }, () => {
          detailListConditionForm.initFormFields(this.state.condition);
        });
      }
    });
  };
  getPayrollDetailList = (extra = {}) => {
    const childFrameObj = document.getElementById("atdTable");
    const { pageInfo } = this.state;
    const { child, ...extraParams } = extra;
    const salarySendId = getQueryString("id");
    const { payrollStore } = this.props;
    const { detailListConditionForm: form, setDetailListShowSearchAd } = payrollStore;
    const payload = {
      salarySendId, ...pageInfo, ...extraParams, ...form.getFormParams(),
      departmentIds: form.getFormParams().departmentIds ? form.getFormParams().departmentIds.split(",") : [],
      subCompanyIds: form.getFormParams().subCompanyIds ? form.getFormParams().subCompanyIds.split(",") : []
    };
    this.setState({ loading: true });
    setDetailListShowSearchAd(false)
    getPayrollDetailList(payload).then(({ status, data }) => {
      this.setState({ loading: false });
      if (status) {
        const { columns, datas: dataSource, pageInfo: pages } = data;
        const { pageNum: current, pageSize, total } = pages;
        this.setState({
          dataSource,
          columns: _.map(columns, (item, index) => ({
            dataIndex: item.column, title: item.text, width: item.width,
            fixed: index <= 2 ? "left" : null
          })),
          pageInfo: { ...pageInfo, current, pageSize, total }
        }, () => {
          const { pageInfo, dataSource, columns } = this.state;
          (child === "PAGEINFO" || child === "init") &&
          childFrameObj.contentWindow.postMessage(JSON.stringify({
            dataSource,
            columns,
            pageInfo,
            sumpayload: { salarySendId: getQueryString("id") }
          }), "*");
        });
      }
    }).catch(() => this.setState({ loading: false }));
  };
  handleExportAll = () => {
    const salarySendId = getQueryString("id");
    const url = `${window.location.origin}/api/bs/hrmsalary/salaryBill/send/exportDetailList?salarySendId=${salarySendId}`;
    window.open(url, "_self");
  };
  handleSearch = () => this.getPayrollDetailList({ child: "PAGEINFO", current: 1 });

  render() {
    const { salarySendDetailBaseInfo, condition, loading } = this.state;
    const { payrollStore } = this.props;
    const { setDetailListShowSearchAd, detailListShowSearchAd, detailListConditionForm } = payrollStore;
    const { salaryMonth, template, sendNum, sendTotal } = salarySendDetailBaseInfo;
    const adBtn = [
      <Button type="primary" onClick={this.handleSearch}>搜索</Button>,
      <Button type="ghost" onClick={() => detailListConditionForm.resetForm()}>重置</Button>,
      <Button type="ghost" onClick={() => setDetailListShowSearchAd(false)}>取消</Button>
    ];
    return (
      <div className="payrollDetail">
        <WeaTab
          searchType={["base", "advanced"]} searchsBasePlaceHolder="请输入姓名"
          buttons={[<Button type="primary" onClick={this.handleExportAll}>导出全部</Button>]}
          showSearchAd={detailListShowSearchAd} setShowSearchAd={bool => setDetailListShowSearchAd(bool)}
          searchsAd={getSearchs(detailListConditionForm, condition, 2)}
          buttonsAd={adBtn} onSearch={this.handleSearch}
          onSearchChange={v => detailListConditionForm.updateFields({ username: v })}
          searchsBaseValue={detailListConditionForm.getFormParams().username}
        />
        <div className="titleBar">
          <div className="titleBarLeft">
            <span>薪资所属月：{salaryMonth}</span>
            <WeaHelpfulTip
              style={{ marginLeft: "10px", marginRight: "10px" }}
              width={200}
              title={<PayrollTips salarySendDetailBaseInfo={salarySendDetailBaseInfo}/>}
              placement="topLeft"
            />
            <span>工资单模板：{template}</span>
          </div>

          <div className="titleBarRight">
            <span>已发放：{sendNum}/<span style={{ color: "red" }}>{sendTotal}</span></span>
          </div>
        </div>

        <div className="tableWrapper">
          <Spin spinning={loading}>
            <iframe
              style={{ border: 0, width: "100%", height: "100%" }}
              // src="http://localhost:7607/#/previewTable"
              src="/spa/hrmSalary/hrmSalaryCalculateDetail/index.html#/previewTable"
              id="atdTable"
            />
          </Spin>
        </div>
      </div>
    );
  }
}

export const PayrollTips = (props) => {
  const { salarySendDetailBaseInfo = {} } = props;
  const { salarySobCycle: { salaryCycle, taxCycle, attendCycle, socialSecurityCycle } } = salarySendDetailBaseInfo;
  const { fromDate, endDate } = salaryCycle;
  const { fromDate: aFromDate, endDate: aEndDate } = attendCycle;
  return <div>
    <div>薪资周期</div>
    <div><span>{fromDate}</span><span>至</span><span>{endDate}</span></div>
    <div>税款所属期</div>
    <div>{taxCycle}</div>
    <div>考勤取值周期</div>
    <div><span>{aFromDate}</span><span>至</span><span>{aEndDate}</span></div>
    <div>福利台账月份</div>
    <div>{`引用的${socialSecurityCycle}福利台账数据`}</div>
  </div>;
};
