package com.emato.ich.fragment;

import android.annotation.SuppressLint;
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.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.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.CabinetTypeEnum;
import com.emato.ich.contant.DecisionEnum;
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.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 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;

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

    @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 = FragmentChooseCabinetBinding.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, ChooseCabinetFragment.this, binding.timeout, 60);
            timer.start();
        } catch (Exception e) {
            Log.e(TAG, "onViewCreated: 倒计时出现异常! ", e);
            LoggingUtils.sendErrorLog("业务异常: 选择柜子类型页面倒计时出现异常! ", e);
        }

        // 获取柜子信息
        ICSPClient.getCabinetInfo(LocalStorage.getInstance().getSession().getToken(), new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                // TODO 获取柜子信息失败处理
                ToastUtils.make(getContext(), "获取柜子信息失败！网络异常！");
                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(ICSPResponseCodeEnum.OK.getCode())) {
                                    List<CabinetInfoVo> cabinetInfoVos = responseData.getData();

                                    cabinetInfoVos.forEach(cabinetInfoVo -> {
                                        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 {
                                    ICSPResponseCodeEnum.responseHint(getContext(), responseData);
                                    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(CabinetTypeEnum.LARGE.getType(), bundle, v);
        });
        // 中柜子
        binding.mediumCabinetBtn.setOnClickListener(v -> {
            if (ButtonUtils.isFastClick()) {
                return;
            }
            preparedOrder(CabinetTypeEnum.MEDIUM.getType(), bundle, v);
        });
        // 小柜子
        binding.smallCabinetBtn.setOnClickListener(v -> {
            if (ButtonUtils.isFastClick()) {
                return;
            }
            preparedOrder(CabinetTypeEnum.SMALL.getType(), bundle, v);
        });
        // 微小柜子
        binding.tinyCabinetBtn.setOnClickListener(v -> {
            if (ButtonUtils.isFastClick()) {
                return;
            }
            preparedOrder(CabinetTypeEnum.MINI.getType(), bundle, v);
        });

        binding.returnBtn.setOnClickListener(v -> {
            if (ButtonUtils.isFastClick()) {
                return;
            }
            MainActivity activity = (MainActivity) getActivity();
            activity.getBundleMap().put(ChooseCabinetFragment.class.getName(), bundle);
            Bundle exceptionBundle = activity.getBundleMap().get(ExceptionFragment.class.getName());
            timer.cancel();
            if (null != exceptionBundle) {
                NavHostFragment.findNavController(ChooseCabinetFragment.this).navigate(R.id.action_chooseCabinetFragment_to_exceptionFragment);
            } else {
                NavHostFragment.findNavController(ChooseCabinetFragment.this).navigate(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(InputInfoFragment.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(DecisionEnum.REOPEN_01.getDecision());
                        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) {
                                //
                                ToastUtils.make(getContext(), "换柜子失败！网络异常！");
                                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(ICSPResponseCodeEnum.OK.getCode())) {
                                                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(InputInfoFragment.class.getName(), bundle);
                                                        activity.getBundleMap().remove(ExceptionFragment.class.getName());
                                                        timer.cancel();
                                                        NavHostFragment.findNavController(ChooseCabinetFragment.this)
                                                                .navigate(R.id.action_chooseCabinetFragment_to_sendInfoConfirmFragment);
                                                    } catch (RuntimeException e) {
                                                        Log.e(TAG, "onResponse: InputInfoFragment页面获取SendInfoConfirmFragment传值错误! ", e);
                                                        LoggingUtils.sendErrorLog("业务异常: InputInfoFragment页面获取SendInfoConfirmFragment传值错误! ", e);
                                                    }
                                                }
                                            } else {
                                                ICSPResponseCodeEnum.responseHint(getContext(), responseData);
                                                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 {
                // 为空走正常投递流程
                timer.cancel();
                activity.getBundleMap().put(ChooseCabinetFragment.class.getName(), bundle);
                NavHostFragment.findNavController(ChooseCabinetFragment.this)
                        .navigate(R.id.action_chooseCabinetFragment_to_inputInfoFragment, bundle);
            }

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

    }

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