import React from "react";
import { Button } from "antd";
import { WeaCheckbox, WeaInputSearch } from "ecCom";
import { getQueryString } from "../../util/url";
import CustomTab from "../../components/customTab";
import { inject, observer } from "mobx-react";
import CompareDetailImportModal from "./compareDetailImportModal";
import CustomPaginationTable from "../../components/customPaginationTable";
import { salaryacctAcctresultCheckAuth } from "../../apis/calculate";
import Authority from "../mySalary/authority";

@inject("calculateStore", "taxAgentStore")
@observer
export default class CompareDetail extends React.Component {
  constructor(props) {
    super(props);
    this.id = "";
    this.state = {
      onlyDiffEmployee: true,
      onlyDiffSalaryItem: true,
      importModalVisible: false,
      searchValue: "",
      calculateAuth: false
    };
    this.pageInfo = { current: 1, pageSize: 10 };
  }

  componentWillMount() {
    this.id = getQueryString("id");
    const { calculateStore: { fetchComparisonResultList } } = this.props;
    const { onlyDiffEmployee, onlyDiffSalaryItem } = this.state;
    let params = {
      onlyDiffEmployee,
      onlyDiffSalaryItem,
      salaryAcctRecordId: this.id,
      current: 1
    };
    fetchComparisonResultList(params);
    this.salaryacctAcctresultCheckAuth({ salaryAcctRecordId: getQueryString("id") })
  }

  salaryacctAcctresultCheckAuth = (params) => {
    const { taxAgentStore: { getPermission } } = this.props;
    getPermission().then(({ data }) => {
      const { isOpenDevolution } = data;
      if (isOpenDevolution) {
        salaryacctAcctresultCheckAuth(params).then(({ status, data }) => {
          this.setState({ calculateAuth: data && status });
        });
      } else {
        this.setState({ calculateAuth: true });
      }
    });
  };

  getColumns = (columns) => {
    let newColumns = [...columns];
    newColumns.map(item => {
      let n = Number(item.dataIndex);
      if (!isNaN(n)) {  // 数字
        item.render = (text, record) => {
          const showDifference = record[`${item.dataIndex}_type`] === "number";
          const { acctResultValue, excelResultValue } = record[item.dataIndex];
          return (
            <div>
              <div>系统值：{acctResultValue}</div>
              <div>线下值：{excelResultValue}</div>
              {
                showDifference &&
                <div style={{ color: "red" }}>
                  差值：{calculateCompares(acctResultValue, excelResultValue)}
                </div>
              }
            </div>
          );
        };
      } else {
        item.fixed = "left";
      }
    });
    return newColumns;
  };

  // 导入
  handleImportClick() {
    this.setState({
      importModalVisible: true
    });
  }

  // 分页变化
  handleDataPageChange(value) {
    const { calculateStore: { fetchComparisonResultList } } = this.props;
    const { onlyDiffEmployee, onlyDiffSalaryItem } = this.state;

    let params = {
      onlyDiffEmployee,
      onlyDiffSalaryItem,
      salaryAcctRecordId: this.id,
      current: value,
      ...this.pageInfo
    };
    fetchComparisonResultList(params);
  }

  handleShowSizeChange(pageInfo) {
    const { calculateStore: { fetchComparisonResultList } } = this.props;
    const { onlyDiffEmployee, onlyDiffSalaryItem } = this.state;
    let params = {
      onlyDiffEmployee,
      onlyDiffSalaryItem,
      salaryAcctRecordId: this.id,
      ...pageInfo
    };
    fetchComparisonResultList(params);
  }

  // 只显示有差异的人员 变化
  onlyDiffEmployeeChange(value) {
    let onlyDiffEmployee = value == 1 ? true : false;
    this.setState({ onlyDiffEmployee });

    const { calculateStore: { fetchComparisonResultList } } = this.props;
    const { onlyDiffSalaryItem } = this.state;

    let params = {
      onlyDiffEmployee,
      onlyDiffSalaryItem,
      salaryAcctRecordId: this.id,
      employeeName: this.state.searchValue,
      current: 1
    };

    fetchComparisonResultList(params);
  }

  // 只显示有差异的薪资项目 变化
  onlyDiffSalaryItemChange(value) {
    let onlyDiffSalaryItem = value == 1 ? true : false;
    this.setState({ onlyDiffSalaryItem });
    const { calculateStore: { fetchComparisonResultList } } = this.props;
    const { onlyDiffEmployee } = this.state;
    let params = {
      onlyDiffEmployee,
      onlyDiffSalaryItem,
      salaryAcctRecordId: this.id,
      employeeName: this.state.searchValue,
      current: 1
    };
    fetchComparisonResultList(params);
  }

  // 搜索
  handleSearch(value) {
    const { calculateStore: { fetchComparisonResultList } } = this.props;
    const { onlyDiffEmployee, onlyDiffSalaryItem } = this.state;
    let params = {
      onlyDiffEmployee,
      onlyDiffSalaryItem,
      salaryAcctRecordId: this.id,
      employeeName: value,
      current: 1
    };
    fetchComparisonResultList(params);
  }

  // 导出
  handleExportClick() {
    window.open(
      "/api/bs/hrmsalary/salaryacct/comparisonresult/export?salaryAcctRecordId=" + this.id
    );
  }

  // 线下对比导入
  handleComparisonFinish() {
    this.pageInfo.current = 1;
    this.pageInfo.pageSize = 10;
    this.handleSearch(this.state.searchValue);
  }

  render() {
    const {
      calculateStore: {
        comparisonResultPageInfo,
        comparisonResultTableStore,
        loading,
        comparisonResultColumns
      }
    } = this.props;
    const { importModalVisible, searchValue, calculateAuth } = this.state;
    const renderRightOperation = () => {
      return (
        <div style={{ display: "inline-block" }}>
          <Button type="primary" style={{ marginRight: "10px" }} onClick={() => this.handleImportClick()}>导入</Button>
          <Button type="default" style={{ marginRight: "10px" }} onClick={() => this.handleExportClick()}>导出</Button>
          <WeaInputSearch value={searchValue} placeholder="请输入姓名" onChange={(value) => {
            this.setState({
              searchValue: value
            });
          }} onSearch={(value) => {
            this.handleSearch(value);
          }}/>
        </div>
      );
    };

    const renderLeftOperation = () => {
      return (
        <div>
          <WeaCheckbox content="只显示有差异的人员" value={this.state.onlyDiffEmployee ? 1 : 0}
                       onChange={(value) => {
                         this.onlyDiffEmployeeChange(value);
                       }}
          />
          <WeaCheckbox content="只显示有差异的薪资项目" value={this.state.onlyDiffSalaryItem ? 1 : 0}
                       onChange={(value) => {
                         this.onlyDiffSalaryItemChange(value);
                       }}
          />
        </div>
      );
    };
    return (
      <Authority ecId={`${this && this.props && this.props.ecId || ""}_Authority@lulowc`}
                 store={{ loading: false, hasRight: calculateAuth }}>
        <div className="compareDetail">
          <CustomTab
            searchOperationItem={
              renderRightOperation()
            }
            leftOperation={
              renderLeftOperation()
            }
          />
          <div className="titleBarWrapper">
            <div className="titleBar">
              <span className="leftTitle">公式=</span>
              <span className="rightTitle">系统值；线下值；<span style={{ color: "red" }}>差值</span></span>
            </div>
          </div>

          <div className="tableWrapper">
            <CustomPaginationTable
              loading={loading}
              dataSource={comparisonResultPageInfo.list ? comparisonResultPageInfo.list : []}
              columns={this.getColumns(comparisonResultColumns ? comparisonResultColumns : [])}
              scroll={{
                x: this.getColumns(comparisonResultColumns ? comparisonResultColumns : []).length * 150,
                y: `calc(100vh - 199px)`
              }}
              total={comparisonResultPageInfo.total}
              current={comparisonResultPageInfo.pageNum}
              pageSize={this.pageInfo.pageSize}
              onPageChange={(value) => {
                this.pageInfo.current = value;
                this.handleDataPageChange(value);
              }}
              onShowSizeChange={(current, pageSize) => {
                this.pageInfo = { current, pageSize };
                this.handleShowSizeChange(this.pageInfo);
              }}
            />
          </div>

          {
            importModalVisible && <CompareDetailImportModal
              visiable={importModalVisible}
              id={this.id}
              onFinish={() => {
                this.handleComparisonFinish();
              }}
              onCancel={() => {
                this.setState({
                  importModalVisible: false
                });
              }}
            />
          }
        </div>
      </Authority>
    );
  }
}

// 计算差值
export const calculateCompares = (systemValue = 0, excelValue = 0) => {
  const systemNum = Number(systemValue);
  const excelNum = Number(excelValue);
  return (systemNum - excelNum).toFixed(2);
};
