package com.emato.ich;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.cherry.sdk.controller.utils.ScanGunKeyEventHelper;
import com.emato.ich.api.ICSPApi;
import com.emato.ich.api.ICSPClient;
import com.emato.ich.contant.ICSPConstant;
import com.emato.ich.contant.OpenLockerResponseConstant;
import com.emato.ich.contant.SystemConfigConstant;
import com.emato.ich.crash.CrashApplication;
import com.emato.ich.device.DeviceControl;
import com.emato.ich.entity.BzCabBizCfg;
import com.emato.ich.entity.Cabinet;
import com.emato.ich.entity.Message;
import com.emato.ich.entity.vo.ResponseData;
import com.emato.ich.entity.vo.ShellVo;
import com.emato.ich.enums.TakeButtonShowEnum;
import com.emato.ich.enums.TakeQrCodeShowEnum;
import com.emato.ich.local.LocalStorage;
import com.emato.ich.message.ICHPublishClient;
import com.emato.ich.message.ICHSubscribeClient;
import com.emato.ich.message.ICHTopic;
import com.emato.ich.message.MessageHandler;
import com.emato.ich.utils.BaseUtils;
import com.emato.ich.utils.JacksonUtils;
import com.emato.ich.utils.LoggingUtils;
import com.emato.ich.utils.StringUtils;
import com.emato.ich.utils.TimeThread;
import com.emato.ich.utils.ToastUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Looper;
import android.provider.SyncStateContract;
import com.emato.ich.utils.Log;

import android.util.ArrayMap;
import android.view.KeyEvent;

import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;

import com.emato.ich.databinding.ActivityMainBinding;
import com.hacknife.carouselbanner.Banner;
import com.hacknife.carouselbanner.CarouselBanner;
import com.hacknife.carouselbanner.CoolCarouselBanner;
import com.hacknife.carouselbanner.interfaces.OnCarouselItemChangeListener;
import com.hacknife.carouselbanner.interfaces.OnCarouselItemClickListener;
import com.xuexiang.xupdate.XUpdate;
import com.xuexiang.xupdate.aria.AriaDownloadServiceProxyImpl;
import com.xuexiang.xupdate.aria.AriaDownloader;
import com.xuexiang.xupdate.easy.EasyUpdate;
import com.xuexiang.xupdate.easy.config.UpdateConfig;
import com.xuexiang.xupdate.entity.UpdateEntity;
import com.xuexiang.xupdate.proxy.impl.DefaultUpdateParser;

import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.jetbrains.annotations.NotNull;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;

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

public class MainActivity extends AppCompatActivity  {

    private AppBarConfiguration appBarConfiguration;
    private ActivityMainBinding binding;
    public ScanGunKeyEventHelper scanGunKeyEventHelper;
    private final Map<String, Bundle> bundleMap = new ArrayMap<>();
    private final Map<String, String> configMap = new ArrayMap<>();

    private static final String TAG = MainActivity.class.getName();

    CarouselBanner banner;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // 初始化图片插件
        Banner.init(new ImageFactory());
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        // 强制关闭输入法
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);


    //        InputMethodManager imm = (InputMethodManager) mActivity.getSystemService(Context.INPUT_METHOD_SERVICE);
    //        imm.hideSoftInputFromWindow(mActivity.getCurrentFocus().getWindowToken(), 0);
        setContentView(binding.getRoot());

        // 自动重启
        ((CrashApplication) getApplication()).addActivity(MainActivity.this);

        // 获取系统配置
        getSystemConfig();

        ICHPublishClient ichPublishClient = ICHPublishClient.getInstance();
        ICHSubscribeClient ichSubscribeClient = ICHSubscribeClient.getInstance();

        ICHTopic.CLIENT_ID = BaseUtils.getClientId();

        // 设置上下文
        ICHSubscribeClient.context = getApplication();

        // 订阅主题
        MessageHandler.openLocker(ichSubscribeClient, ichPublishClient);

        // 注册柜子信息
//\        cabinetInfoReport(ichPublishClient);

        // TODO 更新版本监听
        MessageHandler.autoUpdateVersion(getApplication(), ichSubscribeClient);

        // TODO 监听shell命令脚本
        MessageHandler.executeShell(ichSubscribeClient, ichPublishClient);
//        List<String> list = new ArrayList<>();
        //Banner.init(new ImageFactory());
//        list.add("http://183.3.221.143/group1/M00/00/09/twPdj2MhKNWAK-YRAAFsNNDnV10939.jpg");// cw大药房
        // list.add("http://183.3.221.143/group1/M00/00/09/twPdj2MhKNaAdwpfAAqanlvlafA376.jpg");// 津梁生活
       // list.add("http://183.3.221.143/group1/M00/00/09/twPdj2MYfDaAKEKAAANp3QGoGwQ251.jpg");
        //list.add("http://183.3.221.143/group1/M00/00/09/twPdj2MYfDaAIyukAATXUZaFRD4817.jpg");
        //list.add("http://183.3.221.143/group1/M00/00/0C/twPdj2NaVU6ALV91AAFs0eb1-Q0486.jpg");// 德合
         //list.add("http://183.3.221.143/group1/M00/00/09/twPdj2NMroyABD32AAG_-SrJGo4868.jpg");// 德合 1号柜子
        //list.add("http://183.3.221.143/group1/M00/00/09/twPdj2NMroyADWzDAAHCT9iGPcU955.jpg");// 德合 2号柜子



        banner = findViewById(R.id.banner);

//        banner.setOnCarouselItemChangeListener(new OnCarouselItemChangeListener() {
//            @Override
//            public void onItemChange(int position) {
////                Toast.makeText(MainActivity.this, String.valueOf(position), Toast.LENGTH_LONG).show();
//            }
//        });
//        banner.setOnCarouselItemClickListener(new OnCarouselItemClickListener() {
//            @Override
//            public void onItemClick(int position, String url) {
//                // 点击事件不进行处理
//                // Toast.makeText(MainActivity.this, url, Toast.LENGTH_LONG).show();
//            }
//        });
        //banner.initBanner(list);

    }

    private void getSystemConfig(){

        ICSPClient.getSystemConfig("", BaseUtils.getClientId(), new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Looper.prepare();
                ToastUtils.make(getApplicationContext(), "获取系统配置错误! 网络错误! ");
                Looper.loop();
                Log.e(TAG, "onFailure: 获取系统配置错误! 网络错误! ", e);
                LoggingUtils.sendErrorLog("业务异常: 获取系统配置错误! 网络错误!  ", e);
            }

            @Override
            public void onResponse
                    (@NotNull Call call, @NotNull Response response) throws IOException {
                MainActivity.this.runOnUiThread(() -> {
                    try {
                        String parseResponse = ICSPClient.isSuccessfulAndParseResponse(response);
                        ObjectMapper objectMapper = JacksonUtils.objectmapper;
                        ResponseData<Map<String, String>> readValue = objectMapper.readValue(parseResponse, new TypeReference<ResponseData<Map<String, String>>>() {
                        });
                        if (null != readValue && readValue.getCode().equals(ICSPConstant.OK)) {
                            configMap.putAll(readValue.getData());
                            // 系统配置的session过期时间
                            String time = configMap.get(SystemConfigConstant.deliverer_token_expire_seconds);
                            if (!StringUtils.isNullOrEmpty(time)) {
                                LocalStorage.getInstance().getSession().setTime(Long.parseLong(time));
                            }
                            // 获取轮播图数组字符串
                            String cabImgListStr = configMap.get(SystemConfigConstant.CAB_IMG_LIST);
                            // 转为 List
                            List<String> cabImgList = objectMapper.readValue(cabImgListStr, new TypeReference<List<String>>() {
                            });
                            banner = findViewById(R.id.banner);
                            // 加入 banner
                            if (!cabImgList.isEmpty()) {
                                Log.i(TAG, "onResponse: =====================>获取图片轮播图系统配置成功! ");
                                banner.initBanner(cabImgList);
                            }
                            String url = configMap.get(SystemConfigConstant.cabinet_take_object_qrcode_url);
                            if(url != null){
                                try {
                                    ImageView imageView = findViewById(R.id.fast_take_send);
                                    Glide.with(findViewById(R.id.fast_take_send)).load(url)
                                            .skipMemoryCache(true)//跳过内存缓存
                                            .diskCacheStrategy(DiskCacheStrategy.NONE)//不缓冲disk硬盘中
                                            .into(imageView);
                                } catch (Exception e) {
                                    Log.e(TAG, "onResponse: Glide设置图片异常! ", e);
                                    LoggingUtils.sendErrorLog("业务异常: Glide请求微信公众号图片异常! ", e);
                                }
                            }
                            String cabSerialNo = configMap.get(SystemConfigConstant.cab_serial_no);

                            if(cabSerialNo != null && !"".equals(cabSerialNo)){
                                TextView textView = findViewById(R.id.title_text);
                                textView.setText(cabSerialNo);
                            }
                            String takeQrCodeShow = configMap.get(SystemConfigConstant.take_qr_code_show);
                            String takeButtonShow = configMap.get(SystemConfigConstant.take_button_show);
                            TextView tvDate= (TextView) findViewById(R.id.tv_date);
                            //实时更新时间（1秒更新一次）
                            TimeThread timeThread = new TimeThread(tvDate);//tvDate 是显示时间的控件TextView
                            timeThread.start();//启动线程
                            // 取件二维码是否展示
                            if (TakeQrCodeShowEnum.item_1.getItem().equals(takeQrCodeShow)){
                                findViewById(R.id.fast_take_send).setVisibility(View.GONE);
                                findViewById(R.id.fast_take_send_background).setVisibility(View.GONE);
                            }else {
                                findViewById(R.id.fast_take_send).setVisibility(View.VISIBLE);
                                findViewById(R.id.fast_take_send_background).setVisibility(View.VISIBLE);
                            }
                            // 取件码取件是否展示
                            if (TakeButtonShowEnum.item_1.getItem().equals(takeButtonShow)){
                                findViewById(R.id.take_btn).setVisibility(View.GONE);
                            }else {
                                findViewById(R.id.take_btn).setVisibility(View.VISIBLE);
                            }
                            Log.i(TAG, "onResponse: =====================>获取系统配置成功! ");
                        } else {
                            Log.w(TAG, "onResponse: code==>" + readValue.getCode() + ", msg==>" + readValue.getMsg());
                        }
                    } catch (RuntimeException e) {
                        Log.e(TAG, "onResponse: 获取系统配置错误! 未知错误! ", e);
                    } catch (JsonMappingException e) {
                        Log.e(TAG, "onResponse: 获取系统配置错误! 未知错误! ", e);
                    } catch (JsonProcessingException e) {
                        Log.e(TAG, "onResponse: 获取系统配置错误! 未知错误! ", e);
                    }catch (Exception e){
                        Log.e(TAG, "onResponse: 获取系统配置错误! 未知错误! ", e);
                    }
                });
            }
        });
    }

    public void cabinetInfoReport(ICHPublishClient ichPublishClient){
        String appVersion = BaseUtils.getAppVersion(getApplicationContext());
        String androidVersion = BaseUtils.getVersionName();
        CountDownLatch countDownLatch = new CountDownLatch(10);
        Cabinet cabinet = DeviceControl.queryCabinetInfo(countDownLatch);
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        cabinet.setClientId(BaseUtils.getClientId());
        cabinet.setSoftwareVersion(appVersion);
        cabinet.setAndroidVersion(androidVersion);
        cabinet.setSoftwareType("android");
        cabinet.setImei(BaseUtils.getIMEI(getApplicationContext()));
        cabinet.setMacIpv4(StringUtils.isNullOrEmpty(BaseUtils.getIp()) ? "unknown" : BaseUtils.getIp());
        cabinet.setMacIpv6("unknown");
        cabinet.setNetType("unknown");
        cabinet.setPlatType("S905");
        cabinet.setSim("unknown");
        cabinet.setWifiSSid("unknown");

        ObjectMapper objectMapper = JacksonUtils.objectmapper;

        try {
            String jsonData = objectMapper.writeValueAsString(cabinet);
            Log.i(TAG, "onCreate: jsonData===============>" + jsonData);

            MqttMessage message = new MqttMessage();
            message.setQos(1);
            message.setPayload(jsonData.getBytes());
            ichPublishClient.publish(String.format(ICHTopic.CABINET_INFO_REPORT, BaseUtils.getClientId()), message);
            Log.i(TAG, "cabinetInfoReport: ===============>上报柜子信息成功! ");
        } catch (JsonProcessingException e) {
            Log.e(TAG, "onCreate: 解析成JSON失败!", e);
            LoggingUtils.sendErrorLog("业务异常: 上报柜子信息时解析成JSON失败! ", e);
        }
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (null != scanGunKeyEventHelper) {
            scanGunKeyEventHelper.analysisKeyEvent(event);
        }
        return true;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
//        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
//        int id = item.getItemId();

//        //noinspection SimplifiableIfStatement
//        if (id == R.id.action_settings) {
//            return true;
//        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onSupportNavigateUp() {
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
        return NavigationUI.navigateUp(navController, appBarConfiguration)
                || super.onSupportNavigateUp();
    }

    public Map<String, Bundle> getBundleMap() {
        return bundleMap;
    }

    public Map<String, String> getConfigMap() {
        return configMap;
    }
}