import React, { Component } from "react";
import { WeaCheckbox, WeaTab, WeaTable } from "ecCom";
import { Button } from "antd";
import { inject, observer } from "mobx-react";
import * as API from "../../../apis/offlineCompare";
import { getSearchs, renderLoading } from "../../../util";
import { getQueryString } from "../../../util/url";
import { calculateCompares } from "../../calculateDetail/compareDetail";
import CompareDetailImportModal from "../../calculateDetail/compareDetailImportModal";
import { conditions } from "./condition";
import "./index.less";

@inject("standingBookStore")
@observer
class StandingBookOfflineComparison extends Component {
  constructor(props) {
    super(props);
    this.state = {
      columns: [],
      dataSource: [],
      onlyDiffEmployee: "1",
      showSearchAd: false,
      loading: true,
      importVisible: false,
      pageInfo: {
        current: 1,
        pageSize: 10,
        total: 0
      }
    };
  }

  componentDidMount() {
    const { standingBookStore: { ocForm: form } } = this.props;
    this.comparisonwelfareList();
    form.initFormFields(conditions);
  }

  comparisonwelfareList = () => {
    const billMonth = getQueryString("billMonth");
    const paymentOrganization = getQueryString("paymentOrganization");
    const { onlyDiffEmployee, pageInfo } = this.state;
    const { standingBookStore: { ocForm: form } } = this.props;
    const formParams = form.getFormParams();
    const payload = {
      paymentStatus: 0,
      billMonth,
      paymentOrganization,
      onlyDiffEmployee: onlyDiffEmployee === "1"
    };
    this.setState({ loading: true });
    API.comparisonwelfareList({ ...payload, ...pageInfo, ...formParams }).then(({ status, data }) => {
      this.setState({ loading: false });
      if (status) {
        const { columns, list: dataSource, total, pageNum: current, pageSize } = data;
        this.setState({
          columns: _.map(columns, (it, idx) => ({
            ...it,
            width: 150,
            fixed: idx < 2 ? "left" : false,
            render: (text, record) => {
              const { acctResultValue, excelResultValue } = record[it.dataIndex] || {};
              if (Object.prototype.toString.call(text) === "[object Object]") {
                return <React.Fragment>
                  <div>系统值：{acctResultValue}</div>
                  <div>线下值：{excelResultValue}</div>
                  <div style={{ color: "red" }}>
                    差值：{calculateCompares(acctResultValue, excelResultValue)}
                  </div>
                </React.Fragment>;
              }
              return <span>{text}</span>;
            }
          })),
          dataSource,
          pageInfo: { ...pageInfo, current, total, pageSize }
        });
      }
    });
  };
  handleExport = () => {
    const billMonth = getQueryString("billMonth");
    const paymentOrganization = getQueryString("paymentOrganization");
    const { onlyDiffEmployee } = this.state;
    let url = `/api/bs/hrmsalary/siaccount/comparisonresult/export?paymentStatus=0&billMonth=${billMonth}&paymentOrganization=${paymentOrganization}&onlyDiffEmployee=${onlyDiffEmployee === "1"}`;
    window.open(`${window.location.origin}${url}`);
  };

  render() {
    const { onlyDiffEmployee, showSearchAd, pageInfo, dataSource, columns, loading, importVisible } = this.state;
    const { standingBookStore: { ocForm: form } } = this.props;
    if (_.isEmpty(columns)) { // 无权限处理
      return renderLoading();
    }
    const buttons = [
      <Button type="primary" onClick={() => this.setState({ importVisible: true })}>导入</Button>,
      <Button type="primary" onClick={this.handleExport}>导出</Button>
    ];
    const adBtn = [
      <Button type="primary" onClick={() => {
        this.setState({ showSearchAd: false }, () => {
          this.comparisonwelfareList();
        });
      }}>搜索</Button>,
      <Button type="ghost" onClick={() => form.resetForm()}>重置</Button>,
      <Button type="ghost" onClick={() => this.setState({ showSearchAd: false })}>取消</Button>
    ];
    return (
      <div className="compareWrapper">
        <WeaTab
          datas={[]}
          buttons={buttons}
          buttonsAd={adBtn}
          searchType={["base", "advanced"]}
          searchsBasePlaceHolder="请输入姓名"
          showSearchAd={showSearchAd}
          setShowSearchAd={showSearchAd => this.setState({ showSearchAd })}
          searchsAd={getSearchs(form, conditions, 2)}
          onSearch={() => {
            this.setState({ showSearchAd: false }, () => {
              this.comparisonwelfareList();
            });
          }}
          onSearchChange={v => form.updateFields({ userName: v })}
          searchsBaseValue={form.getFormParams().userName}
          searchsAdQuick={
            <WeaCheckbox
              value={onlyDiffEmployee}
              onChange={
                (onlyDiffEmployee) =>
                  this.setState({ onlyDiffEmployee }, () => {
                    this.comparisonwelfareList();
                  })
              } content="只显示有差异的人员"/>
          }
        />
        <WeaTable
          columns={columns}
          dataSource={dataSource}
          className="ocTable-wrapper"
          scroll={{ x: 1200, y: "calc(100vh - 150px)" }}
          loading={loading}
          pagination={{
            total: pageInfo.total,
            showTotal: total => `共 ${total} 条`,
            showSizeChanger: true,
            pageSizeOptions: ["10", "20", "50", "100"],
            onShowSizeChange: (current, pageSize) => {
              this.setState({ pageInfo: { ...pageInfo, current, pageSize } }, () => {
                this.comparisonwelfareList();
              });
            },
            onChange: current => {
              this.setState({ pageInfo: { ...pageInfo, current } }, () => {
                this.comparisonwelfareList();
              });
            }
          }}
        />
        {
          importVisible &&
          <CompareDetailImportModal
            visiable={importVisible}
            onFinish={() => this.comparisonwelfareList()}
            onCancel={() => this.setState({ importVisible: false })}
          />
        }
      </div>
    );
  }
}

export default StandingBookOfflineComparison;
