import { useRequest } from 'ahooks';
import { useEffect, useRef } from 'react';
import { locales } from '@pisell/utils';
import { linklyPayCancelApi, linklyPayApi, linklyRefundCancelApi, linklyRefundApi, linklyPaySignatureApi, linklyRefundSignatureApi } from "../service";
import { useFail, useStoreRef } from "../../hooks";
import { ModeEnum, PayStatus, StatusEnum } from "../../const";
import { useDispatch, updateState, updateCustom, updateStatus } from "../../store";
import { LinklyActionStatus } from "../const";
import payLog from "../../utils/payLog";

/**
 * 支付或退款
 * @param failAction 失败回调
 */
export var useLinklyPayOrRefund = function useLinklyPayOrRefund(handleCheck) {
  var dispatch = useDispatch();
  var _useStoreRef = useStoreRef(),
    numRef = _useStoreRef.numRef,
    modeRef = _useStoreRef.modeRef,
    orderIdRef = _useStoreRef.orderIdRef,
    deviceRef = _useStoreRef.deviceRef,
    payRef = _useStoreRef.payRef,
    amountRef = _useStoreRef.amountRef;
  var fail = useFail(0);
  var failRef = useRef(fail);
  var resultQueryRef = useRef(null);
  var handleLinklySuccessRef = useRef(null);
  useEffect(function () {
    failRef.current = fail;
  }, [fail]);
  var isPay = modeRef.current === ModeEnum.Pay || modeRef.current === ModeEnum.FullPay;
  var _pay = useRequest(isPay ? linklyPayApi : linklyRefundApi, {
    manual: true,
    onSuccess: function onSuccess(res) {
      _onSuccess(res);
    },
    onError: function onError(error) {
      _onError(error);

      // TODO: mock数据
      // console.log('mock>>>>>>');
      // const res = {
      //   status: true,
      //   code: 200,
      //   message: '',
      //   data: {
      //     pinpad_id: 3,
      //     is_auto_print: 0,
      //     session_id: '923d4abe-6521-43c8-915b-decde8b406bd',
      //     status: 0,
      //     response_code: '00',
      //     response_text: 'APPROVED',
      //     signature_flag: 0,
      //   },
      // };
      // onSuccess(res, isPay ? 'pay' : 'refund');
    }
  });
  var _onSuccess = function _onSuccess(res) {
    var _res$data;
    console.log("linkly".concat(isPay ? 'Pay' : 'Refund', "Success---->>>>>>>"), res);
    if (!handleCheck()) {
      return;
    }
    payLog.log("Linkly\uFF1A".concat(isPay ? '支付' : '退款', "\u63A5\u53E3\u6210\u529F"), {
      res: res
    });

    // status 交易状态 0:未知，继续查询 1:成功 -1:失败 -2:交易错误
    // signature_flag 是否弹框确认签名 0:不用签名 1:等待签名确认  2:签名取消 3:签名确认
    var status = res === null || res === void 0 || (_res$data = res.data) === null || _res$data === void 0 ? void 0 : _res$data.status;

    // 继续查询交易状态
    if (status == 0) {
      var _res$data2;
      // 交易流水号
      numRef.current = res === null || res === void 0 || (_res$data2 = res.data) === null || _res$data2 === void 0 ? void 0 : _res$data2.session_id;
      dispatch(updateState({
        number: numRef.current
      }));
      // 需要展示取消按钮
      dispatch(updateCustom({
        actionStatus: LinklyActionStatus.Cancel
      }));
      // 调用支付查询接口
      setTimeout(function () {
        var _resultQueryRef$curre;
        (_resultQueryRef$curre = resultQueryRef.current) === null || _resultQueryRef$curre === void 0 || _resultQueryRef$curre.call(resultQueryRef);
      }, 300);
      return;
    }

    // 无需展示取消按钮
    dispatch(updateCustom({
      actionStatus: LinklyActionStatus.Empty
    }));

    // 交易成功
    if (status == 1) {
      var _handleLinklySuccessR;
      (_handleLinklySuccessR = handleLinklySuccessRef.current) === null || _handleLinklySuccessR === void 0 || _handleLinklySuccessR.call(handleLinklySuccessRef, res);
      return;
    }

    // 交易失败
    if (status < 0) {
      var _failRef$current;
      // 需要特殊处理，将code码转换为支付失败code码
      res.code = PayStatus.Unknown;
      (_failRef$current = failRef.current) === null || _failRef$current === void 0 || _failRef$current.call(failRef, res, false);
    }
  };
  var _onError = function _onError(error) {
    var _failRef$current2;
    console.log("linkly".concat(isPay ? 'Pay' : 'Refund', "Error---->>>>>>>"), error);
    // 无网 或 已卸载 则不进行处理
    if (!handleCheck()) {
      return;
    }
    payLog.log("Linkly\uFF1A".concat(isPay ? '支付' : '退款', "\u63A5\u53E3\u5931\u8D25"), {
      error: JSON.stringify(error || {})
    });
    (_failRef$current2 = failRef.current) === null || _failRef$current2 === void 0 || _failRef$current2.call(failRef, error, false);
  };
  var payOrRefund = function payOrRefund(resultQuery, handleLinklySuccess) {
    var _deviceRef$current, _payRef$current;
    handleLinklySuccessRef.current = handleLinklySuccess;
    resultQueryRef.current = resultQuery;
    var param = {
      // 订单id
      order_id: orderIdRef.current,
      // 设备id
      pinpad_id: deviceRef === null || deviceRef === void 0 || (_deviceRef$current = deviceRef.current) === null || _deviceRef$current === void 0 || (_deviceRef$current = _deviceRef$current.metadata) === null || _deviceRef$current === void 0 ? void 0 : _deviceRef$current.linkly_pinpad_id,
      // 交易金额, 包含选择的订单金额+手续费，订单金额+手续费=交易金额
      amount: isPay ? (_payRef$current = payRef.current) === null || _payRef$current === void 0 ? void 0 : _payRef$current.total : amountRef.current
    };
    payLog.setContext({
      transactionNumber: String(orderIdRef.current)
    });
    payLog.log("Linkly\uFF1A\u53D1\u8D77".concat(isPay ? '支付' : '退款'), {
      param: param
    });
    _pay.run(param);
  };
  return {
    action: {
      pay: _pay
    },
    payOrRefund: payOrRefund
  };
};

/**
 * @title: 取消支付或退款
 * @description: 取消支付或退款调用接口后不管成功还是失败都需要调用支付查询接口
 */
export var useLinklyCancel = function useLinklyCancel(handleCheck) {
  var dispatch = useDispatch();
  var _useStoreRef2 = useStoreRef(),
    numRef = _useStoreRef2.numRef,
    modeRef = _useStoreRef2.modeRef,
    deviceRef = _useStoreRef2.deviceRef;
  var resultQueryRef = useRef(null);
  var isPay = modeRef.current === ModeEnum.Pay || modeRef.current === ModeEnum.FullPay;
  var cancelAction = function cancelAction(res, type) {
    var _resultQueryRef$curre2;
    // 需要将按钮状态释放
    dispatch(updateCustom({
      buttonDisabled: false
    }));
    if (!handleCheck()) {
      return;
    }
    payLog.log("Linkly\uFF1A\u53D6\u6D88".concat(type === 'success' ? '成功' : '失败'), {
      res: res
    });
    (_resultQueryRef$curre2 = resultQueryRef.current) === null || _resultQueryRef$curre2 === void 0 || _resultQueryRef$curre2.call(resultQueryRef);
  };
  var _cancel = useRequest(isPay ? linklyPayCancelApi : linklyRefundCancelApi, {
    manual: true,
    onSuccess: function onSuccess(res) {
      return cancelAction(res, 'success');
    },
    onError: function onError(error) {
      return cancelAction(error, 'error');
    }
  });
  var linklyCancel = function linklyCancel(resultQuery) {
    var _deviceRef$current2;
    resultQueryRef.current = resultQuery;
    dispatch(updateCustom({
      buttonDisabled: true
    }));
    var param = {
      pinpad_id: deviceRef === null || deviceRef === void 0 || (_deviceRef$current2 = deviceRef.current) === null || _deviceRef$current2 === void 0 || (_deviceRef$current2 = _deviceRef$current2.metadata) === null || _deviceRef$current2 === void 0 ? void 0 : _deviceRef$current2.linkly_pinpad_id,
      session_id: numRef.current
    };
    payLog.log('Linkly：发起取消', {
      param: param
    });
    _cancel.run(param);
    dispatch(updateCustom({
      actionStatus: LinklyActionStatus.CancelWaiting
    }));
  };
  return {
    action: {
      cancel: _cancel
    },
    linklyCancel: linklyCancel
  };
};

/**
 * @title: 支付或退款签名
 * @description: 支付或退款签名调用接口后不管成功还是失败都需要调用支付查询接口
 */
export var useLinklySignature = function useLinklySignature(handleCheck) {
  var dispatch = useDispatch();
  var _useStoreRef3 = useStoreRef(),
    numRef = _useStoreRef3.numRef,
    modeRef = _useStoreRef3.modeRef,
    deviceRef = _useStoreRef3.deviceRef;
  var resultQueryRef = useRef(null);
  var isPay = modeRef.current === ModeEnum.Pay || modeRef.current === ModeEnum.FullPay;
  var signatureAction = function signatureAction(res, type) {
    var _resultQueryRef$curre3;
    console.log('signatureAction---->>>>>>>', res);
    if (!handleCheck()) {
      return;
    }
    payLog.log("Linkly\uFF1A\u7B7E\u540D\u63A5\u53E3".concat(type === 'success' ? '成功' : '失败'), {
      res: res
    });
    (_resultQueryRef$curre3 = resultQueryRef.current) === null || _resultQueryRef$curre3 === void 0 || _resultQueryRef$curre3.call(resultQueryRef);
  };
  var _signature = useRequest(isPay ? linklyPaySignatureApi : linklyRefundSignatureApi, {
    manual: true,
    onSuccess: function onSuccess(res) {
      return signatureAction(res, 'success');
    },
    onError: function onError(error) {
      return signatureAction(error, 'error');
    }
  });
  var linklySignature = function linklySignature(status, resultQuery) {
    var _deviceRef$current3;
    resultQueryRef.current = resultQuery;
    var param = {
      // 设备id
      pinpad_id: deviceRef === null || deviceRef === void 0 || (_deviceRef$current3 = deviceRef.current) === null || _deviceRef$current3 === void 0 || (_deviceRef$current3 = _deviceRef$current3.metadata) === null || _deviceRef$current3 === void 0 ? void 0 : _deviceRef$current3.linkly_pinpad_id,
      // 交易流水号
      session_id: numRef.current,
      signature_flag: status
    };
    dispatch(updateStatus(StatusEnum.Loading));
    dispatch(updateState({
      title: locales.getText('page.eftpos-pay.text.loading')(modeRef.current)
    }));
    dispatch(updateCustom({
      actionStatus: LinklyActionStatus.SignatureWaiting
    }));
    payLog.log('Linkly：发起签名', {
      param: param
    });
    _signature.run(param);
  };
  return {
    action: {
      signature: _signature
    },
    linklySignature: linklySignature
  };
};