package com.emato.ich.fragment;

import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;

import com.emato.ich.contant.SystemConfigConstant;
import com.emato.ich.utils.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

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.contant.ICSPConstant;
import com.emato.ich.contant.DecisionConstant;
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.NavUtils;
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 java.lang.reflect.Field;

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;
    private long start;

    @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) {
        start = System.currentTimeMillis();
        binding = FragmentExceptionBinding.inflate(inflater, container, false);
        return binding.getRoot();
    }


    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        long end = System.currentTimeMillis();
        Log.i(TAG, TAG + "页面渲染速度为" + (end - start) + "ms。");
//        ColorConstant.setButtonColor(binding.returnBtn, ColorConstant.RETURN_BUTTON_BG_COLOR);
        try {
            MainActivity activity = (MainActivity) getActivity();
            timer = TimeOutUtils.timeout(activity, ExceptionFragment.this, binding.timeout, 90);
            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(InputInfoKeyBoardFragment.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);
            if (null != timer) {
                timer.cancel();
            }
            NavUtils.navigate(this, R.id.action_exceptionFragment_to_ChooseCabinetFragment);
        });
        // 门没开换柜门
        binding.issueDoorNotOpen.setOnClickListener(view1 -> {
            if (ButtonUtils.isFastClick()) {
                return;
            }
            handleExceptionScene(finalArguments, DecisionConstant.REOPEN_02, view1);
        });
        // 门没开再开一次
        binding.issueOpenAgain.setOnClickListener(view1 -> {
            if (ButtonUtils.isFastClick()) {
                return;
            }
            handleExceptionScene(finalArguments, DecisionConstant.REOPEN_03, view1);
        });
        // 未投递 取消
        binding.issueCancel.setOnClickListener(view1 -> {
            if (ButtonUtils.isFastClick()) {
                return;
            }
            handleExceptionScene(finalArguments, DecisionConstant.CANCEL_11, view1);
        });
        // 拿出快递 取消
        binding.issueTakeCancel.setOnClickListener(view1 -> {
            if (ButtonUtils.isFastClick()) {
                return;
            }
            handleExceptionScene(finalArguments, DecisionConstant.CANCEL_12, view1);
        });

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

    private void handleExceptionScene(Bundle bundle, String decision, 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站通")
        AlertDialog alertDialog = builder.setTitle("温馨提示")
                //.setMessage("点击按钮会执行相应操作! 本次投递只能使用一次! ")
                .setMessage("点击按钮会执行相应操作! \n本次投递只能使用一次! \n确定执行吗？")
                //.setPositiveButton("是", (dialog, which) -> {
                .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);
                        confirmOrderVo.setDecision(decision);

                        // 禁用按钮
                        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(ICSPConstant.OK)) {
                                                    String code = responseData.getCode();
                                                    Object data = responseData.getData();
                                                    Log.i(TAG, "onResponse: 响应码: " + code + ", 响应消息: " + responseData.getMsg());
                                                    switch (decision) {
                                                        case DecisionConstant.CANCEL_11:
                                                            // 未投递 取消
                                                        case DecisionConstant.CANCEL_12:
                                                            // 拿出快递 取消
                                                            if (null != timer) {
                                                                timer.cancel();
                                                            }
                                                            NavUtils.navigate(ExceptionFragment.this, R.id.action_exceptionFragment_to_sendSuccessFragment);
                                                            break;
                                                        case DecisionConstant.REOPEN_01:
                                                            // 大小不合适

                                                            break;
                                                        case DecisionConstant.REOPEN_02:
                                                            // 门没开换柜门
                                                            // 更新柜门信息 跳转到成功页面
                                                            // 响应信息
                                                            if (responseData.getCode().equals(ICSPConstant.OK)) {
                                                                bundle.putString("preparedOrderResponse", objectMapper.writeValueAsString(data));

                                                                // 跳转到确认投递
                                                                try {
//                                                                    MainActivity activity = (MainActivity) getActivity();
//                                                                    activity.getBundleMap().put(InputInfoKeyBoardFragment.class.getName(), bundle);
                                                                } catch (RuntimeException e) {
                                                                    Log.e(TAG, "onResponse: InputInfoFragment页面获取SendInfoConfirmFragment传值错误! ", e);
                                                                    LoggingUtils.sendErrorLog("业务异常: InputInfoFragment页面获取SendInfoConfirmFragment传值错误! ", e);
                                                                }
                                                                if (null != timer) {
                                                                    timer.cancel();
                                                                }
                                                                NavUtils.navigate(ExceptionFragment.this, R.id.action_InputInfoKeyBoardFragment_to_sendInfoConfirmFragment);
                                                            }
                                                            break;
                                                        case DecisionConstant.REOPEN_03:
                                                            // 门没开再开一次

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

                    } catch (JsonProcessingException e) {
                        Log.e(TAG, "handleExceptionScene: 解析订单数据失败!", e);
                        LoggingUtils.sendErrorLog("业务异常: 异常页面解析订单数据失败! ", e);
                    }
                })
                //.setNegativeButton("否", (dialog, which) -> {
                .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();
        alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setBackgroundColor(0xFF00A0D7);
        alertDialog.getButton(android.app.AlertDialog.BUTTON_POSITIVE).setTextColor(Color.WHITE);
        alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextSize(20);
        alertDialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextSize(20);
        try {
            //获取mAlert对象
            Field mAlert = AlertDialog.class.getDeclaredField("mAlert");
            mAlert.setAccessible(true);
            Object mAlertController = mAlert.get(alertDialog);
            //获取mTitleView并设置大小颜色
            Field mTitle = mAlertController.getClass().getDeclaredField("mTitleView");
            mTitle.setAccessible(true);
            TextView mTitleView = (TextView) mTitle.get(mAlertController);
            mTitleView.setTextSize(25);
            mTitleView.setTextColor(0xFF00A0D7);
            //获取mMessageView并设置大小颜色
            Field mMessage = mAlertController.getClass().getDeclaredField("mMessageView");
            mMessage.setAccessible(true);
            TextView mMessageView = (TextView) mMessage.get(mAlertController);
            mMessageView.setTextSize(18);
            mMessageView.setTextColor(Color.BLACK);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
    }

    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() {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        super.onDestroy();
        binding = null;
        Log.i(TAG, TAG + "被销毁。。。");
    }


}
