package com.emato.ich.fragment;

import android.app.AlertDialog;
import android.graphics.Color;
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 android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
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.FragmentSendInfoConfirmBinding;
import com.emato.ich.entity.vo.ResponseData;
import com.emato.ich.entity.vo.ConfirmOrderVo;
import com.emato.ich.entity.vo.PreparedOrderResponseVo;
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 java.util.Objects;

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

/**
 * 投递信息确认页面
 */
public class SendInfoConfirmFragment extends Fragment {

    private FragmentSendInfoConfirmBinding binding;
    private static final String TAG = SendInfoConfirmFragment.class.getName();
    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 = FragmentSendInfoConfirmBinding.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。");
        // 是否为快递员登录
        boolean isCourierLogin = true;
        try {
            MainActivity activity = (MainActivity) getActivity();
            timer = TimeOutUtils.timeout(activity, SendInfoConfirmFragment.this, binding.timeout, 150);
            timer.start();
        } catch (Exception e) {
            Log.e(TAG, "onViewCreated: 倒计时出现异常! ", e);
            LoggingUtils.sendErrorLog("业务异常: 订单确认页面倒计时出现异常! ", e);
        }

        Bundle arguments = null;
        MainActivity activity = null;
        try {
            activity = (MainActivity) getActivity();
            Bundle mainBundle = activity.getBundleMap().get(MainFragment.class.getName());
            String pageType = mainBundle.getString("pageType");
            // 用户寄送跳转不需要进行登录
            if ("expressDelivery".equals(pageType)){
                arguments = activity.getBundleMap().get(ExpressDeliveryFragment.class.getName());
                isCourierLogin =false;
            }else if ("collectMaterials".equals(pageType)){
                // 快递员跳转需要进行登录
                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;
        boolean finalIsCourierLogin = isCourierLogin;
        binding.alreadySend.setOnClickListener(view1 -> {
            if (ButtonUtils.isFastClick()) {
                return;
            }
            // TODO 确认投递, 真正下单
            String clientId = BaseUtils.getClientId();
            // /order/deliverer/confirm
            ConfirmOrderVo confirmOrderVo = new ConfirmOrderVo();
            confirmOrderVo.setClientId(clientId);
            confirmOrderVo.setOrderSn(finalOrderSn);
            confirmOrderVo.setDecision(DecisionConstant.CONFIRM_00);
            Callback callback = new Callback() {
                @Override
                public void onFailure(@NotNull Call call, @NotNull IOException e) {
                    // TODO 确认失败
//                    getActivity().runOnUiThread(() -> {
//
//                    });
                    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(() -> {
                        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 确认投递成功逻辑处理
                                    ToastUtils.make(getContext(), "投递成功！");
                                    if (null != timer) {
                                        timer.cancel();
                                    }
                                    if (finalIsCourierLogin){
                                        NavUtils.navigate(SendInfoConfirmFragment.this, R.id.action_sendInfoConfirmFragment_to_sendSuccessFragment);
                                    }else {
                                        NavUtils.navigate(SendInfoConfirmFragment.this, R.id.action_sendInfoConfirmFragment_to_mainFragment);
                                    }
                                } else {
                                    // TODO 确认投递失败逻辑处理
                                    ToastUtils.make(getContext(), 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(getContext(), "服务器异常！ 请稍后重试！");
                        }
                    });
                }
            };

            if (finalIsCourierLogin){
                ICSPClient.confirmOrder(LocalStorage.getInstance().getSession().getToken(), confirmOrderVo, callback);
            }else {
                ICSPClient.confirmOrder( confirmOrderVo, callback);
            }
            // 投递完成后已经是另外一单, 可以继续异常处理
            LocalStorage.getInstance().getSession().setException(true);
        });

        // 异常页面跳转
        MainActivity finalActivity = activity;
        binding.exceptionBtn.setOnClickListener(view1 -> {
            if (ButtonUtils.isFastClick()) {
                return;
            }
            Bundle bundle = new Bundle();
            if (null != timer) {
                timer.cancel();
            }
            bundle.putString("exception", "exception_page");
            finalActivity.getBundleMap().put(SendInfoConfirmFragment.class.getName(), bundle);
            NavUtils.navigate(this, R.id.action_sendInfoConfirmFragment_to_exceptionFragment);
        });

        // 未投递按钮
        String finalSectionType = sectionType;
        binding.noneSend.setOnClickListener(view1 -> {
            if (ButtonUtils.isFastClick()) {
                return;
            }
//            Bundle bundle = new Bundle();
//            bundle.putString("exception", "exception_page");
//            finalActivity.getBundleMap().put(SendInfoConfirmFragment.class.getName(), bundle);
            AlertDialog alertDialog = new AlertDialog.Builder(finalActivity)
                    //.setTitle("e站通")
                    .setTitle("温馨提示")
                    //.setMessage("点击未投递会取消本次投递！并且取消投递后的订单状态为预下单！确认取消吗？")
                    .setMessage("点击未投递会取消本次投递！\n并且取消投递后的订单状态为预下单！\n确认取消吗？")
                    .setPositiveButton("确认", (dialog, which) -> {
                        // 是, 取消本次投递
                        ConfirmOrderVo confirmOrderVo = new ConfirmOrderVo();
                        confirmOrderVo.setOrderSn(finalOrderSn);
                        confirmOrderVo.setClientId(BaseUtils.getClientId());
                        confirmOrderVo.setDecision(DecisionConstant.CANCEL_11);
                        confirmOrderVo.setLockerType(finalSectionType);
                        ICSPClient.confirmOrder(LocalStorage.getInstance().getSession().getToken(), confirmOrderVo, new Callback() {
                            @Override
                            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                                Log.e(TAG, "onFailure: 取消投递错误! 网络错误! ", e);
                                LoggingUtils.sendErrorLog("业务异常: 取消投递错误! 网络错误! ", e);
                            }

                            @Override
                            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                                getActivity().runOnUiThread(() -> {
                                    try {
                                        if (null != timer) {
                                            timer.cancel();
                                        }
                                        NavUtils.navigate(SendInfoConfirmFragment.this, R.id.action_sendInfoConfirmFragment_to_sendSuccessFragment);
                                    } catch (Exception e) {

                                    }
                                });
                            }
                        });
                    }).setNegativeButton("取消", (dialog, which) -> {
                        // 否
                        dialog.dismiss();
                    }).create();
            alertDialog.show();
            alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setBackgroundColor(Color.BLUE);
            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(Color.BLUE);
                //获取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();
            }
        });

        binding.mainBtn.setOnClickListener(view1 -> {
            if (ButtonUtils.isFastClick()) {
                return;
            }
            AlertDialog alertDialog = new AlertDialog.Builder(finalActivity)
                    //.setTitle("e站通")
                    .setTitle("温馨提示")
                    //.setMessage("返回主页会取消本次投递！并且本次投递的订单状态为预下单！确认取消吗？")
                    .setMessage("返回主页会取消本次投递！\n并且本次投递的订单状态为预下单！\n确认取消吗？")
                    .setPositiveButton("确认", ((dialog, which) -> {
                        if (null != timer) {
                            timer.cancel();
                        }
                        boolean isException = false;
                        if (LocalStorage.getInstance().getSession().getException()) {
                            isException = true;
                        }
                        LocalStorage.getInstance().cleanSession(((MainActivity) getActivity()), isException);
                        NavUtils.navigate(this, R.id.action_sendInfoConfirmFragment_to_mainFragment);
                    })).setNegativeButton("取消", ((dialog, which) -> {
                        dialog.dismiss();
                    })).create();
            alertDialog.show();
            alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setBackgroundColor(Color.BLUE);
            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(Color.BLUE);
                //获取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();
            }
        });

        binding.backHome.setOnClickListener(view1 -> {
            if (ButtonUtils.isFastClick()) {
                return;
            }
            AlertDialog alertDialog = new AlertDialog.Builder(finalActivity)
                    //.setTitle("e站通")
                    .setTitle("温馨提示")
                    //.setMessage("返回主页会取消本次投递！并且本次投递的订单状态为预下单！确认取消吗？")
                    .setMessage("返回主页会取消本次投递！\n并且本次投递的订单状态为预下单！\n确认取消吗？")
                    .setPositiveButton("确认", ((dialog, which) -> {
                        if (null != timer) {
                            timer.cancel();
                        }
                        boolean isException = false;
                        if (LocalStorage.getInstance().getSession().getException()) {
                            isException = true;
                        }
                        LocalStorage.getInstance().cleanSession(((MainActivity) getActivity()), isException);
                        NavUtils.navigate(this, R.id.action_sendInfoConfirmFragment_to_mainFragment);
                    })).setNegativeButton("取消", ((dialog, which) -> {
                        dialog.dismiss();
                    })).create();
            alertDialog.show();
            alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setBackgroundColor(Color.BLUE);
            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(Color.BLUE);
                //获取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();
            }
        });

    }

    @Override
    public void onDestroy() {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        super.onDestroy();
        binding = null;
        Log.i(TAG, TAG + "被销毁。。。");
    }
}
