package com.qy.agv.activity;

import static com.qy.agv.comm.BaseApplication.mScanManager;
import static com.qy.agv.util.Constant.CACHE_BIND_CONTROL;
import static com.qy.agv.util.Constant.CACHE_LOGIN_KEY;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
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.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.SimpleAdapter;
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.qy.agv.R;
import com.qy.agv.activity.adapter.HomeListViewAdapter;
import com.qy.agv.activity.adapter.MainListViewAdapter;
import com.qy.agv.activity.dao.MainDao;
import com.qy.agv.activity.model.BinLocModel;
import com.qy.agv.activity.model.EventMessage;
import com.qy.agv.activity.model.OrderTaskModel;
import com.qy.agv.activity.model.RobotModel;
import com.qy.agv.activity.model.ShelfModel;
import com.qy.agv.activity.model.TaskModel;
import com.qy.agv.activity.model.UserModel;
import com.qy.agv.comm.BaseActivity;
import com.qy.agv.comm.CacheService;
import com.qy.agv.comm.Res;
import com.qy.agv.databinding.ActivityHomeBinding;
import com.qy.agv.databinding.ActivityMainBinding;
import com.qy.agv.update.UpdateManager;
import com.qy.agv.util.Constant;
import com.qy.agv.util.HttpsUtil;
import com.qy.agv.util.MD5Encryption;
import com.qy.agv.util.MyProgress;
import com.qy.agv.util.Permission;
import com.qy.agv.util.ProjectUtils;
import com.qy.agv.util.StringUtils;
import com.qy.agv.util.ToastUtils;
import com.qy.agv.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.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

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

    private ActivityHomeBinding binding;
    private Context context;
    private HomeListViewAdapter listViewAdapter;
    private ArrayList<OrderTaskModel> mList;
    private UserModel user;
    private Button submit;
    private PopupWindow popupWindow2;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityHomeBinding.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();
        }, 5000);
    }

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


    private void initData(){
        mList = new ArrayList<>();
        listViewAdapter = new HomeListViewAdapter(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.lvComment.setOnItemClickListener((parent, view, position, id) -> {
            OrderTaskModel orderTaskModel = mList.get(position);
            Bundle bundle = new Bundle();
            bundle.putString("id", orderTaskModel.getId());
            toActivity(OrderTaskInfoActivity.class, bundle);
        });
        binding.swipeContainer.autoRefresh();
    }

    private void initView(){
        submit = findViewById(R.id.c_iv_common_submit);
        submit.setBackgroundColor(Res.getColor("transparent"));
        submit.setTextColor(Res.getColor("white"));
        submit.setVisibility(View.GONE);
//        submit.setText("未登录");
//        submit.setOnClickListener(view -> {
//            if("未登录".contentEquals(submit.getText())) {
//                login();
//            }else{
//                Bundle bundle = new Bundle();
//                bundle.putString("from", "2");
//                toActivity(RobotInfoActivity.class, bundle);
//            }
//        });
//        submit.setOnLongClickListener(v -> {
//            toActivity(RobotInfoActivity.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);
        }
        if(Constant.MODEL.contains("MV-IDP")){
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction(ACTION_PDA_SERVICE_SCANNER_DATA);
            registerReceiver(mHkReceiver, intentFilter);
        }
        if(Constant.MODEL.contains("L2KS")){
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction(ACTION_DATA_CODE_RECEIVED);
            registerReceiver(mSumReceiver, intentFilter);
        }
    }

    public void checkToken(String loginName, String loginPwd) {
        MyProgress progress = MyProgress.getInstance();
        progress.show(context, "提示", "正在登录");
        try {
            RequestParams params = httParams(Constant.LOG_IN);
            params.addBodyParameter("grant_type", "password");
            params.addBodyParameter("username", loginName);
            if (StringUtils.isEmpty(loginName)) {
                ToastUtils.showToast(context, "账号不能为空");
                return;
            }
            if (StringUtils.isEmpty(loginPwd)) {
                ToastUtils.showToast(context, "密码不能为空");
                return;
            }
            //      密码md5加密
            String pwdMd5 = MD5Encryption.encrypt(loginPwd);
            params.addBodyParameter("password", pwdMd5);
            x.http().post(params, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String arg0) {
                    mylog.debug(arg0);
                    try {
                        if (arg0.contains("error_description")) {
                            JSONObject object = new JSONObject(arg0);
                            ToastUtils.showToast(context, object.getString("error_description"));
                        } else {
                            user = new Gson().fromJson(arg0, UserModel.class);
                            user.setLoginName(loginName);
                            user.setLoginPwd(loginPwd);
                            Constant.ACCESS_TOKEN = user.getAccess_token();
                            Constant.REFRESH_TOKEN = user.getAccess_token();
                            arg0 = new Gson().toJson(user);
                            CacheService.getInstance(context).saveCache(CACHE_LOGIN_KEY, "user", arg0);
                            if (user.getUser_id() != null) {
                                if (popupWindow2 != null) {
                                    popupWindow2.dismiss();
                                }
                                Constant.user = user;
                                Object real_name_obj = user.getReal_name();
                                if (real_name_obj != null) {
                                    submit.setText(real_name_obj.toString());
                                }
                                searchTask(0);
                            }
                        }
                    } 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);
        }
    }

    @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 (user == null) {
                ToastUtils.showToast(context, "该设备没有登录");
                return;
            }

        }catch (Exception ex){
            mylog.error("任务发送异常：", ex);
            ToastUtils.showToast(context, "发送异常");
        }
    }

    public void setBackgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha;
        getWindow().setAttributes(lp);
    }

    private void searchTask(int from) {
        MyProgress myProgress = MyProgress.getInstance();
        if(from == 0) {
            myProgress.show(context, "提示", "正在加载");
        }
        RequestParams params = httParams(Constant.ORDER_TASK_LIST);
//        params.addBodyParameter("requester", Constant.user.getUser_id().toString());
        params.addBodyParameter("current", "1");
        params.addBodyParameter("size", "100");
//        params.addBodyParameter("distributionTime", DateUtil.getCurrDate(Constant.DATE_FORMATE));
        x.http().get(params, new Callback.CommonCallback<JSONObject>() {
            @Override
            public void onSuccess(JSONObject rs) {
                mylog.info(rs.toString());
                try {
                    if (rs.getInt("code") != 200) {
                        ToastUtils.showToast(context, "请求失败");
                    } else {
                        if (rs.getBoolean("success")) {
                            System.out.println(rs.get("data"));
                            Type rds = new TypeToken<Map<String, JsonElement>>() {
                            }.getType();
                            Map<String, JsonElement> records = new Gson().fromJson(rs.get("data").toString(), rds);
                            int pages = rs.getJSONObject("data").getInt("pages");
                            System.out.println(records.get("records"));
                            Type lt = new TypeToken<ArrayList<OrderTaskModel>>() {}.getType();
                            Object recodes_obj = records.get("records");
                            if(recodes_obj!=null) {
                                if(from == 0) {
                                    mList.clear();
                                    List<OrderTaskModel> taskModelList = new Gson().fromJson(recodes_obj.toString(), lt);
                                    mList.addAll(taskModelList);
                                    reloadView();
                                }
                                if(from == 1){
                                    List<OrderTaskModel> taskModelList = new Gson().fromJson(recodes_obj.toString(), lt);
                                    updateList(taskModelList);
                                }
                            }
                        }
                    }
                } 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() {
                myProgress.close();
            }

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

    public void reloadView(){
        if(mList.size() > 0) {
            binding.swipeContainer.setVisibility(View.VISIBLE);
            binding.tvEmpty.setVisibility(View.GONE);
        }else{
            binding.swipeContainer.setVisibility(View.GONE);
            binding.tvEmpty.setVisibility(View.VISIBLE);
        }
        listViewAdapter.notifyDataSetChanged();
        binding.swipeContainer.setRefreshing(false);
        binding.swipeContainer.setLoading(false);
    }

    public void updateList(List<OrderTaskModel> n_list){
        if(mList.size() != n_list.size()){
            mList.clear();
            mList.addAll(n_list);
            reloadView();
        }else{
            for (OrderTaskModel taskModel:mList){
                String id = taskModel.getId();
                for (OrderTaskModel nTaskModel:n_list){
                    if(id.equals(nTaskModel.getId())){
                        taskModel.setStatus(nTaskModel.getStatus());
                    }
                }
            }
            listViewAdapter.notifyDataSetChanged();
        }
    }

    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)){
            user = new Gson().fromJson(userStr, UserModel.class);
            loginName.setText(user.getLoginName());
            loginPassword.setText(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() == 2){
            logout();
        }
        if(message.getType() == 3){
            searchTask(1);
        }
    }
}