package com.emato.ich.fragment;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
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 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.FragmentExpressDeliveryBinding;
import com.emato.ich.entity.vo.PreparedOrderResponseVo;
import com.emato.ich.entity.vo.PreparedOrderVo;
import com.emato.ich.entity.vo.ResponseData;
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.Log;
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 ExpressDeliveryFragment extends Fragment {

    private static final String TAG = ExpressDeliveryFragment.class.getName();
    private FragmentExpressDeliveryBinding binding;
    private CountDownTimer timer;
    private long start;
    private PreparedOrderResponseVo data;
    @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 = FragmentExpressDeliveryBinding.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。");
        super.onViewCreated(view, savedInstanceState);

//        ColorConstant.setButtonColor(binding.returnBtn, ColorConstant.RETURN_BUTTON_BG_COLOR);
        try {
            MainActivity activity = ((MainActivity) getActivity());
            timer = TimeOutUtils.timeout(activity, ExpressDeliveryFragment.this, binding.timeout, 60);
            timer.start();
        } catch (Exception e) {
            Log.e(TAG, "onViewCreated: 倒计时出现异常! ", e);
            LoggingUtils.sendErrorLog("业务异常: 取件页面倒计时出现异常! ", e);
        }

        Bundle arguments = null;
        String sectionType = null;
        MainActivity activity = (MainActivity) getActivity();
        String url = activity.getConfigMap().get(SystemConfigConstant.cabinet_take_object_qrcode_url);
        arguments = activity.getBundleMap().get(ChooseCabinetFragment.class.getName());
        // 需要先跳转选柜子的页面后才能走这里
        sectionType = arguments.getString("section_type");
/*        if (getActivity() != null && activity.getConfigMap().size() > 0 && !StringUtils.isNullOrEmpty(url)) {
            // todo:这里可改为从后端获取寄件二维码图片 
            ICSPClient.getWeChatMPImage(url, 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 {
                            InputStream is = response.body().byteStream();
                            final Drawable d = Drawable.createFromStream(is, "src");
                            binding.expressDeliveryQrCodeImage.setBackground(d);
                            is.close();
                        } catch (Exception e) {
                            Log.e(TAG, "onResponse: 设置图片异常! ", e);
                            LoggingUtils.sendErrorLog("业务异常: 设置图片异常! ", e);
                        }
                    });
                }
            });
        }*/




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

        // TODO 设置键盘塞值和处理确认按钮
        String finalSectionType = sectionType;
        binding.keyBoard.inputButtonConfirm.setOnClickListener(v -> {
            if (ButtonUtils.isFastClick()) {
                return;
            }
            // 点击确定按钮  获取到editTextDeliveryCode 的值 然后调用icsp判断投递码是否存在接口，在回调方法中判断是成功
            // 若成功则跳转页面到选择柜子类型的页面，
            // 在选择柜子类型页面判断如果是投递码投递跳转过来的 则调用投递码下单接口
            if(StringUtils.isNullOrEmpty(binding.editTextDeliveryCode.getText().toString())){
                ToastUtils.make(getContext(), "请求服务器失败！网络异常！");
            }else {
                Bundle bundle = new Bundle();
                // 验证完 预下单
                PreparedOrderVo preparedOrderVo = new PreparedOrderVo();
                preparedOrderVo.setClientId(BaseUtils.getClientId());
                preparedOrderVo.setDeliveryCode(binding.editTextDeliveryCode.getText().toString());
                preparedOrderVo.setLockerType(finalSectionType);
                // 预下单
                ICSPClient.preparedOrder(preparedOrderVo, 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("业务异常: 预下单失败! call: " + call.timeout().toString(), e);
                    }

                    @Override
                    public void onResponse(@NotNull Call call, @NotNull Response response) {
                        ((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>>() {
                                    });
                                    data = responseData.getData();
                                    // 响应信息
                                    if (responseData.getCode().equals(ICSPConstant.OK)) {
                                        bundle.putString("preparedOrderResponse", objectMapper.writeValueAsString(data));
                                        bundle.putString("editTextDeliveryCode", binding.editTextDeliveryCode.getText().toString());
                                        bundle.putString("sectionType", finalSectionType);
                                        bundle.putString("takeNo", binding.editTextDeliveryCode.getText().toString());

                                        // 跳转到确认投递
                                        try {
                                            MainActivity activity = (MainActivity) getActivity();
                                            activity.getBundleMap().put(ExpressDeliveryFragment.class.getName(), bundle);
                                        } catch (RuntimeException e) {
                                            Log.e(TAG, "onResponse: InputInfoFragment页面获取SendInfoConfirmFragment传值错误! ", e);
                                            LoggingUtils.sendErrorLog("业务异常: InputInfoFragment页面获取SendInfoConfirmFragment传值错误! ", e);
                                        }
                                        if (null != timer) {
                                            timer.cancel();
                                        }
                                        NavUtils.navigate(ExpressDeliveryFragment.this, R.id.action_expressDeliveryFragment_to_sendInfoConfirmFragment);
                                    }
                                    Log.i(TAG, "onResponse: ICSP返回码: " + responseData.getCode() + ", 返回信息: " + responseData.getMsg());
                                    ToastUtils.make(getContext(), responseData.getMsg());
                                } 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);
                            }
                        });
                    }
                });
            }



        });
        // 输入投递码
        binding.editTextDeliveryCode.requestFocus();
        binding.keyBoard.inputButton0.setOnClickListener(v -> {
            int length = binding.editTextDeliveryCode.getText().length();
            if (length >= 6) {
                ToastUtils.make(getContext(), "投递码不能超过6位! ");
                return;
            }
            int start = binding.editTextDeliveryCode.getSelectionStart();
            binding.editTextDeliveryCode.getText().insert(start, "0");
        });
        binding.keyBoard.inputButton1.setOnClickListener(v -> {
            int length = binding.editTextDeliveryCode.getText().length();
            if (length >= 6) {
                ToastUtils.make(getContext(), "投递码不能超过6位! ");
                return;
            }
            int start = binding.editTextDeliveryCode.getSelectionStart();
            binding.editTextDeliveryCode.getText().insert(start, "1");
        });
        binding.keyBoard.inputButton2.setOnClickListener(v -> {
            int length = binding.editTextDeliveryCode.getText().length();
            if (length >= 6) {
                ToastUtils.make(getContext(), "投递码不能超过6位! ");
                return;
            }
            int start = binding.editTextDeliveryCode.getSelectionStart();
            binding.editTextDeliveryCode.getText().insert(start, "2");
        });
        binding.keyBoard.inputButton3.setOnClickListener(v -> {
            int length = binding.editTextDeliveryCode.getText().length();
            if (length >= 6) {
                ToastUtils.make(getContext(), "投递码不能超过6位! ");
                return;
            }
            int start = binding.editTextDeliveryCode.getSelectionStart();
            binding.editTextDeliveryCode.getText().insert(start, "3");
        });
        binding.keyBoard.inputButton4.setOnClickListener(v -> {
            int length = binding.editTextDeliveryCode.getText().length();
            if (length >= 6) {
                ToastUtils.make(getContext(), "投递码不能超过6位! ");
                return;
            }
            int start = binding.editTextDeliveryCode.getSelectionStart();
            binding.editTextDeliveryCode.getText().insert(start, "4");
        });
        binding.keyBoard.inputButton5.setOnClickListener(v -> {
            int length = binding.editTextDeliveryCode.getText().length();
            if (length >= 6) {
                ToastUtils.make(getContext(), "投递码不能超过6位! ");
                return;
            }
            int start = binding.editTextDeliveryCode.getSelectionStart();
            binding.editTextDeliveryCode.getText().insert(start, "5");
        });
        binding.keyBoard.inputButton6.setOnClickListener(v -> {
            int length = binding.editTextDeliveryCode.getText().length();
            if (length >= 6) {
                ToastUtils.make(getContext(), "投递码不能超过6位! ");
                return;
            }
            int start = binding.editTextDeliveryCode.getSelectionStart();
            binding.editTextDeliveryCode.getText().insert(start, "6");
        });
        binding.keyBoard.inputButton7.setOnClickListener(v -> {
            int length = binding.editTextDeliveryCode.getText().length();
            if (length >= 6) {
                ToastUtils.make(getContext(), "投递码不能超过6位! ");
                return;
            }
            int start = binding.editTextDeliveryCode.getSelectionStart();
            binding.editTextDeliveryCode.getText().insert(start, "7");
        });
        binding.keyBoard.inputButton8.setOnClickListener(v -> {
            int length = binding.editTextDeliveryCode.getText().length();
            if (length >= 6) {
                ToastUtils.make(getContext(), "投递码不能超过6位! ");
                return;
            }
            int start = binding.editTextDeliveryCode.getSelectionStart();
            binding.editTextDeliveryCode.getText().insert(start, "8");
        });
        binding.keyBoard.inputButton9.setOnClickListener(v -> {
            int length = binding.editTextDeliveryCode.getText().length();
            if (length >= 6) {
                ToastUtils.make(getContext(), "投递码不能超过6位! ");
                return;
            }
            int start = binding.editTextDeliveryCode.getSelectionStart();
            binding.editTextDeliveryCode.getText().insert(start, "9");
        });
        binding.keyBoard.inputButtonCancel.setOnClickListener(v -> {
            Editable text = binding.editTextDeliveryCode.getText();
            int start = binding.editTextDeliveryCode.getSelectionStart();
            if (text.length() > 0) {
                if (start > 0) {
                    text.delete(start - 1, start);
                }
                binding.editTextDeliveryCode.setText(text, TextView.BufferType.EDITABLE);
                binding.editTextDeliveryCode.setSelection(start - 1 < 0 ? text.length() : start - 1);
            }
        });
        // 长按删除
        binding.keyBoard.inputButtonCancel.setOnLongClickListener(v -> {
            binding.editTextDeliveryCode.getText().clear();
            return false;
        });
    }


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