/*
 * Author: 黎永顺
 * name: 薪资核算-导入
 * Description:
 * Date: 2023/9/18
 */
import React, { Component } from "react";
import { WeaCheckbox, WeaLocaleProvider } from "ecCom";
import { Badge, Button, message } from "antd";
import ImportDialog from "../../../../../components/importDialog";
import { cacheImportField, getImportField, importAcctResult } from "../../../../../apis/calculate";
import AddHeaderFieldsModal from "../../../../calculateDetail/acctResult/importModal/addHeaderFieldsModal";
import { convertToUrlString, getURLParameters } from "../../../../../util/url";

const getLabel = WeaLocaleProvider.getLabel;

class Index extends Component {
  constructor(props) {
    super(props);
    this.state = {
      salaryItemIds: "", //选择的导入表单项
      exportTempUrl: "", //导出模板url
      headerFieldsDialog: { visible: false, itemsByGroup: [], selectItems: "" },
      importDialog: {
        visible: false, title: "", nextloading: false,
        link: null, importResult: {}, imageId: "",
        previewUrl: "/api/bs/hrmsalary/salaryacct/acctresult/preview",
        extraPreview: { salaryAcctRecordId: "", salaryItemIds: "" }
      }
    };
  }

  async componentWillReceiveProps(nextProps, nextContext) {
    if (nextProps.visible !== this.props.visible) {
      if (nextProps.salaryAcctRecordId && nextProps.visible) {
        const { data } = await getImportField({ salaryAcctRecordId: nextProps.salaryAcctRecordId });
        const { checkItems, itemsByGroup } = data;
        const payload = {
          importType: false, salaryAcctRecordId: nextProps.salaryAcctRecordId,
          salaryItemIds: checkItems.join(",")
        };
        this.setState({
          exportTempUrl: `/api/bs/hrmsalary/salaryacct/acctresult/importtemplate/export?${convertToUrlString(payload)}`,
          importDialog: {
            ...this.state.importDialog,
            extraPreview: { salaryAcctRecordId: nextProps.salaryAcctRecordId, salaryItemIds: checkItems.join(",") }
          },
          headerFieldsDialog: {
            ...this.state.headerFieldsDialog,
            selectItems: checkItems.join(","),
            itemsByGroup: _.map(itemsByGroup, item => {
              return {
                ...item,
                salaryItems: _.map(item.salaryItems, it => ({
                  ...it,
                  checked: false
                }))
              };
            })
          }
        });
      }
      this.setState({
        importDialog: {
          ...this.state.importDialog, link: this.handleExportTemp,
          visible: nextProps.visible, title: nextProps.title, importResult: {}
        }
      });
    }
  }

  handleImport = (payload) => {
    const { headerFieldsDialog: { selectItems: salaryItemIds }, importDialog } = this.state;
    const { salaryAcctRecordId } = this.props;
    this.setState({ importDialog: { ...importDialog, nextloading: true } });
    importAcctResult({ ...payload, salaryItemIds, salaryAcctRecordId })
      .then(({ data, status }) => {
        this.setState({ importDialog: { ...importDialog, nextloading: false } });
        if (status) {
          this.setState({
            importDialog: { ...importDialog, ...payload, importResult: data }
          });
        }
      }).catch(() => this.setState({ importDialog: { ...importDialog, nextloading: false } }));
  };
  handleExportTemp = () => {
    const { headerFieldsDialog: { selectItems }, exportTempUrl } = this.state;
    if (!selectItems) {
      message.error(getLabel(111, "请选择表头字段"));
    } else {
      window.open(exportTempUrl, "_blank");
    }
  };
  handleSelectedField = () => {
    this.setState({
      headerFieldsDialog: {
        ...this.state.headerFieldsDialog, visible: true
      }
    });
  };
  /*
   * Author: 黎永顺
   * Description:表单选项
   * Params:
   * Date: 2023/9/18
   */
  renderFormComponent = () => {
    const { selectItems } = this.state.headerFieldsDialog;
    return <div style={{ padding: "8px 16px", border: "1px solid #e5e5e5", margin: "4px 0" }}>
      <Badge
        count={!_.isEmpty(selectItems) ? selectItems.split(",").length : 0}>
        <Button onClick={this.handleSelectedField}>{getLabel(111, "请选择表头字段")}</Button>
      </Badge>
    </div>;
  };

  render() {
    const { importDialog, headerFieldsDialog, exportTempUrl } = this.state;
    const { salaryAcctRecordId } = this.props;
    return (
      <React.Fragment>
        <ImportDialog
          {...importDialog} onCancel={this.props.onCancel}
          importParams={this.renderFormComponent()}
          onResetImportResult={() => this.setState(({
            importDialog: { ...importDialog, importResult: {}, imageId: "" }
          }))}
          exportDataDom={
            <WeaCheckbox
              content={getLabel(543208, "导出现有数据")}
              value={getURLParameters(exportTempUrl).importType === "true" ? "1" : "0"}
              helpfulTip={getLabel(111, "提示：建议先导出现有最新数据，修改后再导入")}
              onChange={val => {
                const payload = {
                  importType: val === "1", salaryAcctRecordId,
                  salaryItemIds: headerFieldsDialog.selectItems
                };
                this.setState(({
                  exportTempUrl: `/api/bs/hrmsalary/salaryacct/acctresult/importtemplate/export?${convertToUrlString(payload)}`
                }));
              }}
            />
          }
          nextCallback={imageId => this.setState({ importDialog: { ...importDialog, imageId } })}
          nextUplaodCallback={imageId => this.handleImport({ imageId })}
        />
        <AddHeaderFieldsModal
          {...headerFieldsDialog}
          onCancel={() => this.setState({
            headerFieldsDialog: { ...headerFieldsDialog, visible: false }
          })}
          onAdd={selectItems => this.setState({
            headerFieldsDialog: {
              ...headerFieldsDialog,
              visible: false, selectItems: selectItems.join(",")
            }
          }, () => {
            const { selectItems: salaryItems } = this.state.headerFieldsDialog;
            cacheImportField({ salaryAcctRecordId, salaryItemIds: salaryItems ? salaryItems.split(",") : [] })
              .then(({ status, errormsg }) => {
                if (status) {
                  const payload = {
                    importType: getURLParameters(exportTempUrl).importType,
                    salaryAcctRecordId, salaryItemIds: salaryItems
                  };
                  this.setState(({
                    exportTempUrl: `/api/bs/hrmsalary/salaryacct/acctresult/importtemplate/export?${convertToUrlString(payload)}`
                  }));
                } else {
                  message.error(errormsg);
                }
              });
          })}
        />
      </React.Fragment>
    );
  }
}

export default Index;
