package com.emato.ich.utils;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.widget.TextView;

import androidx.fragment.app.Fragment;
import androidx.navigation.fragment.NavHostFragment;

import com.emato.ich.MainActivity;
import com.emato.ich.R;
import com.emato.ich.api.ICSPClient;
import com.emato.ich.contant.DecisionConstant;
import com.emato.ich.contant.ICSPConstant;
import com.emato.ich.entity.vo.ConfirmOrderVo;
import com.emato.ich.entity.vo.PreparedOrderResponseVo;
import com.emato.ich.entity.vo.ResponseData;
import com.emato.ich.fragment.ChooseCabinetFragment;
import com.emato.ich.fragment.CollectMaterialsFragment;
import com.emato.ich.fragment.CourierFragment;
import com.emato.ich.fragment.ExceptionFragment;
import com.emato.ich.fragment.ExpressDeliveryFragment;
import com.emato.ich.fragment.InputInfoFragment;
import com.emato.ich.fragment.InputInfoKeyBoardFragment;
import com.emato.ich.fragment.MainFragment;
import com.emato.ich.fragment.PaymentFragment;
import com.emato.ich.fragment.SendFragment;
import com.emato.ich.fragment.SendInfoConfirmFragment;
import com.emato.ich.fragment.SendKeyBoardFragment;
import com.emato.ich.fragment.SendMainFragment;
import com.emato.ich.fragment.SendSuccessFragment;
import com.emato.ich.fragment.TakeCodeFragment;
import com.emato.ich.fragment.TakeFragment;
import com.emato.ich.fragment.TakeSuccessFragment;
import com.emato.ich.local.LocalStorage;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * 页面倒计时工具类
 */
public class TimeOutUtils {
    private static final  String TAG = "超时自动确认投递";
    /**
     * 倒计时
     * @param mainActivity      activity
     * @param fragment          fragment
     * @param textView          倒计时显示的控件
     * @param time              时间
     * @return                  计时器
     */
    public static CountDownTimer timeout(MainActivity mainActivity, Fragment fragment, TextView textView, int time){
        // TODO 需要action 每一个Fragment都需要一个跳转Main的action  需要判断是哪个Fragment
        return new CountDownTimer(time * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                textView.setText(String.valueOf((millisUntilFinished / 1000)));
                if (millisUntilFinished <= 1999) {
                    int fragmentAction = getFragmentAction(mainActivity,fragment);
                    if (fragmentAction != 0) {
                        NavUtils.navigate(fragment, fragmentAction);
                        fragment.onDestroy();
                    }
                }
            }

            @Override
            public void onFinish() {
                int fragmentAction = getFragmentAction(mainActivity,fragment);
                if (fragmentAction != 0) {
                    // 清空session和页面传值, 异常处理有不同处理方式
                    boolean isException = false;
                    if ( LocalStorage.getInstance().getSession().getException() &&
                            (fragment instanceof SendInfoConfirmFragment || fragment instanceof SendSuccessFragment)) {
                        isException = true;
                    }
                    LocalStorage.getInstance().cleanSession(mainActivity, isException);
                    fragment.onDestroy();
                }
            }


        };
    }

    /**
     * 根据Fragment来跳转
     * @param fragment      fragment
     * @return              跳转所对应的action id
     */
    private static int getFragmentAction(MainActivity mainActivity ,Fragment fragment) {

        if (fragment instanceof ChooseCabinetFragment) {
            return R.id.action_chooseCabinetFragment_to_mainFragment;
        } else if (fragment instanceof ExceptionFragment) {
            return R.id.actionExceptionFragment_to_mainFragment;
        } else if (fragment instanceof InputInfoFragment) {
            return R.id.action_InputInfoKeyBoardFragment_to_mainFragment;
        } else if (fragment instanceof InputInfoKeyBoardFragment) {
            return R.id.action_InputInfoKeyBoardFragment_to_mainFragment;
        }else if (fragment instanceof SendFragment) {
            return R.id.action_sendFragment_to_mainFragment;
        } else if (fragment instanceof SendKeyBoardFragment) {
            return R.id.action_sendFragment_to_mainFragment;
        }else if (fragment instanceof SendInfoConfirmFragment) {
            //todo： 在此调用确认投递接口  确认投递后返回首页  待测试
            confirmOrder(mainActivity);
            return R.id.action_sendInfoConfirmFragment_to_mainFragment;
        } else if (fragment instanceof SendMainFragment) {
            return R.id.action_sendMainFragment_to_mainFragment;
        } else if (fragment instanceof SendSuccessFragment) {
            return R.id.action_sendSuccessFragment_to_mainFragment;
        } else if (fragment instanceof TakeCodeFragment) {
            return R.id.action_takeCodeFragment_to_mainFragment;
        } else if (fragment instanceof TakeFragment) {
            return R.id.action_takeFragment_to_mainFragment;
        } else if (fragment instanceof TakeSuccessFragment) {
            return R.id.action_takeSuccessFragment_to_mainFragment;
        } else if (fragment instanceof CourierFragment) {
            return R.id.action_courierFragment_to_mainFragment;
        } else if (fragment instanceof ExpressDeliveryFragment) {
            return R.id.action_expressDeliveryFragment_to_mainFragment;
        } else if (fragment instanceof CollectMaterialsFragment) {
            return R.id.action_collectMaterialsFragment_to_mainFragment;
        } else if (fragment instanceof PaymentFragment) {
            return R.id.action_paymentFragment_to_mainFragment;
        } else if (fragment instanceof MainFragment) {
            return R.id.action_mainFragment_to_screenProtectFragment;
        }
        return 0;
    }

    /**
     * 确认订单
     * @param mainActivity
     */
    private static void confirmOrder(MainActivity mainActivity) {
        Bundle arguments = null;
        MainActivity activity = null;
        try {
            activity = mainActivity;
            arguments = activity.getBundleMap().get(InputInfoKeyBoardFragment.class.getName());
        } catch (RuntimeException e) {
            Log.e(TAG, "onResponse: SendInfoConfirmFragment页面获取InputInfoKeyBoardFragment传值错误! ", e);
            LoggingUtils.sendErrorLog("业务异常: SendInfoConfirmFragment页面获取InputInfoKeyBoardFragment传值错误! ", e);
        }

        String orderSn = null;
        String collectorPhone;
        PreparedOrderResponseVo orderResponseVo;
        String sectionType = null;
        // 设置订单提示属性
        if (null != arguments) {
            try {
                String response = arguments.getString("preparedOrderResponse");
                sectionType = arguments.getString("sectionType");
                orderResponseVo = JacksonUtils.objectmapper.readValue(response, PreparedOrderResponseVo.class);
                collectorPhone = orderResponseVo.getCollectorPhone();
                orderSn = orderResponseVo.getOrderSn();
                           /* binding.openCabinetNo.setText(orderResponseVo.getLockerName());
                            binding.takeNo.setText(arguments.getString("takeNo"));
                            binding.takeNumber.setText(collectorPhone);*/

            } catch (JsonProcessingException e) {
                Log.e(TAG, "onViewCreated: 解析预下单页面传递信息错误! ", e);
                LoggingUtils.sendErrorLog("业务异常: 解析预下单页面传递信息错误! ", e);
            }

        }
        String finalOrderSn = orderSn;
        // TODO 确认投递, 真正下单
        String clientId = BaseUtils.getClientId();
        // /order/deliverer/confirm
        ConfirmOrderVo confirmOrderVo = new ConfirmOrderVo();
        confirmOrderVo.setClientId(clientId);
        confirmOrderVo.setOrderSn(finalOrderSn);
        confirmOrderVo.setDecision(DecisionConstant.CONFIRM_00);
        MainActivity finalActivity = activity;
        ICSPClient.confirmOrder(LocalStorage.getInstance().getSession().getToken(), confirmOrderVo, new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                // TODO 确认失败
//                    getActivity().runOnUiThread(() -> {
//
//                    });
                Log.e(TAG, "onFailure: 确认投递失败! ", e);
                LoggingUtils.sendErrorLog("业务异常: 投递失败！网络异常! ", e);
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                finalActivity.runOnUiThread(() -> {
                    String parseResponse = ICSPClient.isSuccessfulAndParseResponse(response);
                    if (!StringUtils.isNullOrEmpty(parseResponse)) {
                        ObjectMapper objectMapper = JacksonUtils.objectmapper;
                        try {
                            ResponseData responseData = objectMapper.readValue(parseResponse, ResponseData.class);
                            String code = responseData.getCode();
                            if (code.equals(ICSPConstant.OK)) {
                                // TODO 确认投递成功逻辑处理
                            } else {
                                // TODO 确认投递失败逻辑处理
                                ToastUtils.make(null, responseData.getMsg());
                                Log.w(TAG, "onResponse: " + responseData.getMsg());
                            }
                        } catch (JsonProcessingException e) {
                            Log.e(TAG, "onResponse: 确认投递解析响应信息失败!", e);
                            LoggingUtils.sendErrorLog("业务异常: 确认投递解析响应信息失败! ", e);
                        } catch (RuntimeException e) {
                            Log.e(TAG, "onResponse: 投递失败! ", e);
                            LoggingUtils.sendErrorLog("业务异常: 投递失败! 未知异常! ", e);
                        }
                    } else {
                        ToastUtils.make(null, "服务器异常！ 请稍后重试！");
                    }
                });
            }
        });
        // 投递完成后已经是另外一单, 可以继续异常处理
        LocalStorage.getInstance().getSession().setException(true);
    }


}
