package com.ygtx.emcs.activity;

import static com.ygtx.emcs.comm.BaseApplication.mScanManager;
import static com.ygtx.emcs.util.Constant.CACHE_BIND_CONTROL;
import static com.ygtx.emcs.util.Constant.CACHE_LOGIN_KEY;

import android.content.Context;
import android.content.IntentFilter;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.reflect.TypeToken;
import com.ygtx.emcs.R;
import com.ygtx.emcs.activity.adapter.MainListViewAdapter;
import com.ygtx.emcs.activity.model.EventMessage;
import com.ygtx.emcs.activity.model.StockModel;
import com.ygtx.emcs.activity.model.TaskModel;
import com.ygtx.emcs.activity.model.UserModel;
import com.ygtx.emcs.comm.BaseActivity;
import com.ygtx.emcs.comm.CacheService;
import com.ygtx.emcs.comm.Res;
import com.ygtx.emcs.databinding.ActivityMainBinding;
import com.ygtx.emcs.update.UpdateManager;
import com.ygtx.emcs.util.Constant;
import com.ygtx.emcs.util.HttpsUtil;
import com.ygtx.emcs.util.MyProgress;
import com.ygtx.emcs.util.Permission;
import com.ygtx.emcs.util.ProjectUtils;
import com.ygtx.emcs.util.StringUtils;
import com.ygtx.emcs.util.ToastUtils;
import com.ygtx.emcs.util.ToolUtils;

import org.apache.log4j.Logger;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;


public class MainActivity extends BaseActivity {
    public static Logger mylog =Logger.getLogger(MainActivity.class);

    private ActivityMainBinding binding;
    private Context context;
    private MainListViewAdapter listViewAdapter;
    private ArrayList<StockModel> mList;
    private Button submit;
    private PopupWindow popupWindow;
    private PopupWindow popupWindow2;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        context = this;
        ProjectUtils.init(this);
        registerReceiver();
        initCommonTop2();
        initLogin();
        initView();
        initData();
        Permission.checkPermission(this);
        EventBus.getDefault().register(this);
        reloadData();
        checkNet();
        update();
    }

    private void checkNet(){
        new Thread(()->{
            while (true){
                try {
                    boolean rs = ToolUtils.checkUrl(Constant.HTTP_URL);
                    if(!rs){
                        int times = ToolUtils.ping2("www.baidu.com", 1, 3000);
                        runOnUiThread(()->{
                            binding.showMsg.setVisibility(View.VISIBLE);
                            if(times < 0){
                                binding.showMsg.setText("网络连接异常");
                            }else{
                                binding.showMsg.setText("服务器连接异常");
                            }
                        });
                    }else{
                        runOnUiThread(()->{
                            binding.showMsg.setVisibility(View.GONE);
                        });
                    }
                    TimeUnit.SECONDS.sleep(5);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void reloadData(){
        new Handler().postDelayed(()->{
            if(Constant.user != null) {
                searchTask(1);
            }
            reloadData();
        }, 10000);
    }

    private void initLogin(){
        String userStr = CacheService.getInstance(context).getCache(CACHE_LOGIN_KEY, "user");
        if(!StringUtils.isEmpty(userStr)){
            Constant.user = new Gson().fromJson(userStr, UserModel.class);
            if(!StringUtils.isEmpty(Constant.user.getLoginPwd()) && !StringUtils.isEmpty(Constant.user.getLoginName())){
                checkToken(Constant.user.getLoginName(), Constant.user.getLoginPwd());
            }
        }
    }


    private void initData(){
        mList = new ArrayList<>();
        listViewAdapter = new MainListViewAdapter(mList, context);
        binding.swipeContainer.setAdapter(listViewAdapter);
        binding.swipeContainer.setVisibility(View.GONE);
        binding.tvEmpty.setVisibility(View.VISIBLE);
        binding.swipeContainer.setColorSchemeResources(R.color.colorPrimary, R.color.colorPrimaryDark);
        binding.swipeContainer.setProgressViewEndTarget(true, 200);
        binding.swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                searchTask(0);
            }
        });
        binding.swipeContainer.autoRefresh();
    }

    private void initView(){
        ImageView back = findViewById(R.id.c_iv_common_back);
        back.setVisibility(View.VISIBLE);
        back.setImageDrawable(Res.getDrawable("list"));
        back.setOnClickListener(view -> {
//            toActivity(ControlActivity.class);
        });

        submit = findViewById(R.id.c_iv_common_submit);
        submit.setBackgroundColor(Res.getColor("transparent"));
        submit.setTextColor(Res.getColor("white"));
        submit.setVisibility(View.VISIBLE);
        submit.setText("未登录");
        submit.setOnClickListener(view -> {
            if("未登录".contentEquals(submit.getText())) {
//                checkToken(getMac(), getMac());
                login();
            }else{
                toActivity(AppInfoActivity.class);
            }
        });
        submit.setOnLongClickListener(v -> {
            toActivity(AppInfoActivity.class);
            return false;
        });
    }

    private void registerReceiver() {
        if (mScanManager != null) {
            IntentFilter filter = new IntentFilter();
            if(Constant.MODEL.contains("ET")) {
                filter.addAction(ET_SCAN_ACTION);
            }
            registerReceiver(mReceiver, filter);
        }
    }

    public void checkToken(String loginName, String loginPwd) {
        MyProgress progress = MyProgress.getInstance();
        progress.show(context, "提示", "正在登录");
        try {
            RequestParams params = httParams(Constant.LOG_IN);
            if (StringUtils.isEmpty(loginName)) {
                ToastUtils.showToast(context, "账号不能为空");
                return;
            }
            if (StringUtils.isEmpty(loginPwd)) {
                ToastUtils.showToast(context, "密码不能为空");
                return;
            }
            //      密码md5加密
            params.addParameter("password", loginPwd);
            params.addParameter("code", "YGTX_PASS_CODE");
            params.addParameter("uuid", UUID.randomUUID().toString());
            params.addParameter("username", loginName);
            x.http().post(params, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String arg0) {
                    mylog.debug(arg0);
                    try {
                        JSONObject json = new JSONObject(arg0);
                        Object code = json.get("code");
                        if(!json.has("code")){
                            ToastUtils.showToast(context, arg0);
                            return;
                        }
                        if (Integer.parseInt(code.toString()) != 200) {
                            String msg = json.getString("msg");
                            ToastUtils.showToast(context, msg);
                            return;
                        }
                        Constant.ACCESS_TOKEN = json.getString("token");
                        if (popupWindow2 != null) {
                            popupWindow2.dismiss();
                        }
                        getUserInfo();
                        searchTask(0);
                    } catch (JSONException e) {
                        e.printStackTrace();
                        mylog.error(e);
                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    ex.printStackTrace();
                    HttpsUtil.parserError(MainActivity.this, ex);
                }

                @Override
                public void onFinished() {
                    progress.close();
                }

                @Override
                public void onCancelled(CancelledException arg0) {
                    mylog.error("onRead:", arg0);
                }
            });
        }catch (Exception e){
            ToastUtils.showToast(context, "登录失败");
            mylog.error(e);
        }
    }

    private void getUserInfo(){
        RequestParams params = httParams(Constant.GET_INFO);
        x.http().get(params, new Callback.CommonCallback<JSONObject>() {
            @Override
            public void onSuccess(JSONObject rs) {
                mylog.info(rs);
                try {
                    if (rs.getInt ("code")!= 200) {
                        ToastUtils.showToast(context, rs.getString("msg"));
                    } else {
                        Constant.user = new Gson().fromJson(rs.getString("user"), UserModel.class);
                        Object userName = Constant.user.getUserName();
                        if (userName != null) {
                            submit.setText(userName.toString());
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ex.printStackTrace();
                HttpsUtil.parserError(MainActivity.this, ex);
                mylog.error("请求异常：", ex);
            }
            @Override
            public void onFinished() {

            }
            @Override
            public void onCancelled(CancelledException arg0) {
                mylog.error("onRead:", arg0);
            }
        });
    }

    @Override
    protected String getCommonTopTitle() {
        return Res.getString("app_name");
    }

    @Override
    protected int getCommonTopICO() {
        return 0;
    }

    @Override
    public void receiverTask(String barcode) {
        System.out.println("扫码：" + barcode);
        try {
            if (barcode.startsWith("05-")) {
                String loginName = barcode.split("-")[1];
                String[] login_password = loginName.split(",");
                checkToken(login_password[0], login_password[1]);
                return;
            }
            if (Constant.user == null) {
                ToastUtils.showToast(context, "该设备没有登录");
                return;
            }
            if (popupWindow != null && popupWindow.isShowing()) {
                popupWindow.dismiss();
                popupWindow = null;
            }
        }catch (Exception ex){
            mylog.error("任务发送异常：", ex);
            ToastUtils.showToast(context, "发送异常");
        }
    }

    private void searchTask(int from) {
        MyProgress myProgress = MyProgress.getInstance();
        if(from == 0) {
            myProgress.show(context, "提示", "正在加载");
        }
        if(Constant.user==null || Constant.user.getUserId() == null){
            return;
        }
        RequestParams params = httParams(Constant.STOCK_IN_LIST);
        params.addBodyParameter("requester", Constant.user.getUserId().toString());
        params.addBodyParameter("current", "1");
        params.addBodyParameter("size", "100");
        params.addBodyParameter("descs", "distribution_time");
    }

    private void logout(){
        Constant.user = null;
        CacheService.getInstance(context).clear(CACHE_BIND_CONTROL);
        CacheService.getInstance(context).clear(CACHE_LOGIN_KEY);
        Constant.ACCESS_TOKEN = null;
        Constant.REFRESH_TOKEN = null;
        mList.clear();
        listViewAdapter.notifyDataSetChanged();
        binding.swipeContainer.setVisibility(View.GONE);
        binding.tvEmpty.setVisibility(View.VISIBLE);
        submit.setText("未登录");
    }

    private void login(){
        View view = binding.getRoot().getRootView();
        View popup_login_view= LayoutInflater.from(context).inflate(R.layout.popupwindow_login,null);
        EditText loginName = popup_login_view.findViewById(R.id.tv_login_name);
        EditText loginPassword = popup_login_view.findViewById(R.id.tv_login_password);
        String userStr = CacheService.getInstance(context).getCache(CACHE_LOGIN_KEY, "user");
        if(!StringUtils.isEmpty(userStr)){
            Constant.user = new Gson().fromJson(userStr, UserModel.class);
            loginName.setText(Constant.user.getLoginName());
            loginPassword.setText(Constant.user.getLoginPwd());
        }
        Button cancel = popup_login_view.findViewById(R.id.bt_cancel);
        Button ok = popup_login_view.findViewById(R.id.bt_ok);
        cancel.setOnClickListener(v -> {
            popupWindow2.dismiss();
        });
        ok.setOnClickListener(v -> {
            String lName = loginName.getText().toString();
            String lPassword = loginPassword.getText().toString();
            checkToken(lName, lPassword);
        });
        WindowManager manager = this.getWindowManager();
        DisplayMetrics outMetrics = new DisplayMetrics();
        manager.getDefaultDisplay().getMetrics(outMetrics);
        double width = outMetrics.widthPixels*0.8;
        popupWindow2 = new PopupWindow(view, (int) width,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        //设置窗体的内容
        popupWindow2.setContentView(popup_login_view);
        popupWindow2.setOutsideTouchable(true);
        popupWindow2.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        popupWindow2.setFocusable(true);
        popupWindow2.setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
        popupWindow2.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                setBackgroundAlpha(1.0f);
            }
        });
        setBackgroundAlpha(0.5f);
        popupWindow2.showAtLocation(view, Gravity.CENTER, 0, 0);
    }

    public void update(){
        UpdateManager updateManager = new UpdateManager(context);
        try {
            updateManager.checkUpdate(context);
        }catch (Exception ex){
            ex.printStackTrace();
            mylog.error("更新检测异常", ex);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true, priority = 1)
    public void onReceiveMsg(EventMessage message){
        if(message.getType() == 1){
            logout();
        }
    }
}