/*
 * Author: 黎永顺
 * name: 在线申报-缴款按钮
 * Description:
 * Date: 2023/8/22
 */
import React, { Component } from "react";
import { WeaLoadingGlobal, WeaLocaleProvider } from "ecCom";
import { inject, observer } from "mobx-react";
import { Button, message, Modal } from "antd";
import PaymentDialog from "./paymentDialog";
import {
  taxPaymentAgreemenPay,
  taxPaymentgetAgreement,
  taxPaymentgetAgreementFeedback,
  taxPaymentTaxAmount,
  taxPaymentVoucherCancel,
  taxPaymentVoucherPrint
} from "../../../apis/declare";
import { getQueryString } from "../../../util/url";
import { paymentBankConditions, paymentTripartiteConditions } from "./constants";

const { getLabel } = WeaLocaleProvider;

@inject("declareStore")
@observer
class PaymentBtn extends Component {
  constructor(props) {
    super(props);
    this.state = {
      paymentDialog: {
        visible: false, title: "",
        buttons: [], conditions: [],
        taxAmount: ""
      }
    };
    this.timer = null;
  }

  handleTripartiteContributions = () => {
    Modal.confirm({
      title: getLabel(131329, "信息确认"),
      content: <div>
        <div style={{ textAlign: "center" }}>{getLabel(111, "确定要进行三方缴款吗？")}</div>
        <div
          style={{ textAlign: "center" }}>{getLabel(111, "若申请过银行缴款，点击确定，将自动作废银行缴款凭证。并进行三方缴款。 ")}</div>
      </div>,
      onOk: () => {
        taxPaymentTaxAmount({ taxDeclareRecordId: getQueryString("id"), reportType: this.props.reportType })
          .then(({ status, data, errormsg }) => {
            if (status) {
              const { paymentDialog } = this.state;
              this.setState({
                paymentDialog: {
                  ...paymentDialog, visible: true,
                  title: getLabel(111, "应缴纳"), taxAmount: data.amount,
                  buttons: [
                    <Button type="primary" onClick={this.taxPaymentgetAgreement}>{getLabel(111, "确认缴款")}</Button>
                  ],
                  conditions: _.map(paymentTripartiteConditions, item => {
                    return {
                      ...item,
                      items: _.map(item.items, it => {
                        const key = it["domkey"][0];
                        return {
                          ...it,
                          value: data[key]
                        };
                      })
                    };
                  })
                }
              });
            } else {
              message.error(errormsg);
            }
          });
      }
    });
  };
  taxPaymentgetAgreement = () => {
    const { taxCycle: taxYearMonth, taxAgentId } = this.props.declareInfo;
    const payload = {
      taxDeclareRecordId: getQueryString("id"),
      taxAgentId, taxYearMonth: taxYearMonth + "-01",
      reportType: this.props.reportType
    };
    this.setState({
      paymentDialog: {
        ...this.state.paymentDialog,
        buttons: [
          <Button type="primary" loading={true}>{getLabel(111, "确认缴款")}</Button>
        ]
      }
    });
    taxPaymentgetAgreement(payload).then(({ status, data, errormsg }) => {
      if (status) {
        this.handleCancel();
        this.getBankAccountInfo({ ...payload, requestId: data });
      } else {
        this.setState({
          paymentDialog: {
            ...this.state.paymentDialog,
            buttons: [
              <Button type="primary" onClick={() => this.taxPaymentgetAgreement()}
                      loading={false}>{getLabel(111, "确认缴款")}</Button>
            ]
          }
        });
        message.error(errormsg);
      }
    }).catch(() => {
      this.setState({
        paymentDialog: {
          ...this.state.paymentDialog,
          buttons: [
            <Button type="primary" onClick={() => this.taxPaymentgetAgreement()}
                    loading={false}>{getLabel(111, "确认缴款")}</Button>
          ]
        }
      });
    });
  };
  getBankAccountInfo = (payload) => {
    let loop = () => {
      WeaLoadingGlobal.start({ tip: getLabel(111, "获取三方信息中...") });
      clearTimeout(this.timer);
      this.timer = setTimeout(async () => {
        let response = await taxPaymentgetAgreementFeedback(payload);
        const { data, status, errormsg } = response;
        if (status) {
          const { finish, form } = data;
          if (finish) {
            WeaLoadingGlobal.destroy();
            const { feedbacks, bankForm } = form;
            const { paymentDialog } = this.state;
            this.setState({
              paymentDialog: {
                ...paymentDialog, visible: true,
                title: getLabel(111, "银行账号信息"),
                buttons: [
                  <Button type="primary" onClick={this.taxPaymentAgreemenPay}>{getLabel(826, "确定")}</Button>
                ],
                conditions: _.map(paymentBankConditions, item => {
                  return {
                    ...item,
                    items: _.map(item.items, it => {
                      const key = it["domkey"][0];
                      if (key === "protocolNumber") {
                        return {
                          ...it,
                          value: !_.isEmpty(bankForm) ? bankForm.bank : "",
                          options: _.map(feedbacks, o => ({ key: o.sfxyh, showname: o.yhhbmc }))
                        };
                      } else if (key === "count") {
                        return {
                          ...it,
                          value: !_.isEmpty(bankForm) ? bankForm.bank : "",
                          options: _.map(feedbacks, o => ({ key: o.sfxyh, showname: o.khhhh }))
                        };
                      } else if (key === "paymentNumber") {
                        return {
                          ...it,
                          value: !_.isEmpty(bankForm) ? bankForm.bank : "",
                          options: _.map(feedbacks, o => ({ key: o.sfxyh, showname: o.jkzh }))
                        };
                      }
                      return { ...it };
                    })
                  };
                })
              }
            });
          } else {
            loop();
          }
        } else {
          message.warning(errormsg);
          clearTimeout(this.timer);
          WeaLoadingGlobal.destroy();
        }
      }, 800);
    };
    loop();
  };
  taxPaymentAgreemenPay = () => {
    const { paymentDialog } = this.state;
    const { taxAmount } = paymentDialog;
    const { declareStore: { paymentForm }, reportType } = this.props;
    const { taxCycle: taxYearMonth, taxAgentId } = this.props.declareInfo;
    paymentForm.validateForm().then(f => {
      if (f.isValid) {
        const { protocolNumber, paymentNumber } = paymentForm.getFormDatas();
        const payload = {
          taxDeclareRecordId: getQueryString("id"),
          taxYearMonth: taxYearMonth + "-01",
          taxAgentId, taxAmount, protocolNumber: protocolNumber.value,
          reportType, paymentNumber: paymentNumber.valueSpan
        };
        this.setState({
          paymentDialog: {
            ...this.state.paymentDialog,
            buttons: [
              <Button type="primary" loading={true}>{getLabel(826, "确定")}</Button>
            ]
          }
        });
        taxPaymentAgreemenPay(payload).then(({ status, errormsg }) => {
          this.setState({
            paymentDialog: {
              ...this.state.paymentDialog,
              buttons: [
                <Button type="primary" loading={false}
                        onClick={this.taxPaymentAgreemenPay}>{getLabel(826, "确定")}</Button>
              ]
            }
          });
          if (status) {
            message.success(getLabel(111, "缴款处理中，请稍后点击缴款反馈按钮获取缴款信息"));
            this.handleCancel();
          } else {
            message.error(errormsg);
          }
        }).catch(() => this.setState({
          paymentDialog: {
            ...this.state.paymentDialog,
            buttons: [
              <Button type="primary" loading={false}
                      onClick={this.taxPaymentAgreemenPay}>{getLabel(826, "确定")}</Button>
            ]
          }
        }));
      } else {
        f.showErrors();
      }
    });
  };
  handleMenuChange = ({ key }) => {
    if (key === "bank_voucher_payment") {
      taxPaymentTaxAmount({ taxDeclareRecordId: getQueryString("id"), reportType: this.props.reportType })
        .then(({ status, data, errormsg }) => {
          if (status) {
            const { paymentDialog } = this.state;
            this.setState({
              paymentDialog: {
                ...paymentDialog, visible: true, title: getLabel(111, "应缴纳"),
                buttons: [
                  <Button type="primary" onClick={this.taxPaymentVoucherPrint}>{getLabel(111, "确认缴款")}</Button>
                ],
                conditions: _.map(paymentTripartiteConditions, item => {
                  return {
                    ...item,
                    items: _.map(item.items, it => {
                      const key = it["domkey"][0];
                      return {
                        ...it,
                        value: data[key]
                      };
                    })
                  };
                })
              }
            });
          } else {
            message.error(errormsg);
          }
        });
    } else if (key === "destory_voucher") {
      Modal.confirm({
        title: getLabel(131329, "信息确认"),
        content: getLabel(111, "确定作废缴款凭证吗？作废后可重新获取。"),
        onOk: () => {
          const { taxAgentId, taxCycle: taxYearMonth } = this.props.declareInfo;
          const payload = {
            taxDeclareRecordId: getQueryString("id"),
            taxAgentId, taxYearMonth: taxYearMonth + "-01",
            reportType: this.props.reportType
          };
          taxPaymentVoucherCancel(payload).then(({ status, errormsg }) => {
            if (status) {
              message.success(getLabel(111, "作废缴款凭证成功！"));
            } else {
              message.error(errormsg || getLabel(111, "作废失败！"));
            }
          });
        }
      });
    }
  };
  taxPaymentVoucherPrint = () => {
    const { taxCycle: taxYearMonth, taxAgentId } = this.props.declareInfo;
    const payload = {
      taxDeclareRecordId: getQueryString("id"),
      taxAgentId, taxYearMonth: taxYearMonth + "-01"
    };
    this.setState({
      paymentDialog: {
        ...this.state.paymentDialog,
        buttons: [
          <Button type="primary" loading={true}>{getLabel(111, "确认缴款")}</Button>
        ]
      }
    });
    taxPaymentVoucherPrint(payload).then(({ status, errormsg }) => {
      if (status) {
        message.success(getLabel(111, "处理中，请稍后点击缴款反馈！"));
        this.handleCancel();
      } else {
        this.setState({
          paymentDialog: {
            ...this.state.paymentDialog,
            buttons: [
              <Button type="primary" onClick={() => this.taxPaymentVoucherPrint()}
                      loading={false}>{getLabel(111, "确认缴款")}</Button>
            ]
          }
        });
        message.error(errormsg || getLabel(111, "缴款反馈失败！"));
      }
    }).catch(() => {
      this.setState({
        paymentDialog: {
          ...this.state.paymentDialog,
          buttons: [
            <Button type="primary" onClick={() => this.taxPaymentVoucherPrint()}
                    loading={false}>{getLabel(111, "确认缴款")}</Button>
          ]
        }
      });
    });
  };
  handleCancel = () => {
    const { paymentDialog } = this.state;
    this.setState({
      paymentDialog: {
        ...paymentDialog, visible: false,
        title: "", buttons: [], conditions: []
      }
    });
  };

  render() {
    const { paymentDialog } = this.state;
    return (
      <React.Fragment>
        <Button type="ghost" onClick={this.handleTripartiteContributions}>{getLabel(111, "三方缴款")}</Button>
        {/*<Dropdown.Button*/}
        {/*  onClick={this.handleTripartiteContributions}*/}
        {/*  overlay={*/}
        {/*    <Menu onClick={this.handleMenuChange}>*/}
        {/*      <Menu.Item key="bank_voucher_payment">{getLabel(111, "银行端凭证缴款")}</Menu.Item>*/}
        {/*      <Menu.Item key="destory_voucher">{getLabel(111, "作废缴款凭证")}</Menu.Item>*/}
        {/*    </Menu>*/}
        {/*  }*/}
        {/*  type="ghost">{getLabel(111, "三方缴款")}</Dropdown.Button>*/}
        <PaymentDialog
          {...paymentDialog}
          onCancel={this.handleCancel}
        />
      </React.Fragment>
    );
  }
}

export default PaymentBtn;
