package com.emato.ich.fragment;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import com.emato.ich.utils.Log;
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 androidx.navigation.fragment.NavHostFragment;

import com.cherry.sdk.controller.utils.ScanGunKeyEventHelper;
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.ScanGunConstant;
import com.emato.ich.databinding.FragmentInputInfoBinding;
import com.emato.ich.entity.vo.ResponseData;
import com.emato.ich.entity.vo.PreparedOrderResponseVo;
import com.emato.ich.entity.vo.PreparedOrderVo;
import com.emato.ich.local.LocalStorage;
import com.emato.ich.utils.BaseUtils;
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 com.google.android.material.snackbar.Snackbar;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

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

/**
 * 输入投递信息
 */
public class InputInfoFragment extends Fragment {

    private static final String TAG = "InputInfoFragment";
    private FragmentInputInfoBinding binding;
    private PreparedOrderResponseVo data;
    private final AtomicInteger mailNoLock = new AtomicInteger(1);
    private final AtomicInteger submitLock = new AtomicInteger(1);
    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 = FragmentInputInfoBinding.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。");
//        BaseUtils.disableEditText(binding.delivererPhone);
        BaseUtils.disableEditText(binding.delivererPhoneConfirm);
        BaseUtils.disableEditText(binding.mailNo);

        try {
            MainActivity activity = (MainActivity) getActivity();
            timer = TimeOutUtils.timeout(activity, InputInfoFragment.this, binding.timeout, 120);
            timer.start();
        } catch (Exception e) {
            Log.e(TAG, "onViewCreated: 倒计时出现异常! ", e);
            LoggingUtils.sendErrorLog("业务异常: 输入投递信息页面倒计时出现异常! ", e);
        }

        Bundle arguments = null;
        String sectionType = null;
        try {
            MainActivity activity = (MainActivity) getActivity();
            arguments = activity.getBundleMap().get(ChooseCabinetFragment.class.getName());
            sectionType = arguments.getString("section_type");

            // 扫描枪监听 扫描运单号
            activity.scanGunKeyEventHelper = new ScanGunKeyEventHelper(s -> {
                // 扫码成功回调
                Log.d(TAG, "onScanSuccess: " + s);

                if (!StringUtils.isNullOrEmpty(s)) {
                    for (String pattern : ScanGunConstant.getPatterns()) {
                        Matcher matcher = Pattern.compile(pattern).matcher(s);
                        if (!matcher.matches()) {
                            ToastUtils.make(getContext(), "请将条形码置于扫码枪前! ");
                            return;
                        }
                    }
                }

                if (mailNoLock.get() == 1) {
                    Editable text = binding.mailNo.getText();
                    text.clear();
                    binding.mailNo.setText(s);
                    mailNoLock.incrementAndGet();
                    // TODO 预定义,实际参数可能不一致 oms获取用户手机号 自动填充
                    ICSPClient.getUserPhoneNumber(LocalStorage.getInstance().getSession().getToken(), BaseUtils.getClientId(), s, new Callback() {
                        @Override
                        public void onFailure(@NotNull Call call, @NotNull IOException e) {
                            // 请求失败
                            Log.e(TAG, "onFailure: 请求oms获取手机号失败! 网络异常! ", e);
                            LoggingUtils.sendErrorLog("业务异常: 请求oms获取手机号失败! 网络异常! ", e);
                            ToastUtils.make(getContext(), "服务器异常! 请手动输入!");
                            mailNoLock.set(1);
                        }

                        @Override
                        public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {

                            getActivity().runOnUiThread(() -> {
                                String parseResponse = ICSPClient.isSuccessfulAndParseResponse(response);
                                if (!StringUtils.isNullOrEmpty(parseResponse)) {
                                    try {
                                        ResponseData<PreparedOrderResponseVo> responseData = new ObjectMapper().readValue(parseResponse, new TypeReference<ResponseData<PreparedOrderResponseVo>>() {
                                        });

                                        PreparedOrderResponseVo data = responseData.getData();
                                        if (null != responseData && ICSPConstant.OK.equals(responseData.getCode())) {
                                            String collectorPhone = data.getCollectorPhone();
                                            binding.delivererPhoneConfirm.setText(collectorPhone);
                                        } else {
                                            ToastUtils.make(getContext(), responseData.getMsg());
                                        }

                                    } catch (JsonProcessingException e) {
                                        Log.e(TAG, "onResponse: 服务器响应错误! 自动获取用户手机号失败! ", e);
                                        ToastUtils.make(getContext(), "网络异常! 请手动输入手机号! ");
                                        LoggingUtils.sendErrorLog("业务异常: 服务器响应错误! 自动获取用户手机号失败! ", e);
                                    } catch (RuntimeException e) {
                                        Log.e(TAG, "onResponse: 获取用户手机号未知错误! ", e);
                                        ToastUtils.make(getContext(), "未查询到手机号! 请手动输入! ");
                                        LoggingUtils.sendErrorLog("业务异常: 获取用户手机号未知错误! ", e);
                                    }
                                } else {
                                    ToastUtils.make(getContext(), "服务器异常！请稍后重试！");
                                }
                                mailNoLock.set(1);
                            });

                        }
                    });
                }
            });

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

        // TODO 离线逻辑, 暂时不做

        Pattern phonePattern = Pattern.compile("^((13[0-9])|(14[0,1,4-9])|(15[0-3,5-9])|(16[2,5,6,7])|(17[0-8])|(18[0-9])|(19[0-3,5-9]))\\d{8}$");
        // 下单逻辑
        String finalSectionType = sectionType;
        if (submitLock.get() == 1) {
            submitLock.incrementAndGet();
            binding.buttonConfirm.setOnClickListener(view1 -> {
                Bundle bundle = new Bundle();
                String mailNo = binding.mailNo.getText().toString();
//            String phone = binding.delivererPhone.getText().toString();
                String phoneConfirm = binding.delivererPhoneConfirm.getText().toString();
                if (!phonePattern.matcher(phoneConfirm).matches()) {
                    ToastUtils.make(getContext(), "请输入正确的手机号！");
                } else if (StringUtils.isNullOrEmpty(mailNo)) {
                    ToastUtils.make(getContext(), "运单号不能为空！请扫描运单号！");
                } else {
                    // 验证完 预下单
                    PreparedOrderVo preparedOrderVo = new PreparedOrderVo();
                    preparedOrderVo.setClientId(BaseUtils.getClientId());
                    preparedOrderVo.setMailNo(mailNo);
                    preparedOrderVo.setCollectorPhone(phoneConfirm);
                    preparedOrderVo.setLockerType(finalSectionType);
                    preparedOrderVo.setDelivererPhone(LocalStorage.getInstance().getSession().getPhone());

                    // 预下单
                    ICSPClient.preparedOrder(LocalStorage.getInstance().getSession().getToken(), 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("takeNo", mailNo);
                                            bundle.putString("sectionType", finalSectionType);

                                            // 跳转到确认投递
                                            try {
                                                MainActivity activity = (MainActivity) getActivity();
                                                activity.getBundleMap().put(InputInfoKeyBoardFragment.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(InputInfoFragment.this, R.id.action_InputInfoKeyBoardFragment_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);
                                }
                            });
                        }
                    });
                }
            });

        }

        // 数字输入 5 手机号   4 密码

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

        binding.mailNo.setOnFocusChangeListener((view1, hasFocus) -> {
            if (hasFocus) {
                binding.inputButton0.setOnClickListener(v -> {
                    int start = binding.mailNo.getSelectionStart();
                    binding.mailNo.getText().insert(start, "0");
                });
                binding.inputButton1.setOnClickListener(v -> {
                    int start = binding.mailNo.getSelectionStart();
                    binding.mailNo.getText().insert(start, "1");
                });
                binding.inputButton2.setOnClickListener(v -> {
                    int start = binding.mailNo.getSelectionStart();
                    binding.mailNo.getText().insert(start, "2");
                });
                binding.inputButton3.setOnClickListener(v -> {
                    int start = binding.mailNo.getSelectionStart();
                    binding.mailNo.getText().insert(start, "3");
                });
                binding.inputButton4.setOnClickListener(v -> {
                    int start = binding.mailNo.getSelectionStart();
                    binding.mailNo.getText().insert(start, "4");
                });
                binding.inputButton5.setOnClickListener(v -> {
                    int start = binding.mailNo.getSelectionStart();
                    binding.mailNo.getText().insert(start, "5");
                });
                binding.inputButton6.setOnClickListener(v -> {
                    int start = binding.mailNo.getSelectionStart();
                    binding.mailNo.getText().insert(start, "6");
                });
                binding.inputButton7.setOnClickListener(v -> {
                    int start = binding.mailNo.getSelectionStart();
                    binding.mailNo.getText().insert(start, "7");
                });
                binding.inputButton8.setOnClickListener(v -> {
                    int start = binding.mailNo.getSelectionStart();
                    binding.mailNo.getText().insert(start, "8");
                });
                binding.inputButton9.setOnClickListener(v -> {
                    int start = binding.mailNo.getSelectionStart();
                    binding.mailNo.getText().insert(start, "9");
                });
                binding.inputButtonCancel.setOnClickListener(v -> {
                    Editable text = binding.mailNo.getText();
                    int start = binding.mailNo.getSelectionStart();
                    if (text.length() > 0) {
                        if (start > 0) {
                            text.delete(start-1, start);
                        }
                        binding.mailNo.setText(text, TextView.BufferType.EDITABLE);
                        binding.mailNo.setSelection(start-1<0 ? text.length() : start-1);
                    }
                });
                // 长按删除
                binding.inputButtonCancel.setOnLongClickListener(v -> {
                    binding.mailNo.getText().clear();
                    return false;
                });
            }
        });

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

        // 默认选中运单号输入框
        if (StringUtils.isNullOrEmpty(binding.mailNo.getText().toString())) {
            binding.mailNo.requestFocus();
        }
    }

    public PreparedOrderResponseVo getData() {
        return data;
    }

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