package com.emato.ich.fragment;

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.contant.ICSPConstant;
import com.emato.ich.contant.SystemConfigConstant;
import com.emato.ich.databinding.FragmentTakeSuccessBinding;
import com.emato.ich.entity.vo.PreparedOrderResponseVo;
import com.emato.ich.entity.vo.ResponseData;
import com.emato.ich.entity.vo.TakeParcelVo;
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 okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * 取件成功提示页面
 */
public class TakeSuccessFragment extends Fragment {

    private static final String TAG = TakeSuccessFragment.class.getName();
    private FragmentTakeSuccessBinding binding;
    private CountDownTimer timer;
    private CountDownTimer timer2;
    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 = FragmentTakeSuccessBinding.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.returnMainBtn, ColorConstant.RETURN_BUTTON_BG_COLOR);
        try {
            MainActivity activity = ((MainActivity) getActivity());
            timer = TimeOutUtils.timeout(activity, TakeSuccessFragment.this, binding.timeout, 60);
            timer.start();
        } catch (Exception e) {
            Log.e(TAG, "onViewCreated: 倒计时出现异常! ", e);
            LoggingUtils.sendErrorLog("业务异常: 取件成功页面倒计时出现异常! ", e);
        }

        binding.continueTakeBtn.setOnClickListener(view1 -> {
            if (ButtonUtils.isFastClick()) {
                return;
            }
            if (null != timer) {
                timer.cancel();
            }
            if (null != timer2) {
                timer2.cancel();
            }
            NavUtils.navigate(this, R.id.action_takeSuccessFragment_to_takeCodeFragment);
        });

        binding.returnMainBtn.setOnClickListener(view1 -> {
            if (ButtonUtils.isFastClick()) {
                return;
            }
            if (null != timer) {
                timer.cancel();
            }
            if (null != timer2) {
                timer2.cancel();
            }
            MainActivity activity = (MainActivity) getActivity();
            LocalStorage.getInstance().cleanSession(activity, false);
            NavUtils.navigate(this, R.id.action_takeSuccessFragment_to_mainFragment);
        });

        try {
            MainActivity activity = (MainActivity) getActivity();
            String s = activity.getConfigMap().get(SystemConfigConstant.cabinet_take_object_reopen_time);
            Bundle bundle = activity.getBundleMap().get(TakeCodeFragment.class.getName());
            binding.openCabinetHintNo.setText(bundle.getString("takeCabinetNo"));
            // 倒计时
            s = StringUtils.isNullOrEmpty(s) ? "15" : s;
            int i = Integer.parseInt(s);
            timer2 = new CountDownTimer(i * 1000, 1000) {
                @Override
                public void onTick(long millisUntilFinished) {
                    binding.openCabinetCountDownHint.setText(String.format("倒计时%s秒，只有一次机会，超时后不可开门！", (millisUntilFinished / 1000)));
                }

                @Override
                public void onFinish() {
                    binding.openCabinetCountDownHint.setText("已超时，不可开门！");
                    binding.reOpenCabinetBtn.setEnabled(false);
                }
            };
            timer2.start();
        } catch (RuntimeException e) {
            Log.e(TAG, "onViewCreated: 倒计时未知异常! ", e);
            LoggingUtils.sendErrorLog("业务异常: 取件成功再开一次按钮倒计时出现异常! ", e);
        }

        binding.reOpenCabinetBtn.setOnClickListener(view1 -> {
            if (ButtonUtils.isFastClick()) {
                return;
            }
            binding.openCabinetCountDownHint.setText("已超时，不可开门！");
            if (null != timer2) {
                timer2.cancel();
            }
            binding.reOpenCabinetBtn.setEnabled(false);

            // TODO 取件逻辑
            String takeParcelCode = null;
            MainActivity activity = null;
            try {
                activity = (MainActivity) getActivity();
                Bundle bundle = activity.getBundleMap().get(TakeCodeFragment.class.getName());
                takeParcelCode = bundle.getString("takeParcelCode");
            } catch (RuntimeException e) {
                Log.e(TAG, "onViewCreated: 获取TakeCodeFragment传值TakeSuccessFragment失败! ", e);
                LoggingUtils.sendErrorLog("业务异常: 获取TakeCodeFragment传值TakeSuccessFragment失败! ", e);
            }
            TakeParcelVo takeParcelVo = new TakeParcelVo();
            takeParcelVo.setClientId(BaseUtils.getClientId());
            takeParcelVo.setPickUp(takeParcelCode);
            takeParcelVo.setReopen("1");
            MainActivity finalActivity = activity;
            ICSPClient.takeParcel(LocalStorage.getInstance().getSession().getToken(), takeParcelVo, new Callback() {
                @Override
                public void onFailure(@NotNull Call call, @NotNull IOException e) {
                    // TODO 取件接口请求失败逻辑处理
                    ToastUtils.make(getContext(), "取件失败！网络异常！");
                    Log.e(TAG, "onFailure: 取件请求失败!", e);
                    LoggingUtils.sendErrorLog("业务异常: 取件失败！网络异常! ", e);
                }

                @Override
                public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                    // TODO 返回锁板和锁id, 开柜门
                    getActivity().runOnUiThread(() -> {
                        String parseResponse = ICSPClient.isSuccessfulAndParseResponse(response);
                        if (!StringUtils.isNullOrEmpty(parseResponse)) {
                            try {
                                ObjectMapper objectMapper = JacksonUtils.objectmapper;
                                ResponseData<PreparedOrderResponseVo> responseData = null;
                                try {
                                    responseData = objectMapper.readValue(parseResponse, new TypeReference<ResponseData<PreparedOrderResponseVo>>() {
                                    });
                                    ToastUtils.make(getContext(), responseData.getMsg());
                                } catch (JsonProcessingException e) {
                                    Log.e(TAG, "onResponse: 解析取件开门响应信息失败! ", e);
                                    LoggingUtils.sendErrorLog("业务异常: 解析取件开门响应信息失败! ", e);
                                } catch (RuntimeException e) {
                                    Log.e(TAG, "onResponse: 未知错误! ", e);
                                    ToastUtils.make(getContext(), "未知错误！");
                                    LoggingUtils.sendErrorLog("业务异常: 解析取件开门响应信息失败! 未知错误! ", e);
                                }
                                if (null != responseData && responseData.getCode().equals(ICSPConstant.OK)) {
                                    // 开门
                                    Log.i(TAG, "onResponse: 取件成功! ");
                                    ToastUtils.make(getContext(), "取件成功！");
                                    PreparedOrderResponseVo data = responseData.getData();
                                    binding.openCabinetHintNo.setText(data.getLockerName());
                                    finalActivity.getBundleMap().remove(TakeCodeFragment.class.getName());
                                } else {
                                    ToastUtils.make(getContext(), responseData.getMsg());
                                }
                            } catch (RuntimeException e) {
                                Log.e(TAG, "onResponse: 取件失败! ", e);
                                ToastUtils.make(getContext(), "取件失败！");
                                LoggingUtils.sendErrorLog("业务异常: 取件失败! 未知错误! ", e);
                            }
                        } else {
                            ToastUtils.make(getContext(), "服务器异常！ 请稍后重试！");
                        }
                    });
                }
            });
        });
    }

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