package com.emato.ich.fragment;

import android.app.AlertDialog;
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.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.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.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 SendInfoConfirmFragment extends Fragment {

    private FragmentSendInfoConfirmBinding binding;
    private static final String TAG = SendInfoConfirmFragment.class.getName();
    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 = FragmentSendInfoConfirmBinding.inflate(inflater, container, false);

        return binding.getRoot();
    }

    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {

        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();
            arguments = activity.getBundleMap().get(InputInfoFragment.class.getName());
        } catch (RuntimeException e) {
            Log.e(TAG, "onResponse: SendInfoConfirmFragment页面获取InputInfoFragment传值错误! ", e);
            LoggingUtils.sendErrorLog("业务异常: SendInfoConfirmFragment页面获取InputInfoFragment传值错误! ", 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;
        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(DecisionEnum.CONFIRM_00.getDecision());
            ICSPClient.confirmOrder(LocalStorage.getInstance().getSession().getToken(), confirmOrderVo, 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(ICSPResponseCodeEnum.OK.getCode())) {
                                    // TODO 确认投递成功逻辑处理
                                    ToastUtils.make(getContext(), "投递成功！");
                                    timer.cancel();
                                    NavHostFragment.findNavController(SendInfoConfirmFragment.this)
                                            .navigate(R.id.action_sendInfoConfirmFragment_to_sendSuccessFragment);
                                } 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(), "服务器异常！ 请稍后重试！");
                        }
                    });
                }
            });
            // 投递完成后已经是另外一单, 可以继续异常处理
            LocalStorage.getInstance().getSession().setException(true);
        });

        // 异常页面跳转
        MainActivity finalActivity = activity;
        binding.exceptionBtn.setOnClickListener(view1 -> {
            if (ButtonUtils.isFastClick()) {
                return;
            }
            Bundle bundle = new Bundle();
            timer.cancel();
            bundle.putString("exception", "exception_page");
            finalActivity.getBundleMap().put(SendInfoConfirmFragment.class.getName(), bundle);
            NavHostFragment.findNavController(SendInfoConfirmFragment.this)
                    .navigate(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站通")
                    .setMessage("确定要取消本次投递吗？")
                    .setPositiveButton("是", (dialog, which) -> {
                        // 是, 取消本次投递
                        ConfirmOrderVo confirmOrderVo = new ConfirmOrderVo();
                        confirmOrderVo.setOrderSn(finalOrderSn);
                        confirmOrderVo.setClientId(BaseUtils.getClientId());
                        confirmOrderVo.setDecision(DecisionEnum.CANCEL_11.getDecision());
                        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 {
                                        timer.cancel();
                                        NavHostFragment.findNavController(SendInfoConfirmFragment.this)
                                                .navigate(R.id.action_sendInfoConfirmFragment_to_sendSuccessFragment);
                                    } catch (Exception e) {

                                    }
                                });
                            }
                        });
                    }).setNegativeButton("否", (dialog, which) -> {
                        // 否
                        dialog.dismiss();
                    }).create();
            alertDialog.show();
        });

        binding.returnMainBtn.setOnClickListener(view1 -> {
            if (ButtonUtils.isFastClick()) {
                return;
            }
            AlertDialog alertDialog = new AlertDialog.Builder(finalActivity)
                    .setTitle("e站通")
                    .setMessage("返回主页会取消本次投递！确认取消吗？")
                    .setPositiveButton("是", ((dialog, which) -> {
                        timer.cancel();
                        LocalStorage.getInstance().cleanSession(((MainActivity) getActivity()));
                        NavHostFragment.findNavController(SendInfoConfirmFragment.this)
                                .navigate(R.id.action_sendInfoConfirmFragment_to_mainFragment);
                    })).setNegativeButton("否", ((dialog, which) -> {
                        dialog.dismiss();
                    })).create();
            alertDialog.show();
        });

    }

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