import React from "react";
import ImportModal from "../../../../components/importModal";
import { Badge, Button, message } from "antd";
import { inject, observer } from "mobx-react";
import SelectFieldModal from "./selectFieldModal";
import { getQueryString } from "../../../../util/url";
import AddHeaderFieldsModal from "./addHeaderFieldsModal";
import { cacheImportField } from "../../../../apis/calculate";
import {
  exportSiaccountWelfarebalanceimporttemplatetetemplate,
  exportSiaccountWelfareImporttemplate,
  exportSiaccountWelfaresupplyimporttemplatetemplate
} from "../../../../apis/standingBook";

@inject("calculateStore", "standingBookStore")
@observer
export default class AcctResultImportModal extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      modalParam: {
        salaryAcctRecordId: "",
        salaryItemIds: ""
      },
      step: 0,
      selectFieldVisible: false,
      addHeadFields: {
        visible: false, itemsByGroup: []
      }
    };
  }

  componentWillMount() {
    const { id } = this.props;
    if (id) {
      this.getImportField();
    } else {
      this.setState({
        modalParam: { ...this.state.modalParam, salaryAcctRecordId: "123" }
      });
    }
  }

  getImportField = () => {
    const { calculateStore: { getImportField }, id } = this.props;
    const { addHeadFields } = this.props;
    getImportField(id).then(data => {
      this.setState({
        addHeadFields: {
          ...addHeadFields,
          itemsByGroup: _.map(data.itemsByGroup, item => {
            return {
              ...item,
              salaryItems: _.map(item.salaryItems, it => ({
                ...it,
                checked: false
              }))
            };
          })
        },
        modalParam: {
          ...this.state.modalParam,
          salaryAcctRecordId: id,
          salaryItemIds: data.checkItems.join(",")
        }
      });
    });
  };

  // 获取模板
  handleAccResultTemplateLink() {
    const { isStandingBook, standingBookTabKey, standingBookType } = this.props;
    let url = "";
    if (_.isEmpty(this.state.modalParam.salaryItemIds)) {
      message.warning("请选择表单字段");
      return;
    }
    if (!isStandingBook) {
      url = `${window.location.origin}/api/bs/hrmsalary/salaryacct/acctresult/importtemplate/export?salaryItemIds=${this.state.modalParam.salaryItemIds}&salaryAcctRecordId=${this.state.modalParam.salaryAcctRecordId}`;
    } else {
      const billMonth = getQueryString("billMonth");
      const paymentOrganization = getQueryString("paymentOrganization");
      if (standingBookTabKey === "1") {
        const promise = exportSiaccountWelfareImporttemplate({
          billMonth,
          welfareNames: this.state.modalParam.salaryItemIds.split(","),
          paymentOrganization: Number(paymentOrganization)
        });
      } else if (standingBookTabKey === "3") {
        const promise = exportSiaccountWelfaresupplyimporttemplatetemplate({
          billMonth,
          welfareNames: this.state.modalParam.salaryItemIds.split(","),
          paymentOrganization: Number(paymentOrganization)
        });
      } else if (standingBookType === "difference") {
        const promise = exportSiaccountWelfarebalanceimporttemplatetetemplate({
          billMonth,
          welfareNames: this.state.modalParam.salaryItemIds.split(","),
          paymentOrganization: Number(paymentOrganization)
        });
      }
    }
    window.open(url, "_self");
  }

  // 设置步骤
  setStep(step) {
    this.setState({ step });
  }

  // 完成
  handleFinish() {
    this.setState({ step: 0 });
    this.props.onCancel();
    if (!this.props.isStandingBook) {
      const childFrameObj = document.getElementById("atdTable");
      const salaryAcctRecordId = getQueryString("id");
      const payload = {
        type: "PR",
        listType: "",
        url: "/api/bs/hrmsalary/salaryacct/acctresult/list",
        queryParams: {
          salaryAcctRecordId
        }
      };
      childFrameObj.contentWindow.postMessage(JSON.stringify(payload), "*");
    }
  }

  // 渲染第一步表单
  renderFormComponent = () => {
    return <Badge
      count={!_.isEmpty(this.state.modalParam.salaryItemIds) ? this.state.modalParam.salaryItemIds.split(",").length : 0}>
      <Button onClick={this.handleSelectedField}>请选择表单字段</Button>
    </Badge>;
  };

  // 选择表单字段
  handleSelectedField = () => {
    if (window.location.hash.indexOf("calculateDetail") !== -1) {
      this.setState({
        addHeadFields: {
          ...this.state.addHeadFields,
          visible: true
        }
      });
    } else {
      this.setState({
        selectFieldVisible: true
      });
    }
  };

  // 添加表头字段
  handleAdd = (fieldDate) => {
    let salaryItemIdsList = [];
    if (!_.isEmpty(fieldDate.formulaItems)) {
      fieldDate.formulaItems.map(item => {
        if (item.checked) {
          salaryItemIdsList.push(item.salaryItemId);
        }
      });
    }
    if (!_.isEmpty(fieldDate.inputItems)) {
      fieldDate.inputItems.map(item => {
        if (item.checked) {
          salaryItemIdsList.push(item.salaryItemId);
        }
      });
    }
    if (!_.isEmpty(fieldDate.sqlItems)) {
      fieldDate.sqlItems.map(item => {
        if (item.checked) {
          salaryItemIdsList.push(item.salaryItemId);
        }
      });
    }
    let salaryItemIds = "";
    if (salaryItemIdsList.length > 0) {
      salaryItemIds = salaryItemIdsList.join(",");
    }

    let modalParam = { ...this.state.modalParam };
    modalParam.salaryItemIds = salaryItemIds;
    this.setState({
      modalParam
    });
    this.props.onAdd(fieldDate);
  };

  // 初始化Import数据
  handleImportModalInit() {
    const {
      calculateStore: {
        setPreviewAcctResultColumns,
        setPreviewAcctResultDataSource,
        setImportAcctResult
      },
      standingBookStore: {
        setPreviewStandingBookAcctResultDataSource,
        setPreviewStandingBookAcctResultColumns,
        setImportStandingBookAcctResult
      },
      isStandingBook
    } = this.props;
    if (!isStandingBook) {
      setPreviewAcctResultColumns([]);
      setPreviewAcctResultDataSource([]);
      setImportAcctResult({});
    } else {
      setPreviewStandingBookAcctResultDataSource([]);
      setPreviewStandingBookAcctResultColumns([]);
      setImportStandingBookAcctResult({});
    }
  }

  render() {
    const billMonth = getQueryString("billMonth");
    //isStandingBook: 是否是社保福利台账核算的导入标识
    //standingBookType: 是否是补差的导入标识
    const { calculateStore, standingBookStore, isStandingBook, visiable, standingBookType } = this.props;
    const {
      fetchPreviewAcctResult,
      previewAcctResultColumns,
      previewAcctResultDataSource,
      importAcctResult,
      fetchImportAcctResult
    } = calculateStore;
    const {
      welfarePreview,
      previewStandingBookAcctResultColumns,
      previewStandingBookAcctResultDataSource,
      importStandingBookAcctResult,
      importInsuranceAcctDetail,
      importBalanceInsuranceDetail
    } = standingBookStore;
    const { step, modalParam, selectFieldVisible, addHeadFields } = this.state;
    return (
      <div>
        {
          visiable && <ImportModal
            isStandingBook={isStandingBook}
            standingBookType={standingBookType}
            init={() => {
              this.handleImportModalInit();
            }}
            params={modalParam}
            columns={!isStandingBook ? previewAcctResultColumns : previewStandingBookAcctResultColumns}
            step={step}
            setStep={this.setStep.bind(this)}
            slideDataSource={!isStandingBook ? previewAcctResultDataSource : previewStandingBookAcctResultDataSource}
            importResult={!isStandingBook ? importAcctResult : importStandingBookAcctResult}
            onFinish={() => {
              this.handleFinish();
            }}
            previewImport={(params) => {
              !isStandingBook ? fetchPreviewAcctResult(params) : welfarePreview(params);
            }}
            importFile={(params) => {
              !isStandingBook ?
                fetchImportAcctResult(params) :
                standingBookType === "difference" ?
                  importBalanceInsuranceDetail({ ...params, billMonth }) :
                  importInsuranceAcctDetail(params);
            }}
            templateLink={() => {
              this.handleAccResultTemplateLink();
            }}
            renderFormComponent={() => this.renderFormComponent()}
            visiable={visiable}
            onCancel={() => {
              this.props.onCancel();
            }}
          />
        }
        {
          selectFieldVisible && <SelectFieldModal
            isStandingBook={isStandingBook}
            standingBookType={standingBookType}
            id={this.props.id}
            visible={selectFieldVisible}
            fieldData={this.props.fieldData}
            onAdd={(fieldDate) => {
              this.handleAdd(fieldDate);
            }}
            onCancel={() => {
              this.setState({
                selectFieldVisible: false
              });
            }}
          />
        }
        <AddHeaderFieldsModal {...addHeadFields} selectItems={modalParam.salaryItemIds}
                              onCancel={() => this.setState({ addHeadFields: { ...addHeadFields, visible: false } })}
                              onAdd={(salaryItemIds) => this.setState({
                                addHeadFields: {
                                  ...addHeadFields,
                                  visible: false
                                },
                                modalParam: {
                                  ...modalParam,
                                  salaryItemIds: salaryItemIds.join(",")
                                }
                              }, () => {
                                const { salaryItemIds } = this.state.modalParam;
                                cacheImportField({
                                  salaryItems: salaryItemIds ? salaryItemIds.split(",") : []
                                }).then();
                              })}
        />
      </div>
    );
  }
}
