/*
  *  薪资项目导入
  *
  * @Author:    黎永顺
  * @Date:      2024/8/7
  * @Wechat:
  * @Email:     971387674@qq.com
  * @description:
*/
import React, { Component } from "react";
import { WeaCheckbox, WeaLoadingGlobal, WeaLocaleProvider } from "ecCom";
import ImportDialog from "../../../components/importDialog";
import * as API from "../../../apis/item";

const getLabel = WeaLocaleProvider.getLabel;

class Index extends Component {
  constructor(props) {
    super(props);
    this.state = {
      importDialog: {
        nextloading: false, link: null, importResult: {}, imageId: "",
        previewUrl: "/api/bs/hrmsalary/salaryitem/preview", hasData: false
      }
    };
  }

  componentWillReceiveProps(nextProps, nextContext) {
    if (nextProps.visible !== this.props.visible && nextProps.visible) {
      this.setState({ importDialog: { ...this.state.importDialog, link: this.handleExportTemp } });
    } else {
      this.setState({
        importDialog: {
          nextloading: false, link: null, importResult: {}, imageId: "",
          previewUrl: "/api/bs/hrmsalary/salaryitem/preview", hasData: false
        }
      });
    }
  }

  handleExportTemp = () => {
    const { importDialog } = this.state;
    const { hasData } = importDialog;
    WeaLoadingGlobal.start();
    const promise = API.downloadTemplate({ hasData });
    WeaLoadingGlobal.destroy();
  };
  handleImport = (payload) => {
    const { importDialog } = this.state, { isExtEmp } = this.props;
    const { extraPreview } = importDialog;
    this.setState({ importDialog: { ...importDialog, nextloading: true } });
    API.importSalaryitem({ ...payload, ...extraPreview, isExtEmp }).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 } }));
  };

  render() {
    const { importDialog } = this.state;
    return (
      <ImportDialog
        {...this.props} {...importDialog}
        onResetImportResult={() => this.setState({
          importDialog: { ...importDialog, importResult: {}, imageId: "", link: null }
        })}
        exportDataDom={
          <WeaCheckbox
            value={importDialog.hasData ? "1" : "0"}
            content={getLabel(543208, "导出现有数据")}
            helpfulTip={getLabel(111, "提示：建议先导出现有最新数据，修改后再导入")}
            onChange={val => {
              this.setState({ importDialog: { ...importDialog, hasData: val === "1" } });
            }}
          />
        }
        nextCallback={imageId => this.setState({ importDialog: { ...importDialog, imageId } })}
        nextUplaodCallback={imageId => this.handleImport({ imageId })}
      />
    );
  }
}

export default Index;
