package com.emato.ich.fragment;

import android.os.Bundle;
import android.os.CountDownTimer;
import com.emato.ich.utils.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
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.api.ICSPResponseCodeEnum;
import com.emato.ich.contant.DecisionEnum;
import com.emato.ich.databinding.FragmentExceptionBinding;
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.local.LocalStorage;
import com.emato.ich.utils.BaseUtils;
import com.emato.ich.utils.ButtonUtils;
import com.emato.ich.utils.JacksonUtils;
import com.emato.ich.utils.LoggingUtils;
import com.emato.ich.utils.StringUtils;
import com.emato.ich.utils.TimeOutUtils;
import com.emato.ich.utils.ToastUtils;
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 ExceptionFragment extends Fragment {

    private static final String TAG = ExceptionFragment.class.getName();
    private FragmentExceptionBinding binding;
    private CountDownTimer timer;

    @Nullable
    @org.jetbrains.annotations.Nullable
    @Override
    public View onCreateView(@NonNull @NotNull LayoutInflater inflater, @Nullable @org.jetbrains.annotations.Nullable ViewGroup container, @Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {

        binding = FragmentExceptionBinding.inflate(inflater, container, false);
        return binding.getRoot();
    }


    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
//        ColorConstant.setButtonColor(binding.returnBtn, ColorConstant.RETURN_BUTTON_BG_COLOR);
        try {
            MainActivity activity = (MainActivity) getActivity();
            timer = TimeOutUtils.timeout(activity, ExceptionFragment.this, binding.timeout, 60);
            timer.start();
        } catch (Exception e) {
            Log.e(TAG, "onViewCreated: 倒计时出现异常! ", e);
            LoggingUtils.sendErrorLog("业务异常: 异常处理页面倒计时出现异常! ", e);
        }

        if (!LocalStorage.getInstance().getSession().getException()) {
            disableButton();
        }

        Bundle arguments = null;
        MainActivity activity = null;
        try {
            activity = (MainActivity) getActivity();
            arguments = activity.getBundleMap().get(InputInfoFragment.class.getName());
        } catch (RuntimeException e) {
            Log.e(TAG, "onViewCreated: InputInfoFragment向ExceptionFragment页面传值错误! ", e);
            LoggingUtils.sendErrorLog("业务异常: InputInfoFragment向ExceptionFragment页面传值错误! ", e);
        }

        // 异常处理, 调下单接口,
        // 大小不合适
        Bundle finalArguments = arguments;
        binding.issueSize.setOnClickListener(view1 -> {
            if (ButtonUtils.isFastClick()) {
                return;
            }
            MainActivity activity1 = (MainActivity) getActivity();
            Bundle bundle = new Bundle();
            bundle.putString("exception", "change_cabinet");
            activity1.getBundleMap().put(ExceptionFragment.class.getName(), bundle);
            timer.cancel();
            NavHostFragment.findNavController(ExceptionFragment.this).navigate(R.id.action_exceptionFragment_to_ChooseCabinetFragment);
        });
        // 门没开换柜门
        binding.issueDoorNotOpen.setOnClickListener(view1 -> {
            if (ButtonUtils.isFastClick()) {
                return;
            }
            handleExceptionScene(finalArguments, DecisionEnum.REOPEN_02, view1);
        });
        // 门没开再开一次
        binding.issueOpenAgain.setOnClickListener(view1 -> {
            if (ButtonUtils.isFastClick()) {
                return;
            }
            handleExceptionScene(finalArguments, DecisionEnum.REOPEN_03, view1);
        });
        // 未投递 取消
        binding.issueCancel.setOnClickListener(view1 -> {
            if (ButtonUtils.isFastClick()) {
                return;
            }
            handleExceptionScene(finalArguments, DecisionEnum.CANCEL_11, view1);
        });
        // 拿出快递 取消
        binding.issueTakeCancel.setOnClickListener(view1 -> {
            if (ButtonUtils.isFastClick()) {
                return;
            }
            handleExceptionScene(finalArguments, DecisionEnum.CANCEL_12, view1);
        });

        // 联系我们
        binding.issueOther.setOnClickListener(view1 -> {
            if (ButtonUtils.isFastClick()) {
                return;
            }
            ToastUtils.make(getContext(), "电话: 16274237018! 请说明原由! ");
        });
        MainActivity finalActivity = activity;
        binding.returnBtn.setOnClickListener(view1 -> {
            if (ButtonUtils.isFastClick()) {
                return;
            }
            Bundle bundle = finalActivity.getBundleMap().get(SendInfoConfirmFragment.class.getName());
            timer.cancel();
            if (null != bundle) {
                // 跳转确认投递页面
                finalActivity.getBundleMap().remove(SendInfoConfirmFragment.class.getName());
                NavHostFragment.findNavController(ExceptionFragment.this)
                        .navigate(R.id.action_exceptionFragment_to_sendInfoConfirmMainFragment);
            } else {
                NavHostFragment.findNavController(ExceptionFragment.this)
                        .navigate(R.id.action_exceptionFragment_to_sendMainFragment);
            }
        });
    }

    private void handleExceptionScene(Bundle bundle, DecisionEnum decisionEnum, View view){
        LocalStorage.Session session = LocalStorage.getInstance().getSession();
        if (LocalStorage.getInstance().isExpired(session)) {
            ToastUtils.make(getContext(), "会话已过期! 请重新登录! ");
            return;
        }
        if (null == bundle) {
            ToastUtils.make(getContext(), "没有待提交的投递订单! ");
            return;
        }

        // 异常按钮提示
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        AlertDialog alertDialog = builder.setTitle("e站通")
                .setMessage("点击按钮会执行相应操作! 本次投递只能使用一次! ")
                .setPositiveButton("是", (dialog, which) -> {
                    ObjectMapper objectMapper = JacksonUtils.objectmapper;
                    String response = bundle.getString("preparedOrderResponse");
                    String sectionType = bundle.getString("section_type");
                    try {
                        PreparedOrderResponseVo preparedOrderResponseVo = objectMapper.readValue(response, PreparedOrderResponseVo.class);
                        ConfirmOrderVo confirmOrderVo = new ConfirmOrderVo();
                        confirmOrderVo.setOrderSn(preparedOrderResponseVo.getOrderSn());
                        confirmOrderVo.setClientId(BaseUtils.getClientId());
                        confirmOrderVo.setLockerType(sectionType);
                        switch (decisionEnum) {
                            case CANCEL_11:
                                // 未投递 取消
                                confirmOrderVo.setDecision(DecisionEnum.CANCEL_11.getDecision());
//                                ToastUtils.make(getContext(), "异常处理只能处理一次! 如未处理您的问题! 请联系我们处理! ");
                                break;
                            case CANCEL_12:
                                // 拿出快递 取消
                                confirmOrderVo.setDecision(DecisionEnum.CANCEL_12.getDecision());
                                ToastUtils.make(getContext(), "异常处理只能处理一次! 如未处理您的问题! 请联系我们处理! ");
//                                NavHostFragment.findNavController(ExceptionFragment.this).navigate(R.id.action_exceptionFragment_to_sendSuccessFragment);
                                break;
                            case REOPEN_01:
                                // 大小不合适
                                confirmOrderVo.setDecision(DecisionEnum.REOPEN_01.getDecision());
//                                ToastUtils.make(getContext(), "异常处理只能处理一次! 如未处理您的问题! 请联系我们处理! ");
                                break;
                            case REOPEN_02:
                                // 门没开换柜门
                                confirmOrderVo.setDecision(DecisionEnum.REOPEN_02.getDecision());
//                                ToastUtils.make(getContext(), "异常处理只能处理一次! 如未处理您的问题! 请联系我们处理! ");
                                break;
                            case REOPEN_03:
                                // 门没开再开一次
                                confirmOrderVo.setDecision(DecisionEnum.REOPEN_03.getDecision());
//                                ToastUtils.make(getContext(), "异常处理只能处理一次! 如未处理您的问题! 请联系我们处理! ");
                                break;
                            default:
                                break;
                        }

                        disableButton();

                        ICSPClient.confirmOrder(LocalStorage.getInstance().getSession().getToken(), confirmOrderVo, new Callback() {
                            @Override
                            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                                ToastUtils.make(getContext(), "发送异常处理请求失败！网络异常！");
                                Log.e(TAG, "onFailure: 发送异常处理请求失败! ", e);
                                LoggingUtils.sendErrorLog("业务异常: 发送异常处理请求失败! ", e);
                            }

                            @Override
                            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                                // 场景不同, 处理方式不同
                                getActivity().runOnUiThread(() -> {
                                    ResponseData responseData = null;
                                    try {
                                        String parseResponse = ICSPClient.isSuccessfulAndParseResponse(response);
                                        if (!StringUtils.isNullOrEmpty(parseResponse)) {
                                            try {
                                                responseData = objectMapper.readValue(parseResponse, ResponseData.class);
                                                // TODO 处理异常
                                                if (responseData != null && responseData.getCode().equals(ICSPResponseCodeEnum.OK.getCode())) {
                                                    String code = responseData.getCode();
                                                    Object data = responseData.getData();
                                                    Log.i(TAG, "onResponse: 响应码: " + code + ", 响应消息: " + responseData.getMsg());
                                                    switch (decisionEnum) {
                                                        case CANCEL_11:
                                                            // 未投递 取消
                                                        case CANCEL_12:
                                                            // 拿出快递 取消
                                                            timer.cancel();
                                                            NavHostFragment.findNavController(ExceptionFragment.this)
                                                                    .navigate(R.id.action_exceptionFragment_to_sendSuccessFragment);
                                                            break;
                                                        case REOPEN_01:
                                                            // 大小不合适

                                                            break;
                                                        case REOPEN_02:
                                                            // 门没开换柜门

                                                            break;
                                                        case REOPEN_03:
                                                            // 门没开再开一次

                                                            break;
                                                        default:
                                                            break;
                                                    }
                                                } else {
                                                    ICSPResponseCodeEnum.responseHint(getContext(), responseData);
                                                    Log.w(TAG, "onResponse: " + responseData.getMsg());
                                                }
                                            } catch (JsonProcessingException e) {
                                                Log.e(TAG, "onResponse: 处理异常场景: " + decisionEnum.getMsg() + ", 解析响应信息时出错! ", e);
                                                LoggingUtils.sendErrorLog("业务异常: 处理异常场景: " + decisionEnum.getMsg() + ", 解析响应信息时出错! ", e);
                                            }
                                        } else {
                                            ToastUtils.make(getContext(), "服务器异常！请稍后重试！");
                                        }
                                    } catch (RuntimeException e) {
                                        Log.e(TAG, "onResponse: 处理\"" + decisionEnum.getMsg() + "\"问题时出错! 返回码: " + responseData.getCode() + ", 错误消息: " + responseData.getMsg(), e);
                                        LoggingUtils.sendErrorLog("业务异常: 处理\"" + decisionEnum.getMsg() + "\"问题时出错! 返回码: " + responseData.getCode() + ", 错误消息: " + responseData.getMsg(), e);
                                    }
                                });
                            }
                        });

                    } catch (JsonProcessingException e) {
                        Log.e(TAG, "handleExceptionScene: 解析订单数据失败!", e);
                        LoggingUtils.sendErrorLog("业务异常: 异常页面解析订单数据失败! ", e);
                    }
                })
                .setNegativeButton("否", (dialog, which) -> {
                    LocalStorage.getInstance().getSession().setException(true);
                    binding.issueCancel.setEnabled(true);
                    binding.issueDoorNotOpen.setEnabled(true);
                    binding.issueOpenAgain.setEnabled(true);
                    binding.issueSize.setEnabled(true);
                    binding.issueTakeCancel.setEnabled(true);
                    dialog.dismiss();
                }).create();
        alertDialog.show();

    }

    private void disableButton(){
        LocalStorage.getInstance().getSession().setException(false);
        binding.issueCancel.setEnabled(false);
        binding.issueDoorNotOpen.setEnabled(false);
        binding.issueOpenAgain.setEnabled(false);
        binding.issueSize.setEnabled(false);
        binding.issueTakeCancel.setEnabled(false);
    }

    @Override
    public void onDestroy() {
        timer.cancel();
        super.onDestroy();
        binding = null;
    }


}
