package com.ygtx.emcs.activity;

import static com.ygtx.emcs.comm.BaseApplication.mScanManager;
import static com.ygtx.emcs.util.Constant.CACHE_BIND_CONFIG;
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.Intent;
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.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.PopupWindow;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ygtx.emcs.R;
import com.ygtx.emcs.activity.adapter.FunctionMenuAdapter;
import com.ygtx.emcs.activity.adapter.MainListViewAdapter;
import com.ygtx.emcs.activity.model.ConfigModel;
import com.ygtx.emcs.activity.model.EventMessage;
import com.ygtx.emcs.activity.model.MainModel;
import com.ygtx.emcs.activity.model.MaterialStockModel;
import com.ygtx.emcs.activity.model.MenuModel;
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.YgtxHomeActivityBinding;
import com.ygtx.emcs.update.UpdateManager;
import com.ygtx.emcs.util.Constant;
import com.ygtx.emcs.util.DataUtil;
import com.ygtx.emcs.util.DateUtil;
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.UUID;
import java.util.concurrent.TimeUnit;


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

    private YgtxHomeActivityBinding binding;
    private Context context;
    private ImageView submit;
    private PopupWindow popupWindow;
    private PopupWindow popupWindow2;
    private List<MenuModel> menuModels = new ArrayList<>();
    private FunctionMenuAdapter mainViewAdapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = YgtxHomeActivityBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        context = this;
        ProjectUtils.init(this);
        registerReceiver();
        initCommonTop2();
        initLogin();
        initView();
        Permission.checkPermission(this);
        EventBus.getDefault().register(this);
        checkNet();
//        binding.tvLoginName.setOnClickListener(v->{
//            receiverTask("CK_20250304002");
//        });
//        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 initLogin(){
        CacheService.getInstance(context).saveCache(CACHE_BIND_CONFIG, "in_stock_flag", "RK");
        CacheService.getInstance(context).saveCache(CACHE_BIND_CONFIG, "out_stock_flag", "CK");
        CacheService.getInstance(context).saveCache(CACHE_BIND_CONFIG, "box_flag", "BOX");

        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())){
                Constant.ACCESS_TOKEN = null;
                checkToken(Constant.user.getLoginName(), Constant.user.getLoginPwd());
            }
        }
    }

    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(FunctionActivity.class);
            if (Constant.user == null) {
                ToastUtils.showToast(context, "请先登录");
                return;
            }
            back.setEnabled(false);
            getUserMenu();
            new Handler().postDelayed(()->{
                back.setEnabled(true);
            }, 1000);
        });

        submit = findViewById(R.id.c_iv_common_person);
        submit.setVisibility(View.VISIBLE);
        submit.setImageDrawable(getDrawable(R.mipmap.ic_action_settings));
        submit.setOnClickListener(view -> {
            toActivity(AppInfoActivity.class);
        });

        binding.loginExit.setText("登录");
        binding.loginExit.setOnClickListener(view->{
            if("登录".contentEquals(binding.loginExit.getText())){
                login();
            }else{
//                myLogout();
                logout();
            }
        });
    }

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

    public void checkToken(String loginName, String loginPwd) {
        MyProgress progress = MyProgress.getInstance();
        try {
            Constant.ACCESS_TOKEN = "";
            progress.show(context, "提示", "正在登录");
            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) {
                            logoutAuth(json.getInt("code"));
                            String msg = json.getString("msg");
                            ToastUtils.showToast(context, msg);
                            return;
                        }
                        Constant.ACCESS_TOKEN = json.getString("token");
                        if (popupWindow2 != null) {
                            popupWindow2.dismiss();
                        }
                        getUserInfo(loginName, loginPwd);
                        getConfig();
                    } catch (JSONException e) {
                        e.printStackTrace();
                        mylog.error(e);
                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    ex.printStackTrace();
                    HttpsUtil.parserError(HomeActivity.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(String loginName, String loginPwd){
        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) {
                        Constant.user = new Gson().fromJson(rs.getString("user"), UserModel.class);
                        Constant.user.setLoginName(loginName);
                        Constant.user.setLoginPwd(loginPwd);
                        Object userName = Constant.user.getUserName();
                        if (userName != null) {
                            showUser();
                        }
                    }else if(rs.getInt("code") == 401){
                        ToastUtils.showToast(context, "会话过期");
                        logoutAuth(rs.getInt("code"));
                    }else{
                        ToastUtils.showToast(context, rs.getString("msg"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ex.printStackTrace();
                HttpsUtil.parserError(HomeActivity.this, ex);
                mylog.error("请求异常：", ex);
            }
            @Override
            public void onFinished() {

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

    private void getUserMenu(){
        RequestParams params = httParams(Constant.GET_USER_MENU);
        x.http().get(params, new Callback.CommonCallback<JSONObject>() {
            @Override
            public void onSuccess(JSONObject rs) {
                mylog.info(rs);
                try {
                    menuModels.clear();
                    if (rs.getInt ("code")== 200) {
                        Type rds = new TypeToken<List<MenuModel>>() {}.getType();
                        menuModels = new Gson().fromJson(rs.get("data").toString(), rds);
                    }else if(rs.getInt("code") == 401){
                        ToastUtils.showToast(context, "会话过期");
                        logoutAuth(rs.getInt("code"));
                    }else{
                        ToastUtils.showToast(context, rs.getString("msg"));
                    }
                    openFunction();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ex.printStackTrace();
                HttpsUtil.parserError(HomeActivity.this, ex);
                mylog.error("请求异常：", ex);
            }
            @Override
            public void onFinished() {

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

    private void getConfig(){
        RequestParams params = httParams(Constant.GET_CONFIG);
        params.addBodyParameter("configKey", "rms.");
        x.http().get(params, new Callback.CommonCallback<JSONObject>() {
            @Override
            public void onSuccess(JSONObject rs) {
                mylog.info(rs);
                try{
                    if (rs.getInt("code") == 200) {
                        Type rds = new TypeToken<List<ConfigModel>>() {}.getType();
                        List<ConfigModel> configModels = new Gson().fromJson(rs.get("rows").toString(), rds);
                        setCache(configModels);
                    }else if(rs.getInt("code") == 401){
                        ToastUtils.showToast(context, "会话过期");
                        logoutAuth(rs.getInt("code"));
                    }else{
                        ToastUtils.showToast(context, rs.getString("msg"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    mylog.error("回调异常:", e);
                }
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ex.printStackTrace();
                HttpsUtil.parserError(HomeActivity.this, ex);
                mylog.error("请求异常：", ex);
            }
            @Override
            public void onFinished() {

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

    private void setCache(List<ConfigModel> stockModels){
        stockModels.forEach(item->{
            String key = item.getConfigKey();
            String val = item.getConfigValue();
            if(key.equals(Constant.BOX_KEY)){
                CacheService.getInstance(context).saveCache(CACHE_BIND_CONFIG, "box_flag", val);
            }
            if(key.equals(Constant.IN_STOCK_KEY)){
                CacheService.getInstance(context).saveCache(CACHE_BIND_CONFIG, "in_stock_flag", val);
            }
            if(key.equals(Constant.OUT_STOCK_KEY)){
                CacheService.getInstance(context).saveCache(CACHE_BIND_CONFIG, "out_stock_flag", val);
            }
        });
    }

    @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, "该设备没有登录");
            }
            checkOrderCode(barcode);
        }catch (Exception ex){
            mylog.error("任务发送异常：", ex);
            ToastUtils.showToast(context, "发送异常");
        }
    }

    private void checkOrderCode(String barcode){
        String in_stock_flag = CacheService.getInstance(context).getCache(CACHE_BIND_CONFIG, "in_stock_flag");
        if(StringUtils.isEmpty(in_stock_flag)){
            ToastUtils.showToast(context, "请设置入库单编码的标识");
            return;
        }
        if(barcode.startsWith(in_stock_flag)){
            Bundle bundle = new Bundle();
            bundle.putString("erpInstockCode", barcode);
            toActivity(StockInNewActivity.class, bundle);
            return;
        }
        String out_stock_flag = CacheService.getInstance(context).getCache(CACHE_BIND_CONFIG, "out_stock_flag");
        if(StringUtils.isEmpty(out_stock_flag)){
            ToastUtils.showToast(context, "请设置出库单编码的标识");
            return;
        }
        if(barcode.startsWith(out_stock_flag)){
            Bundle bundle = new Bundle();
            bundle.putString("erpOutstockCode", barcode);
            toActivity(StockOutNewActivity.class, bundle);
        }
    }

    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;
        clearUser();
    }

    private void showUser(){
        binding.tvLoginName.setText(Constant.user.getUserName());
        binding.tvNickName.setText(Constant.user.getNickName());
        binding.tvLoginTime.setText(DateUtil.getCurrDate());
        binding.loginExit.setText("退出");
        CacheService.getInstance(context).saveCache(CACHE_LOGIN_KEY, "user", new Gson().toJson(Constant.user));
    }

    private void clearUser(){
        binding.tvLoginName.setText("");
        binding.tvLoginTime.setText("");
        binding.tvNickName.setText("未登录");
        binding.loginExit.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);
    }

    private void openFunction(){
        View view = binding.getRoot().getRootView();
        View popup_login_view= LayoutInflater.from(context).inflate(R.layout.ygtx_function_activy,null);
        GridView gridView = popup_login_view.findViewById(R.id.gridView);
        initList(gridView);
        WindowManager manager = this.getWindowManager();
        DisplayMetrics outMetrics = new DisplayMetrics();
        manager.getDefaultDisplay().getMetrics(outMetrics);
        double width = outMetrics.widthPixels*0.8;
        popupWindow = new PopupWindow(view, (int) width,
                ViewGroup.LayoutParams.MATCH_PARENT);
        //设置窗体的内容
        popupWindow.setContentView(popup_login_view);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        popupWindow.setFocusable(true);
        popupWindow.setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
        popupWindow.setOnDismissListener(() -> {
            setBackgroundAlpha(1.0f);
        });
        setBackgroundAlpha(0.5f);
        popupWindow.setAnimationStyle(R.style.AnimationFade);
        popupWindow.showAtLocation(view, Gravity.START, 0, 0);
        popupWindow.update();
    }

    public void initList(GridView gridView){
        ArrayList<MainModel> list = new ArrayList<MainModel>();
        list = DataUtil.getMenus(menuModels);

        final ArrayList<MainModel> ds = list;
        mainViewAdapter = new FunctionMenuAdapter(list, this);
        gridView.setAdapter(mainViewAdapter);
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                MainModel shop = ds.get(arg2);
                Class actionClass = shop.getActionClass();
                if (actionClass==null){
                    ToastUtils.showToast(context,"正在开发");
                }else{
                    Intent intent = new Intent(context, actionClass);
                    startActivity(intent);
                    if(popupWindow!=null && popupWindow.isShowing()){
                        popupWindow.dismiss();
                    }
                }
            }
        });
        mainViewAdapter.notifyDataSetChanged();
    }

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