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.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.FragmentSendBinding;
import com.emato.ich.entity.vo.ResponseData;
import com.emato.ich.entity.vo.ResponseTokenVo;
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 org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.regex.Pattern;

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

/**
 * 投递员登录页面
 */
public class SendFragment extends Fragment {

    private static final String TAG = SendFragment.class.getName();
    private FragmentSendBinding binding;
    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 = FragmentSendBinding.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.editTextTextPersonName4);
        BaseUtils.disableEditText(binding.editTextTextPersonName5);

        try {
            MainActivity activity = (MainActivity) getActivity();
            timer = TimeOutUtils.timeout(activity, SendFragment.this, binding.timeout, 60);
            timer.start();
        } catch (Exception e) {
            Log.e(TAG, "onViewCreated: 倒计时异常! ", e);
            LoggingUtils.sendErrorLog("业务异常: 投递员登录页面倒计时异常! ", e);
        }

        // 如果有配置账号密码, 账号定死
        String loginPhone = null;
        try {
            MainActivity activity = (MainActivity) getActivity();
            loginPhone = activity.getConfigMap().get(SystemConfigConstant.cabinet_login_phone);
        } catch (Exception e) {
            Log.e(TAG, "onViewCreated: 配置登录手机号出错! ", e);
            LoggingUtils.sendErrorLog("业务异常: 配置登录手机号出错! ", e);
        }
        if (!StringUtils.isNullOrEmpty(loginPhone)) {
            //String loginPhoneShow = toHidePhone(loginPhone);
            binding.editTextTextPersonName4.setText(loginPhone);
            binding.editTextTextPersonName4.setEnabled(false);
        } else {
            // 4 手机
            binding.editTextTextPersonName4.setOnFocusChangeListener((view1, hasFocus) -> {
                if (hasFocus) {
                    binding.inputButton0.setOnClickListener(v -> {
                        int length = binding.editTextTextPersonName4.getText().length();
                        if (length >= 11) {
                            ToastUtils.make(getContext(), "手机号不能超过11位! ");
                            return;
                        }
                        int start = binding.editTextTextPersonName4.getSelectionStart();
                        binding.editTextTextPersonName4.getText().insert(start, "0");
                    });
                    binding.inputButton1.setOnClickListener(v -> {
                        int length = binding.editTextTextPersonName4.getText().length();
                        if (length >= 11) {
                            ToastUtils.make(getContext(), "手机号不能超过11位! ");
                            return;
                        }
                        int start = binding.editTextTextPersonName4.getSelectionStart();
                        binding.editTextTextPersonName4.getText().insert(start, "1");
                    });
                    binding.inputButton2.setOnClickListener(v -> {
                        int length = binding.editTextTextPersonName4.getText().length();
                        if (length >= 11) {
                            ToastUtils.make(getContext(), "手机号不能超过11位! ");
                            return;
                        }
                        int start = binding.editTextTextPersonName4.getSelectionStart();
                        binding.editTextTextPersonName4.getText().insert(start, "2");
                    });
                    binding.inputButton3.setOnClickListener(v -> {
                        int length = binding.editTextTextPersonName4.getText().length();
                        if (length >= 11) {
                            ToastUtils.make(getContext(), "手机号不能超过11位! ");
                            return;
                        }
                        int start = binding.editTextTextPersonName4.getSelectionStart();
                        binding.editTextTextPersonName4.getText().insert(start, "3");
                    });
                    binding.inputButton4.setOnClickListener(v -> {
                        int length = binding.editTextTextPersonName4.getText().length();
                        if (length >= 11) {
                            ToastUtils.make(getContext(), "手机号不能超过11位! ");
                            return;
                        }
                        int start = binding.editTextTextPersonName4.getSelectionStart();
                        binding.editTextTextPersonName4.getText().insert(start, "4");
                    });
                    binding.inputButton5.setOnClickListener(v -> {
                        int length = binding.editTextTextPersonName4.getText().length();
                        if (length >= 11) {
                            ToastUtils.make(getContext(), "手机号不能超过11位! ");
                            return;
                        }
                        int start = binding.editTextTextPersonName4.getSelectionStart();
                        binding.editTextTextPersonName4.getText().insert(start, "5");
                    });
                    binding.inputButton6.setOnClickListener(v -> {
                        int length = binding.editTextTextPersonName4.getText().length();
                        if (length >= 11) {
                            ToastUtils.make(getContext(), "手机号不能超过11位! ");
                            return;
                        }
                        int start = binding.editTextTextPersonName4.getSelectionStart();
                        binding.editTextTextPersonName4.getText().insert(start, "6");
                    });
                    binding.inputButton7.setOnClickListener(v -> {
                        int length = binding.editTextTextPersonName4.getText().length();
                        if (length >= 11) {
                            ToastUtils.make(getContext(), "手机号不能超过11位! ");
                            return;
                        }
                        int start = binding.editTextTextPersonName4.getSelectionStart();
                        binding.editTextTextPersonName4.getText().insert(start, "7");
                    });
                    binding.inputButton8.setOnClickListener(v -> {
                        int length = binding.editTextTextPersonName4.getText().length();
                        if (length >= 11) {
                            ToastUtils.make(getContext(), "手机号不能超过11位! ");
                            return;
                        }
                        int start = binding.editTextTextPersonName4.getSelectionStart();
                        binding.editTextTextPersonName4.getText().insert(start, "8");
                    });
                    binding.inputButton9.setOnClickListener(v -> {
                        int length = binding.editTextTextPersonName4.getText().length();
                        if (length >= 11) {
                            ToastUtils.make(getContext(), "手机号不能超过11位! ");
                            return;
                        }
                        int start = binding.editTextTextPersonName4.getSelectionStart();
                        binding.editTextTextPersonName4.getText().insert(start, "9");
                    });
                    binding.inputButtonCancel.setOnClickListener(v -> {
                        Editable text = binding.editTextTextPersonName4.getText();
                        int start = binding.editTextTextPersonName4.getSelectionStart();
                        if (text.length() > 0) {
                            if (start > 0) {
                                text.delete(start-1, start);
                            }
                            binding.editTextTextPersonName4.setText(text, TextView.BufferType.EDITABLE);
                            binding.editTextTextPersonName4.setSelection(start-1<0 ? text.length() : start-1);
                        }
                    });
                    // 长按删除
                    binding.inputButtonCancel.setOnLongClickListener(v -> {
                        binding.editTextTextPersonName4.getText().clear();
                        return false;
                    });
                }
            });
        }

        String finalLoginPhone = loginPhone;
        binding.inputButtonConfirm.setOnClickListener(view1 -> {
            if (ButtonUtils.isFastClick()) {
                return;
            }
            // 登录逻辑  editTextTextPersonName4 手机 editTextTextPersonName5 密码
            String sendPhone =  binding.editTextTextPersonName4.getText().toString();
            String password = binding.editTextTextPersonName5.getText().toString();

            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}$");
            Pattern pwdPattern = Pattern.compile("^[0-9]{8,16}$");

            if (phonePattern.matcher(sendPhone).matches() && pwdPattern.matcher(password).matches()) {

                ICSPClient.login(sendPhone, password, 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 {
                        ((MainActivity) getActivity()).runOnUiThread(() -> {
                            String responseStr = ICSPClient.isSuccessfulAndParseResponse(response);
                            if (!StringUtils.isNullOrEmpty(responseStr)) {
                                try {
                                    ResponseData<ResponseTokenVo> responseData = JacksonUtils.objectmapper.readValue(responseStr, new TypeReference<ResponseData<ResponseTokenVo>>() {});
                                    ResponseTokenVo data = responseData.getData();

                                    if (responseData.getCode().equals(ICSPConstant.OK)) {
                                        LocalStorage.Session session = new LocalStorage.Session();
                                        session.setPhone(sendPhone);
                                        session.setTime(System.currentTimeMillis());
                                        session.setToken(data.getToken());
                                        MainActivity activity = (MainActivity) getActivity();
                                        LocalStorage.getInstance().cleanSession(activity,false);
                                        LocalStorage.getInstance().setSession(session);

                                        // 登录成功
                                        ToastUtils.make(getContext(), "登录成功！");
                                        if (null != timer) {
                                            timer.cancel();
                                        }
                                        NavUtils.navigate(SendFragment.this, R.id.action_sendFragment_to_sendMainFragment);
                                    } else {
                                        ToastUtils.make(getContext(), responseData.getMsg());
                                        Log.w(TAG, "onResponse: " + responseData.getMsg());
                                    }

                                } catch (JsonProcessingException e) {
                                    Log.e(TAG, "onViewCreated: 解析登录响应信息错误! response body: " + responseStr, e);
                                    ToastUtils.make(getContext(), "登录失败！");
                                    LoggingUtils.sendErrorLog("业务异常: 登录失败！", e);
                                } catch (ClassCastException e) {
                                    Log.e(TAG, "onResponse: 解析登录响应信息类型转换错误! response body: " + responseStr, 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(), "服务异常！请稍后重试！");
                            }
                        });
                    }
                });
            } else if (!phonePattern.matcher(sendPhone).matches()){
                ToastUtils.make(getContext(), "输入正确的手机号！");
            } else if (!pwdPattern.matcher(password).matches()) {
                ToastUtils.make(getContext(), "密码格式错误！请输入8-16位的数字！");
            }
        });

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

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


        // 默认选中密码输入
        if (!StringUtils.isNullOrEmpty(binding.editTextTextPersonName4.getText().toString())) {
            binding.editTextTextPersonName5.requestFocus();
        } else {
            binding.editTextTextPersonName4.requestFocus();
        }
    }

    /**
     * 隐藏部分信息
     * @param loginPhone    投递员手机号
     * @return              隐藏后的手机号
     */
    private String toHidePhone(String loginPhone) {
        StringBuilder stringBuilder = new StringBuilder();
        char[] chars = loginPhone.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            if (i > 2 && i < 8) {
                stringBuilder.append('*');
            } else {
                stringBuilder.append(chars[i]);
            }
        }
        return stringBuilder.toString();
    }

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

        Log.i(TAG, TAG + "被销毁。。。");
    }

}