package com.emato.ich.fragment;

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.emato.ich.utils.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

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.FragmentTakeCodeBinding;
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.utils.BaseUtils;
import com.emato.ich.utils.ButtonUtils;
import com.emato.ich.utils.LoggingUtils;
import com.emato.ich.utils.NavUtils;
import com.emato.ich.utils.StringUtils;
import com.emato.ich.utils.JacksonUtils;
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.io.InputStream;

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

/**
 * 取件码输入页面
 */
public class TakeCodeFragment extends Fragment {

    private FragmentTakeCodeBinding binding;
    private static final String TAG = TakeCodeFragment.class.getName();
    private CountDownTimer timer;
    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 = FragmentTakeCodeBinding.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);

        BaseUtils.disableEditText(binding.editTextTextPersonName6);

        try {
            MainActivity activity = ((MainActivity) getActivity());
            timer = TimeOutUtils.timeout(activity, TakeCodeFragment.this, binding.timeout, 90);
            timer.start();
        } catch (Exception e) {
            Log.e(TAG, "onViewCreated: 倒计时出现异常! ", e);
            LoggingUtils.sendErrorLog("业务异常: 取件码输入页面倒计时出现异常! ", e);
        }

//        binding.textView.setBackgroundResource(R.drawable.e_mp_qrcode_8x8_backup);
        MainActivity activity = (MainActivity) getActivity();
        String url = activity.getConfigMap().get(SystemConfigConstant.cabinet_take_object_qrcode_url);

        if (getActivity() != null && activity.getConfigMap().size() > 0 && !StringUtils.isNullOrEmpty(url)) {
            try {
                ImageView imageView = view.findViewById(R.id.textView);
                Glide.with(view).load(url)
                        .skipMemoryCache(true)//跳过内存缓存
                        .diskCacheStrategy(DiskCacheStrategy.NONE)//不缓冲disk硬盘中
                        .into(imageView);
            } catch (Exception e) {
                Log.e(TAG, "onResponse: Glide设置图片异常! ", e);
                LoggingUtils.sendErrorLog("业务异常: Glide请求微信公众号图片异常! ", e);
            }
        }

        // 选中输入框
//        binding.editTextTextPersonName6.requestFocus();

        // 输入逻辑
        binding.editTextTextPersonName6.setOnFocusChangeListener((view1, hasFocus) -> {
            if (hasFocus) {
                binding.takeInputButton0.setOnClickListener(v -> {
                    int length = binding.editTextTextPersonName6.getText().length();
                    if (length >= 8) {
                        ToastUtils.make(getContext(), "取件码不能超过8位");
                        return;
                    }
                    int start = binding.editTextTextPersonName6.getSelectionStart();
                    binding.editTextTextPersonName6.getText().insert(start,"0");
                });
                binding.takeInputButton1.setOnClickListener(v -> {
                    int length = binding.editTextTextPersonName6.getText().length();
                    if (length >= 8) {
                        ToastUtils.make(getContext(), "取件码不能超过8位");
                        return;
                    }
                    int start = binding.editTextTextPersonName6.getSelectionStart();
                    binding.editTextTextPersonName6.getText().insert(start,"1");
                });
                binding.takeInputButton2.setOnClickListener(v -> {
                    int length = binding.editTextTextPersonName6.getText().length();
                    if (length >= 8) {
                        ToastUtils.make(getContext(), "取件码不能超过8位");
                        return;
                    }
                    int start = binding.editTextTextPersonName6.getSelectionStart();
                    binding.editTextTextPersonName6.getText().insert(start,"2");
                });
                binding.takeInputButton3.setOnClickListener(v -> {
                    int length = binding.editTextTextPersonName6.getText().length();
                    if (length >= 8) {
                        ToastUtils.make(getContext(), "取件码不能超过8位");
                        return;
                    }
                    int start = binding.editTextTextPersonName6.getSelectionStart();
                    binding.editTextTextPersonName6.getText().insert(start,"3");
                });
                binding.takeInputButton4.setOnClickListener(v -> {
                    int length = binding.editTextTextPersonName6.getText().length();
                    if (length >= 8) {
                        ToastUtils.make(getContext(), "取件码不能超过8位");
                        return;
                    }
                    int start = binding.editTextTextPersonName6.getSelectionStart();
                    binding.editTextTextPersonName6.getText().insert(start,"4");
                });
                binding.takeInputButton5.setOnClickListener(v -> {
                    int length = binding.editTextTextPersonName6.getText().length();
                    if (length >= 8) {
                        ToastUtils.make(getContext(), "取件码不能超过8位");
                        return;
                    }
                    int start = binding.editTextTextPersonName6.getSelectionStart();
                    binding.editTextTextPersonName6.getText().insert(start,"5");
                });
                binding.takeInputButton6.setOnClickListener(v -> {
                    int length = binding.editTextTextPersonName6.getText().length();
                    if (length >= 8) {
                        ToastUtils.make(getContext(), "取件码不能超过8位");
                        return;
                    }
                    int start = binding.editTextTextPersonName6.getSelectionStart();
                    binding.editTextTextPersonName6.getText().insert(start,"6");
                });
                binding.takeInputButton7.setOnClickListener(v -> {
                    int length = binding.editTextTextPersonName6.getText().length();
                    if (length >= 8) {
                        ToastUtils.make(getContext(), "取件码不能超过8位");
                        return;
                    }
                    int start = binding.editTextTextPersonName6.getSelectionStart();
                    binding.editTextTextPersonName6.getText().insert(start,"7");
                });
                binding.takeInputButton8.setOnClickListener(v -> {
                    int length = binding.editTextTextPersonName6.getText().length();
                    if (length >= 8) {
                        ToastUtils.make(getContext(), "取件码不能超过8位");
                        return;
                    }
                    int start = binding.editTextTextPersonName6.getSelectionStart();
                    binding.editTextTextPersonName6.getText().insert(start,"8");
                });
                binding.takeInputButton9.setOnClickListener(v -> {
                    int length = binding.editTextTextPersonName6.getText().length();
                    if (length >= 8) {
                        ToastUtils.make(getContext(), "取件码不能超过8位");
                        return;
                    }
                    int start = binding.editTextTextPersonName6.getSelectionStart();
                    binding.editTextTextPersonName6.getText().insert(start,"9");
                });
                binding.takeInputButtonCancel.setOnClickListener(v -> {
                    Editable text = binding.editTextTextPersonName6.getText();
                    int start = binding.editTextTextPersonName6.getSelectionStart();
                    if (text.length() > 0) {
                       if (start > 0) {
                           text.delete(start-1, start);
                       }
                       binding.editTextTextPersonName6.setText(text, TextView.BufferType.EDITABLE);
                       binding.editTextTextPersonName6.setSelection(start-1<0 ? text.length() : start-1);
                   }
                });
                // 长按删除
                binding.takeInputButtonCancel.setOnLongClickListener(v -> {
                    binding.editTextTextPersonName6.getText().clear();
                    return false;
                });
            }
        });

        binding.takeInputButtonConfirm.setOnClickListener(view1 -> {
            if (ButtonUtils.isFastClick()) {
                return;
            }
            // TODO 取件逻辑
            String takeParcelCode = binding.editTextTextPersonName6.getText().toString();
            if (null != takeParcelCode && !"".equals(takeParcelCode.trim()) && takeParcelCode.length() > 0) {
                TakeParcelVo takeParcelVo = new TakeParcelVo();
                takeParcelVo.setClientId(BaseUtils.getClientId());
                takeParcelVo.setPickUp(takeParcelCode);
                takeParcelVo.setReopen("0");
                ICSPClient.takeParcel("", 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(), "取件成功！");
                                        Bundle bundle = new Bundle();
                                        bundle.putString("takeParcelCode", takeParcelCode);
                                        bundle.putString("takeCabinetNo", responseData.getData().getLockerName());
                                        ((MainActivity) getActivity()).getBundleMap().put(TakeCodeFragment.class.getName(), bundle);
                                        if (null != timer) {
                                            timer.cancel();
                                        }
                                        NavUtils.navigate(TakeCodeFragment.this, R.id.action_takeCodeFragment_to_takeSuccessFragment);
                                    }
                                } catch (RuntimeException e) {
                                    Log.e(TAG, "onResponse: 取件失败! ", e);
                                    ToastUtils.make(getContext(), "取件失败！");
                                    LoggingUtils.sendErrorLog("业务异常: 取件失败! ", e);
                                }
                            } else {
                                ToastUtils.make(getContext(), "服务器异常！ 请稍后重试！");
                            }
                        });
                    }
                });
            } else {
                ToastUtils.make(getContext(), "取件失败！取件码不能为空！");
            }

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

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