package com.emato.ich.fragment;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.CountDownTimer;

import com.emato.ich.contant.DecisionConstant;
import com.emato.ich.utils.Log;

import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.navigation.NavBackStackEntry;
import androidx.navigation.NavController;
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.CabinetTypeConstant;
import com.emato.ich.contant.DecisionConstant;
import com.emato.ich.databinding.FragmentChooseCabinetBinding;
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.entity.vo.CabinetInfoVo;
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.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.List;
import java.util.Objects;

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

/**
 * 选择柜子页面
 */
public class ChooseCabinetFragment extends Fragment {

    private static final String TAG = ChooseCabinetFragment.class.getName();
    private FragmentChooseCabinetBinding binding;
    private CountDownTimer timer;
    private long start;

    @SuppressLint("ResourceAsColor")
    private void isDisable(Integer available, Button button, TextView textView){
        //            textView.setBackgroundColor(android.graphics.Color.parseColor("#44CE3B"));
        button.setEnabled(available > 0);
    }

    @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 = FragmentChooseCabinetBinding.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, ChooseCabinetFragment.this, binding.timeout, 90);
            timer.start();
        } catch (Exception e) {
            Log.e(TAG, "onViewCreated: 倒计时出现异常! ", e);
            LoggingUtils.sendErrorLog("业务异常: 选择柜子类型页面倒计时出现异常! ", e);
        }
        MainActivity activityTmp = (MainActivity) getActivity();
        Bundle mainBundle = activityTmp.getBundleMap().get(MainFragment.class.getName());
        String pageType = mainBundle.getString("pageType");
        // 用户寄送跳转不需要进行登录
        // 判断是否是直接投递的  how_to_send  如果不是直接投递跳转过来的  那就隐藏投递流程
        if (!"expressDelivery".equals(pageType)){
            view.findViewById(R.id.how_to_send).setVisibility(View.GONE);
        }else{
            view.findViewById(R.id.how_to_send).setVisibility(View.GONE);
        }





        // 获取柜子信息
        ICSPClient.getCabinetInfo(LocalStorage.getInstance().getSession().getToken(), new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                // TODO 获取柜子信息失败处理
                Looper.prepare();
                ToastUtils.make(getContext(), "获取柜子信息失败！网络异常！");
                Looper.loop();
                Log.e(TAG, "onFailure: 获取柜子信息调用失败! call: " + call.timeout().toString(), e);
                LoggingUtils.sendErrorLog("业务异常: 获取柜子信息调用失败! ", e);
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                FragmentActivity activity = getActivity();
                if(activity != null) {
                    activity.runOnUiThread(() -> {
                        String cabinetInfo = ICSPClient.isSuccessfulAndParseResponse(response);

                        if (!StringUtils.isNullOrEmpty(cabinetInfo)) {
                            try {
                                // 需要先请求ICSP获取柜子个数, 某类型无空柜子则按钮置灰
                                ObjectMapper objectMapper = JacksonUtils.objectmapper;
                                ResponseData<List<CabinetInfoVo>> responseData = objectMapper.readValue(cabinetInfo, new TypeReference<ResponseData<List<CabinetInfoVo>>>() {
                                });

                                if (responseData.getCode().equals(ICSPConstant.OK)) {
                                    List<CabinetInfoVo> cabinetInfoVos = responseData.getData();

                                    cabinetInfoVos.forEach(cabinetInfoVo -> {
                                        if (!StringUtils.isNullOrEmpty(cabinetInfoVo.getType())) {
                                            switch (cabinetInfoVo.getType()) {
                                                case "mini":
                                                    binding.tinyCabinet.append("可用" + cabinetInfoVo.getAvailable() + "个");
                                                    isDisable(cabinetInfoVo.getAvailable(), binding.tinyCabinetBtn, binding.tinyCabinetBg);
                                                    break;
                                                case "small":
                                                    binding.smallCabinet.append("可用" + cabinetInfoVo.getAvailable() + "个");
                                                    isDisable(cabinetInfoVo.getAvailable(), binding.smallCabinetBtn, binding.smallCabinetBg);
                                                    break;
                                                case "medium":
                                                    binding.mediumCabinet.append("可用" + cabinetInfoVo.getAvailable() + "个");
                                                    isDisable(cabinetInfoVo.getAvailable(), binding.mediumCabinetBtn, binding.mediumCabinetBg);
                                                    break;
                                                case "large":
                                                    binding.bigCabinet.append("可用" + cabinetInfoVo.getAvailable() + "个");
                                                    isDisable(cabinetInfoVo.getAvailable(), binding.bigCabinetBtn, binding.bigCabinetBg);
                                                    break;
                                                default:
                                                    break;
                                            }
                                        }
                                    });
                                } else {
                                    ToastUtils.make(getContext(), responseData.getMsg());
                                    Log.w(TAG, "onResponse: " + responseData.getMsg());
                                }

                            } catch (IOException e) {
                                Log.e(TAG, "onCreateView: 获取柜子剩余信息响应信息解析失败！", e);
                                LoggingUtils.sendErrorLog("业务异常: 获取柜子剩余信息响应信息解析失败! ", e);
                            } catch (RuntimeException e) {
                                Log.e(TAG, "onResponse: ", e);
                                LoggingUtils.sendErrorLog("业务异常: 获取柜子剩余信息未知错误! ", e);
                            }
                        } else {
                            ToastUtils.make(getContext(), "服务器异常！请稍后重试！");
                        }
                    });
                }
            }
        });

        Bundle bundle = new Bundle();
        // 大柜子
        binding.bigCabinetBtn.setOnClickListener(v -> {
            if (ButtonUtils.isFastClick()) {
                return;
            }
            preparedOrder(CabinetTypeConstant.LARGE, bundle, v);
        });
        // 中柜子
        binding.mediumCabinetBtn.setOnClickListener(v -> {
            if (ButtonUtils.isFastClick()) {
                return;
            }
            preparedOrder(CabinetTypeConstant.MEDIUM, bundle, v);
        });
        // 小柜子
        binding.smallCabinetBtn.setOnClickListener(v -> {
            if (ButtonUtils.isFastClick()) {
                return;
            }
            preparedOrder(CabinetTypeConstant.SMALL, bundle, v);
        });
        // 微小柜子
        binding.tinyCabinetBtn.setOnClickListener(v -> {
            if (ButtonUtils.isFastClick()) {
                return;
            }
            preparedOrder(CabinetTypeConstant.MINI, bundle, v);
        });

        binding.returnBtn.setOnClickListener(v -> {
            if (ButtonUtils.isFastClick()) {
                return;
            }
            MainActivity activity = (MainActivity) getActivity();
            activity.getBundleMap().put(ChooseCabinetFragment.class.getName(), bundle);

            Bundle MainFragmentBundle = activity.getBundleMap().get(MainFragment.class.getName());
            if (Objects.nonNull(MainFragmentBundle)){
                //  我要寄快递页面跳转
                if("expressDelivery".equals(MainFragmentBundle.getString("pageType"))){
                    NavUtils.navigate(this, R.id.action_chooseCabinetFragment_to_mainFragment);
                }
            }
            Bundle exceptionBundle = activity.getBundleMap().get(ExceptionFragment.class.getName());
            if (null != timer) {
                timer.cancel();
            }
            if (null != exceptionBundle) {
                NavUtils.navigate(this, R.id.action_chooseCabinetFragment_to_exceptionFragment);
            } else {
                NavUtils.navigate(this, R.id.action_chooseCabinetFragment_to_sendMainFragment);
            }
        });
    }

    public void preparedOrder(String sectionType, Bundle bundle, View view){

        bundle.putString("section_type", sectionType);
        Bundle exceptionBundle = null;
        try {
            MainActivity activity = (MainActivity) getActivity();
            activity.getBundleMap().put(ChooseCabinetFragment.class.getName(), bundle);
            exceptionBundle = activity.getBundleMap().get(ExceptionFragment.class.getName());

            // 不为空说明是异常页跳过来的, 更新柜子类型, 如果有订单号就更新预下单, 无则走预下单逻辑
            if (null != exceptionBundle) {
                Bundle inputInfoBundle = activity.getBundleMap().get(InputInfoKeyBoardFragment.class.getName());
                ObjectMapper objectMapper = JacksonUtils.objectmapper;
                if (inputInfoBundle == null) {
                    ToastUtils.make(getContext(), "您还没有投递!");
                } else {
                    String orderResponse = inputInfoBundle.getString("preparedOrderResponse");
                    if (null != orderResponse && orderResponse.trim().length() > 0) {
                        PreparedOrderResponseVo preparedOrderResponse = objectMapper.readValue(orderResponse, PreparedOrderResponseVo.class);

                        ConfirmOrderVo confirmOrderVo = new ConfirmOrderVo();
                        confirmOrderVo.setLockerType(sectionType);
                        confirmOrderVo.setDecision(DecisionConstant.REOPEN_01);
                        confirmOrderVo.setClientId(BaseUtils.getClientId());
                        confirmOrderVo.setOrderSn(preparedOrderResponse.getOrderSn());

                        ICSPClient.confirmOrder(LocalStorage.getInstance().getSession().getToken(), confirmOrderVo, new Callback() {
                            @Override
                            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                                //
                                Looper.prepare();
                                ToastUtils.make(getContext(), "换柜子失败！网络异常！");
                                Looper.loop();
                                Log.e(TAG, "onFailure: 大小不合适, 换柜子更新预下单失败! ", e);
                                LoggingUtils.sendErrorLog("业务异常: 大小不合适, 换柜子更新预下单失败! ", e);
                            }

                            @Override
                            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                                // 换柜子成功, 跳转到确认投递页面
                                ((MainActivity) getActivity()).runOnUiThread(() -> {
                                    try {
                                        String responseStr = ICSPClient.isSuccessfulAndParseResponse(response);
                                        if (!StringUtils.isNullOrEmpty(responseStr)) {
                                            ObjectMapper objectMapper = JacksonUtils.objectmapper;
                                            ResponseData<PreparedOrderResponseVo> responseData = objectMapper.readValue(responseStr, new TypeReference<ResponseData<PreparedOrderResponseVo>>() {});
                                            // 响应信息
                                            if (responseData.getCode().equals(ICSPConstant.OK)) {
                                                PreparedOrderResponseVo data = responseData.getData();
                                                if (null != data) {
                                                    data.setOrderSn(preparedOrderResponse.getOrderSn());
                                                    data.setCollectorPhone(preparedOrderResponse.getCollectorPhone());
                                                    String mailNo = inputInfoBundle.getString("takeNo");
                                                    bundle.putString("preparedOrderResponse", objectMapper.writeValueAsString(data));
                                                    bundle.putString("takeNo", mailNo);
                                                    bundle.putString("section_type", data.getLockerName());

                                                    // 跳转到确认投递
                                                    try {
                                                        MainActivity activity = (MainActivity) getActivity();
                                                        activity.getBundleMap().put(InputInfoKeyBoardFragment.class.getName(), bundle);
                                                        activity.getBundleMap().remove(ExceptionFragment.class.getName());
                                                        if (null != timer) {
                                                            timer.cancel();
                                                        }
                                                        NavUtils.navigate(ChooseCabinetFragment.this, R.id.action_chooseCabinetFragment_to_sendInfoConfirmFragment);
                                                    } catch (RuntimeException e) {
                                                        Log.e(TAG, "onResponse: InputInfoFragment页面获取SendInfoConfirmFragment传值错误! ", e);
                                                        LoggingUtils.sendErrorLog("业务异常: InputInfoFragment页面获取SendInfoConfirmFragment传值错误! ", e);
                                                    }
                                                }
                                            } else {
                                                ToastUtils.make(getContext(), responseData.getMsg());
                                                RuntimeException exception = new RuntimeException("系统异常");
                                                Log.e(TAG, "onResponse: ICSP返回码: " + responseData.getCode() + ", 返回信息: " + responseData.getMsg(), exception);
                                                LoggingUtils.sendErrorLog("业务异常: ICSP返回码: " + responseData.getCode() + ", 返回信息: " + responseData.getMsg(), exception);
                                            }
                                        } else {
                                            ToastUtils.make(getContext(), "服务器异常！请稍后重试！");
                                        }
                                    } catch (JsonProcessingException e) {
                                        Log.e(TAG, "onResponse: 预下单转换成JSON出错! ", e);
                                        LoggingUtils.sendErrorLog("业务异常: 预下单转换成JSON出错! ", e);
                                    } catch (RuntimeException e) {
                                        Log.e(TAG, "onResponse: 换柜子错误! ", e);
                                        LoggingUtils.sendErrorLog("业务异常: 换柜子错误! ", e);
                                    }
                                });
                            }
                        });
                    }
                }
            } else {
                // 为空走正常投递流程
                if (null != timer) {
                    timer.cancel();
                }

                String pageType = activity.getBundleMap().get(MainFragment.class.getName()).getString("pageType");
                activity.getBundleMap().put(ChooseCabinetFragment.class.getName(), bundle);
                if(!StringUtils.isNullOrEmpty(pageType) && "expressDelivery".equals(pageType)){
                    NavUtils.navigate(this, R.id.action_chooseCabinetFragment_to_expressDeliveryFragment, bundle);
                }else {
                    String isPay = activity.getBundleMap().get(SendKeyBoardFragment.class.getName()).getString("isPay");
                    if ("0".equals(isPay)){
                        NavUtils.navigate(this, R.id.action_chooseCabinetFragment_to_paymentFragment);
                    }else {
                        NavUtils.navigate(this, R.id.action_chooseCabinetFragment_to_InputInfoKeyBoardFragment, bundle);
                    }
                }

            }

        } catch (RuntimeException | JsonProcessingException e) {
            Log.e(TAG, "onViewCreated: ChooseCabinetFragment向InputInfoFragment页面传值错误! ", e);
            LoggingUtils.sendErrorLog("业务异常: ChooseCabinetFragment向InputInfoFragment页面传值错误! ", e);
        }

    }

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