/*
 * Author: 黎永顺
 * name: 个税查看详情页面
 * Description:
 * Date: 2023/8/18
 */
import React, { Component } from "react";
import { WeaLeftRightLayout, WeaLocaleProvider, WeaTab } from "ecCom";
import { Button, message, Modal, Spin } from "antd";
import TaxDeclarationInfo from "./components/taxDeclarationInfo";
import { apiflowBillingConfigStatus } from "../../apis/intelligentCalculateSalarySettings";
import PaymentBtn from "./components/paymentBtn";
import PaymentFeedbackBtn from "./components/paymentFeedbackBtn";
import {
  deleteInfo,
  deleteTaxDeclaration,
  exportGetDeclareTaxResultFeedback,
  getDeclareInfo,
  getDetailList,
  getTaxDeclarationTab,
  taxdeclaratioGetCancelFeedback,
  taxdeclarationDeclare,
  taxdeclarationGetDeclareFeedback,
  taxdeclarationGetRate,
  taxdeclarationRefreshData,
  taxdeclaratioUpdateCancel,
  taxdeclaratioUpdateDeclare,
  taxPaymentVoucherStatusSync
} from "../../apis/declare";
import { convertToUrlString, getQueryString } from "../../util/url";
import IncomeTaxDeclarationPersonnelSlide from "./components/incomeTaxDeclarationPersonnelSlide";
import TaxDeclareDetailImportDialog from "./components/taxDeclareDetailImportDialog";
import TabEditDialog from "./components/tabEditDialog";
import LeftTab from "./components/leftTab";
import { confirmDialog } from "./confirm";
import { appendixFields } from "./components/constants";
import "./index.less";
import TaxSetDialog from "../dataAcquisition/otherDeduct/taxSetDialog";

const { getLabel } = WeaLocaleProvider;

const APIFox = {
  refresh: taxdeclarationRefreshData, //刷新数据
  declare: taxdeclarationDeclare, //在线申报
  feedback: taxdeclarationGetDeclareFeedback,//申报反馈
  correct: taxdeclaratioUpdateDeclare,//更正申报
  cancel: taxdeclaratioUpdateCancel,//作废申报
  cancelFeedback: taxdeclaratioGetCancelFeedback//作废反馈
};

class Index extends Component {
  constructor(props) {
    super(props);
    this.state = {
      tabs: [], selectedKey: "", columns: [], dataSource: [], editTabVisible: false, keyword: "",
      loading: {
        query: false, refresh: false, declare: false, feedback: false,
        correct: false, cancel: false, cancelFeedback: false, refreshingPay: false,
        issuance: false
      },
      taxDecPersonSlide: {
        visible: false, title: getLabel(1421, "新增"), taxDeclarationId: "", id: ""
      },
      intelCalcSalaryStatus: false, //智能算薪 总开关是否开启
      declareInfo: {}, pageInfo: { current: 0, pageSize: 10, total: 0 },
      reportType: "", showLeft: false,
      taxSetDialog: { visible: false, dataType: "", viewParams: {} }//查看附表
    };
    this.timer = null;
    this.taxDeclareRef = null;
  }

  componentDidMount() {
    window.addEventListener("message", this.handleReceive, false);
  }

  componentWillUnmount() {
    window.removeEventListener("message", this.handleReceive, false);
  }

  init = async (isInit = true) => {
    const [tabsResult, infoResult, calcResult] = await Promise.all([
      this.getTaxDeclarationTab(), this.getDeclareInfo(), this.apiflowBillingConfigStatus()]);
    const { data: tabDataSource, status: tabStatus } = tabsResult;
    const { data: infoDataSource, status: infoStatus } = infoResult;
    const { data: calcSalaryStatus, status: calcStatus } = calcResult;
    this.setState({
      tabs: tabStatus ? _.map(tabDataSource, it => ({
        viewcondition: `${it.incomeCategory}%%${it.taxDeclarationId}`,
        title: it.tabName, editable: true
      })) : this.state.tabs,
      selectedKey: (tabStatus && isInit) ?
        `${_.first(tabDataSource).incomeCategory}%%${_.first(tabDataSource).taxDeclarationId}` :
        `${_.last(tabDataSource).incomeCategory}%%${_.last(tabDataSource).taxDeclarationId}`,
      declareInfo: infoStatus ? infoDataSource : this.state.declareInfo,
      intelCalcSalaryStatus: calcStatus && calcSalaryStatus
    });
    this.getDetailList();
  };
  declare = async () => {
    const [infoResult] = await Promise.all([this.getDeclareInfo()]);
    const { data: infoDataSource, status: infoStatus } = infoResult;
    this.setState({
      declareInfo: infoStatus ? infoDataSource : this.state.declareInfo
    });
    this.getDetailList();
  };
  getTaxDeclarationTab = () => {
    const { reportType } = this.state;
    return getTaxDeclarationTab({ taxDeclareRecordId: getQueryString("id"), reportType });
  };
  getDeclareInfo = () => {
    const { reportType } = this.state;
    return getDeclareInfo({ taxDeclareRecordId: getQueryString("id"), reportType });
  };
  apiflowBillingConfigStatus = () => {
    return apiflowBillingConfigStatus();
  };
  taxdeclarationGetRate = (index) => {
    return taxdeclarationGetRate({ index });
  };
  handleReceive = ({ data }) => {
    const { type, payload: { id, params } = {} } = data;
    if (type === "init") {
      const promise = this.init();
    } else if (type === "turn") {
      if (id === "PAGEINFO") {
        this.setState({ pageInfo: { ...this.state.pageInfo, ...params } }, () => this.getDetailList());
      } else if (id === "EDIT") {
        this.handleTaxDescPerSlide({
          visible: true, id: params.id,
          title: getLabel(501169, "编辑")
        });
      } else if (id === "DELETE") {
        Modal.confirm({
          title: getLabel(131329, "信息确认"),
          content: getLabel(543548, "确认删除吗？"),
          onOk: () => {
            deleteInfo({ id: params.id }).then(({ status, errormsg }) => {
              if (status) {
                message.success(getLabel(502230, "删除成功！"));
                this.getDetailList();
              } else {
                message.error(errormsg || getLabel(20462, "删除失败！"));
              }
            });
          }
        });
      } else if (id === "APPENDIX") {
        const { taxAgentId, taxCycle } = this.state.declareInfo;
        this.setState({
          taxSetDialog: {
            visible: true, viewParams: { employeeId: params.employeeId, taxAgentId, taxCycle: taxCycle + "-01" },
            dataType: _.find(appendixFields, o => o.dataIndex === params.dataIndex).dataType,
            label: params.title
          }
        });
      }
    }
  };
  postMessageToChild = (payload = {}) => {
    const { declareInfo, intelCalcSalaryStatus } = this.state;
    const i18n = {
      "总计": getLabel(523, "总计"), "编辑": getLabel(501169, "编辑"),
      "操作": getLabel(30585, "操作"), "共": getLabel(83698, "共"),
      "条": getLabel(18256, "条"), "删除": getLabel(535052, "删除"),
      "查看附表": getLabel(111, "查看附表")
    };
    const declareStatus = intelCalcSalaryStatus ? declareInfo.declareStatus : "";
    const childFrameObj = document.getElementById("atdTable");
    childFrameObj && childFrameObj.contentWindow.postMessage(JSON.stringify({ ...payload, i18n, declareStatus }), "*");
  };
  getDetailList = () => {
    const { loading, pageInfo, selectedKey, keyword } = this.state;
    const [incomeCategory, taxDeclarationId] = selectedKey.split("%%");
    const payload = {
      ...pageInfo, incomeCategory, taxDeclarationId, keyword,
      taxDeclareRecordId: getQueryString("id")
    };
    this.setState({ loading: { ...loading, query: true } });
    getDetailList(payload).then(({ status, data }) => {
      this.setState({ loading: { ...loading, query: false } });
      if (status) {
        const { columns, list: dataSource, pageNum: current, pageSize, total } = data;
        this.setState({
          dataSource, pageInfo: { ...pageInfo, current, pageSize, total },
          columns: _.map(columns, (it, idx) => {
            if (idx <= 1) {
              return { ...it, width: 150, fixed: "left", ellipsis: true };
            }
            return {
              ...it, width: 150, ellipsis: true,
              isAppendix: _.findIndex(appendixFields, o => o.dataIndex === it.dataIndex) !== -1
            };
          })
        }, () => {
          const payload = {
            dataSource, pageInfo: this.state.pageInfo,
            columns: this.state.columns
          };
          this.postMessageToChild(payload);
        });
      }
    }).catch(() => this.setState({ loading: { ...loading, query: false } }));
  };
  handleOperateDeclare = (type, params = {}) => {
    const loadingTxt = {
      refresh: getLabel(111, "刷新中..."), //刷新数据
      declare: getLabel(111, "申报中..."), //在线申报
      feedback: getLabel(111, "反馈中..."),//申报反馈
      correct: getLabel(111, "更正申报中..."),//更正申报
      cancel: getLabel(111, "作废申报中..."),//作废申报
      cancelFeedback: getLabel(111, "作废反馈中...")//作废反馈
    }, successTxt = {
      refresh: getLabel(111, "刷新数据成功！"), //刷新数据
      declare: getLabel(111, "在线申报成功！"), //在线申报
      feedback: getLabel(111, "申报反馈成功！"),//申报反馈
      correct: getLabel(111, "更正申报成功！"),//更正申报
      cancel: getLabel(111, "作废申报成功！"),//作废申报
      cancelFeedback: getLabel(111, "作废反馈成功！")//作废反馈
    }, failTxt = {
      refresh: getLabel(111, "刷新数据失败！"), //刷新数据
      declare: getLabel(111, "在线申报失败！"), //在线申报
      feedback: getLabel(111, "申报反馈失败！"),//申报反馈
      correct: getLabel(111, "更正申报失败！"),//更正申报
      cancel: getLabel(111, "作废申报失败！"),//作废申报
      cancelFeedback: getLabel(111, "作废反馈失败！")//作废反馈
    };
    this.setState({ loading: { ...this.state.loading, [type]: true } });
    APIFox[type]({ taxDeclareRecordId: getQueryString("id"), ...params })
      .then(async ({ status, data, errormsg }) => {
        if (status) {
          message.destroy();
          message.loading(loadingTxt[type], 0);
          this.timer = setInterval(async () => {
            const { status: resStatus, data: result } = await this.taxdeclarationGetRate(data);
            const { status: rateStatus, finish, msg } = result;
            if (resStatus && rateStatus) {
              if (finish) {
                this.setState({ loading: { ...this.state.loading, [type]: false } });
                clearInterval(this.timer);
                message.destroy();
                message.success(successTxt[type]);
                const promise = type === "refresh" ? await this.init() : await this.declare();
              }
            } else {
              this.setState({ loading: { ...this.state.loading, [type]: false } });
              clearInterval(this.timer);
              message.destroy();
              message.warning(msg || failTxt[type]);
              const promise = type === "refresh" ? await this.init() : await this.declare();
            }
          }, 1000);
        } else {
          this.setState({ loading: { ...this.state.loading, [type]: false } });
          clearInterval(this.timer);
          message.destroy();
          message.warning(errormsg);
        }
      }).catch(() => {
      message.destroy();
      clearInterval(this.timer);
      this.setState({ loading: { ...this.state.loading, [type]: false } });
    });
  };
  taxPaymentVoucherStatusSync = () => {
    const { taxAgentId, taxCycle: taxYearMonth } = this.state.declareInfo;
    const payload = {
      taxDeclareRecordId: getQueryString("id"),
      taxAgentId, taxYearMonth: taxYearMonth + "-01",
      reportType: this.state.reportType
    };
    this.setState({ loading: { ...this.state.loading, refreshingPay: true } });
    taxPaymentVoucherStatusSync(payload).then(({ status, errormsg }) => {
      this.setState({ loading: { ...this.state.loading, refreshingPay: false } });
      if (status) {
        message.success(getLabel(111, "刷新成功！"));
        const promise = this.declare();
      } else {
        message.error(errormsg || getLabel(111, "刷新失败！"));
      }
    }).catch(() => this.setState({ loading: { ...this.state.loading, refreshingPay: false } }));
  };
  getEnterprisePayCertificate = () => {
    const { taxAgentId, taxCycle: taxYearMonth } = this.state.declareInfo;
    const payload = {
      taxDeclareRecordId: getQueryString("id"),
      taxAgentId, taxYearMonth: taxYearMonth + "-01",
      reportType: this.state.reportType
    };
    window.open(`${window.ecologyContentPath || ""}/spa/hrmSalary/static/index.html#/main/hrmSalary/enterprisePayCertificationDetail?${convertToUrlString(payload)}`);
    // this.setState({ loading: { ...this.state.loading, issuance: true } });
    // taxPaymentWithheldVoucherGet(payload).then(({ status, data, errormsg }) => {
    //   this.setState({ loading: { ...this.state.loading, issuance: false } });
    //   if (status && !_.isEmpty(data.vouchers)) {
    //     window.open(`${window.ecologyContentPath || ""}/spa/hrmSalary/static/index.html#/main/hrmSalary/enterprisePayCertificationDetail?${convertToUrlString(payload)}`);
    //   } else {
    //     message.error(errormsg || "");
    //   }
    // }).catch(() => this.setState({ loading: { ...this.state.loading, issuance: false } }));
  };
  export = () => {
    const [incomeCategory, taxDeclarationId] = this.state.selectedKey.split("%%");
    const payload = {
      taxDeclareRecordId: getQueryString("id"),
      taxDeclarationId: taxDeclarationId.toString(),
      incomeCategory
    };
    window.open(`${window.ecologyContentPath || ""}/api/bs/hrmsalary/taxdeclaration/detail/export?${convertToUrlString(payload)}`, "_blank");
  };
  handleTaxDescPerSlide = (params) => {
    const { callback, ...extra } = params;
    const { taxDecPersonSlide, selectedKey } = this.state;
    const [__, taxDeclarationId] = selectedKey.split("%%");
    this.setState({
      taxDecPersonSlide: { ...taxDecPersonSlide, ...extra, taxDeclarationId }
    }, () => callback && this.getDetailList());
  };
  exportGetDeclareTaxResultFeedback = () => {
    const { reportType } = this.state;
    message.destroy();
    message.loading(getLabel(111, "下载中..."), 0);
    exportGetDeclareTaxResultFeedback({ id: getQueryString("id"), reportType })
      .then(async () => {
        message.destroy();
        message.success(getLabel(111, "下载成功！"));
      }).catch(() => {
      message.destroy();
      message.error(getLabel(111, "下载失败！"));
    });
  };
  onlineComparison = () => {
    const [__, taxDeclarationId] = this.state.selectedKey.split("%%");
    window.open(`${window.location.origin}/spa/hrmSalary/static/index.html#/main/hrmSalary/declareDetail/${taxDeclarationId}`, "_blank");
  };
  handleTabEdit = (tabKey, type) => {
    if (type === "remove") {
      const [__, taxDeclarationId] = tabKey.split("%%");
      Modal.confirm({
        title: getLabel(131329, "信息确认"),
        content: getLabel(111, "确认删除吗?"),
        onOk: () => {
          message.destroy();
          message.loading("正在删除中...", 0);
          deleteTaxDeclaration({ taxDeclarationId })
            .then(({ status, errormsg }) => {
              message.destroy();
              if (status) {
                message.success(getLabel(502230, "删除成功"));
                const promise = this.init();
              } else {
                message.error(errormsg);
              }
            }).catch(() => message.destroy());
        }
      });
    } else if (type === "add") {
      this.setState({ editTabVisible: true });
    }
  };

  render() {
    const {
      tabs, selectedKey, loading, declareInfo, intelCalcSalaryStatus, taxDecPersonSlide,
      editTabVisible, reportType, showLeft, taxSetDialog
    } = this.state;
    const [__, taxDeclarationId] = selectedKey.split("%%");
    let btns = [
      <Button type="primary" onClick={this.export}>{getLabel(17416, "导出")}</Button>,
      <Button type="ghost"
              onClick={() => confirmDialog("declare", () => this.handleOperateDeclare("declare", { reportType }), reportType)}
              loading={loading.declare}>{getLabel(111, "在线申报")}</Button>,
      <Button type="ghost" onClick={() => confirmDialog("refresh", () => this.handleOperateDeclare("refresh"))}
              loading={loading.refresh}>{getLabel(111, "刷新数据")}</Button>
    ];
    //申报状态：作废中
    declareInfo.declareStatus === "DECLARE_CANCELLING" && (btns.splice(1, 2, <Button
      type="ghost" loading={loading.cancelFeedback}
      onClick={() => this.handleOperateDeclare("cancelFeedback")}>{getLabel(111, "作废反馈")}</Button>));
    //申报状态：申报中
    declareInfo.declareStatus === "DECLARING" && (btns.splice(1, 2, <Button
      type="ghost" loading={loading.feedback}
      onClick={() => this.handleOperateDeclare("feedback", { reportType })}>{getLabel(111, "申报反馈")}</Button>));
    //申报状态：缴款中
    declareInfo.declareStatus === "DECLARE_SUCCESS_PAYING" && (btns.splice(1, 2));
    //申报状态：已缴款
    declareInfo.declareStatus === "DECLARE_SUCCESS_PAID" && (btns.splice(1, 2,
      <Button type="ghost" loading={loading.correct}
              onClick={() => confirmDialog("correct", () => this.handleOperateDeclare("correct", { reportType }))}>{getLabel(111, "更正申报")}</Button>));
    //申报状态：申报成功，无需缴款
    declareInfo.declareStatus === "DECLARE_SUCCESS_NO_PAY" &&
    (btns.splice(1, 2,
      <Button type="ghost" loading={loading.correct}
              onClick={() => confirmDialog("correct", () => this.handleOperateDeclare("correct", { reportType }))}>{getLabel(111, "更正申报")}</Button>,
      <Button type="ghost"
              loading={loading.cancel}
              onClick={() => confirmDialog("cancel", () => this.handleOperateDeclare("cancel", { reportType }))}>{getLabel(111, "作废申报")}</Button>
    ));
    //申报状态：申报成功，未缴款
    declareInfo.declareStatus === "DECLARE_SUCCESS_UNPAID" &&
    (btns.splice(1, 2,
      <Button type="ghost" loading={loading.correct}
              onClick={() => confirmDialog("correct", () => this.handleOperateDeclare("correct", { reportType }))}>{getLabel(111, "更正申报")}</Button>,
      <Button type="ghost"
              loading={loading.cancel}
              onClick={() => confirmDialog("cancel", () => this.handleOperateDeclare("cancel", { reportType }))}>{getLabel(111, "作废申报")}</Button>
      // <Button type="ghost"
      //         loading={loading.refreshingPay}
      //         onClick={this.taxPaymentVoucherStatusSync}>{getLabel(111, "刷新缴款状态")}</Button>
    ));
    if (!intelCalcSalaryStatus) {
      if (["NOT_DECLARE", "DECLARE_FAIL"].includes(declareInfo.declareStatus)) {
        btns.splice(1, 1);
      }
    }
    if (intelCalcSalaryStatus) {
      if (["NOT_DECLARE", "DECLARE_FAIL"].includes(declareInfo.declareStatus)) {
        btns.unshift(
          <Button type="primary"
                  onClick={() => this.taxDeclareRef.handleImportTaxDeclare(taxDeclarationId)}>{getLabel(32935, "导入")}</Button>
        );
        btns.unshift(
          <Button type="primary" onClick={() => this.handleTaxDescPerSlide({
            visible: true,
            title: getLabel(1421, "新增")
          })}>{getLabel(1421, "新增")}</Button>
        );
      }
    }
    if (intelCalcSalaryStatus && (declareInfo.declareStatus === "DECLARE_SUCCESS_UNPAID")) {
      btns.push(
        <PaymentBtn declareInfo={declareInfo} updateDeclare={this.declare} reportType={reportType}/>,
        <PaymentFeedbackBtn declareInfo={declareInfo} updateDeclare={this.declare} reportType={reportType}/>
      );
    }
    if (intelCalcSalaryStatus && declareInfo.taxPaidAmount && parseFloat(declareInfo.taxPaidAmount) > 0) {
      btns.push(<Button type="ghost" loading={loading.issuance}
                        onClick={this.getEnterprisePayCertificate}>{getLabel(111, "开具企业完税证明")}</Button>);
    }
    return (
      <WeaLeftRightLayout
        showLeft={showLeft}
        leftWidth={210}
        leftCom={<LeftTab
          onChangeTab={(reportType, isInit = false) => this.setState({ reportType }, () => isInit && this.init())}
          onCollapse={showLeft => this.setState({ showLeft })}/>}
        onCollapse={showLeft => this.setState({ showLeft })}>
        <div className="declareDetail-layout">
          <TaxDeclarationInfo declareInfo={declareInfo} onOperate={fun => this[fun]()}/>
          <div className="declareDetail-layout-content">
            <WeaTab
              datas={tabs} keyParam="viewcondition" selectedKey={selectedKey} showAddBtn buttons={btns}
              type="editable-inline" onEdit={this.handleTabEdit} leftStyle={{ width: "calc(100% - 450px)" }}
              onChange={(v) => this.setState({ selectedKey: v }, () => this.getDetailList())}
              searchType={["base"]} searchsBasePlaceHolder={getLabel(26919, "请输入姓名")}
              onSearchChange={keyword => this.setState({ keyword })}
              onSearch={this.getDetailList}
            />
            {/*个税申报表-新增编辑框*/}
            <IncomeTaxDeclarationPersonnelSlide
              {...taxDecPersonSlide}
              onClose={(callback) => this.handleTaxDescPerSlide({ visible: false, id: "", callback })}
            />
            {/*个税申报表导入*/}
            <TaxDeclareDetailImportDialog ref={dom => this.taxDeclareRef = dom}
                                          onSuccess={this.declare}
            />
            {/*个税申报表-新增tab弹框*/}
            <TabEditDialog visible={editTabVisible}
                           onCancel={(isRefresh) => this.setState({ editTabVisible: false }, () => isRefresh && this.init(false))}/>
          </div>
          {/*查看附表*/}
          <TaxSetDialog {...taxSetDialog}
                        onCancel={() => this.setState({ taxSetDialog: { ...taxSetDialog, visible: false } })}/>
          <div className="declareDetail-layout-table-content">
            <Spin spinning={loading.query}>
              <iframe
                style={{ border: 0, width: "100%", height: "100%" }}
                // src="http://localhost:7607/#/taxDeclareTable"
                src="/spa/hrmSalary/hrmSalaryCalculateDetail/index.html#/taxDeclareTable"
                id="atdTable"
              />
            </Spin>
          </div>
        </div>
      </WeaLeftRightLayout>
    );
  }
}

export default Index;
