package com.ygtx.emcs.activity;

import static com.ygtx.emcs.util.Constant.CACHE_BIND_CONFIG;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.provider.Settings;
import android.view.View;
import android.widget.EditText;

import com.ygtx.emcs.R;
import com.ygtx.emcs.comm.BaseActivity;
import com.ygtx.emcs.comm.CacheService;
import com.ygtx.emcs.databinding.YgtxAppInfoBinding;
import com.ygtx.emcs.update.UpdateManager;
import com.ygtx.emcs.update.UpdateXmlService;
import com.ygtx.emcs.util.Constant;
import com.ygtx.emcs.util.ProjectUtils;
import com.ygtx.emcs.util.StringUtils;
import com.ygtx.emcs.util.ToastUtils;
import com.ygtx.emcs.util.VersionUtils;

import org.apache.log4j.Logger;
import org.xutils.x;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.HashMap;


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

    private Context context;
    private YgtxAppInfoBinding binding;
    private HashMap<String,String> mHashMap;
    private EditText inputServer;
    private EditText boxServer;
    private EditText inStockServer;
    private EditText outStockServer;
    public AlertDialog dialog;
    public AlertDialog dialogBox;
    public AlertDialog dialogInStock;
    public AlertDialog dialogOutStock;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = YgtxAppInfoBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        x.view().inject(this);
        context = this;
        initCommonTop2();
        init();
    }

    @SuppressLint("ClickableViewAccessibility")
    public void init(){
        inputServer = new EditText(this);
        boxServer = new EditText(this);
        inStockServer = new EditText(this);
        outStockServer = new EditText(this);
        if(Constant.user!=null) {
            binding.tvLoginName.setText(Constant.user.getUserName());
        }else{
            binding.tvLoginName.setText("未登录");
        }
        binding.tvWorkStation.setText("操作员");
        binding.tvVersion.setText(VersionUtils.getVerName(context));
        binding.tvDeviceSeq.setText(getMac());
        binding.versionUpdate.setOnClickListener(view->{
            updateApp();
        });
        binding.exit.setOnClickListener(view->{
            myLogout();
        });
//        binding.tvIp.setVisibility(View.GONE);
        binding.tvIp.setText(Constant.server_ip);
        updateIP();
        updateBox();
        updateInStock();
        updateOutStock();
    }

    private void updateApp(){
        try {
            boolean haveInstallPermission = context.getPackageManager().canRequestPackageInstalls();
            Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
            if (!haveInstallPermission) {
                context.startActivity(intent);
            }
        }catch (NoSuchMethodError e){
            e.printStackTrace();
        }
        if(isUpdate()) {
            ProjectUtils.init(this);
            UpdateManager updateManager = new UpdateManager(context, mHashMap);
            updateManager.showDownloadDialog();
        }else {
            ToastUtils.showToast(this, "已经是最新版本了");
        }
    }

    public boolean isUpdate(){
        try {
            int versionCode = VersionUtils.getVerCode(this);
            UpdateXmlService service = new UpdateXmlService();
            String path = ProjectUtils.getProjectURL() + "/version.xml";
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(5 * 1000);
            conn.setConnectTimeout(10000);
            conn.setRequestMethod("GET");
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                    .permitAll().build();
            StrictMode.setThreadPolicy(policy);
            InputStream inStream = conn.getInputStream();
            mHashMap = service.parseXml(inStream);
            String current_version = mHashMap.get("version");
            if (StringUtils.isEmpty(current_version)) {
                return false;
            }
            if (null != mHashMap) {
                int serviceCode = Integer.parseInt(current_version);
                return serviceCode > versionCode;
            }
        } catch (SocketTimeoutException ex){
            mylog.error("连接超过:", ex);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    private void updateIP(){
        binding.tvIp.setOnLongClickListener(view->{
            AlertDialog.Builder builder = new AlertDialog.Builder(context)
                    .setTitle("设置IP")
                    .setIcon(R.mipmap.logo)
                    .setView(inputServer)
                    .setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    })
                    .setPositiveButton(getString(R.string.sure), null);
            if(dialog==null){
                dialog = builder.show();
            }else{
                dialog.show();
            }
            inputServer.setText(binding.tvIp.getText().toString());
            dialog.getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
                public void onClick(View v){
                    Constant.server_ip = inputServer.getText().toString();
                    Constant.HTTP_URL = "http://"+Constant.server_ip;
                    binding.tvIp.setText(Constant.server_ip);
                    ToastUtils.showToast(context, "设置成功");
                    dialog.dismiss();
                }
            });
            return false;
        });
    }

    private void updateBox(){
        String box_flag = CacheService.getInstance(context).getCache(CACHE_BIND_CONFIG, "box_flag");
        if(!StringUtils.isEmpty(box_flag)){
            binding.tvBoxFlag.setText(box_flag);
        }
        binding.btnBoxUpdate.setOnClickListener(view->{
            boxServer.setText(binding.tvBoxFlag.getText().toString());
            AlertDialog.Builder builder = new AlertDialog.Builder(context)
                    .setTitle("设置料框编码")
                    .setIcon(R.mipmap.logo)
                    .setView(boxServer)
                    .setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    })
                    .setPositiveButton(getString(R.string.sure), null);
            if(dialogBox==null){
                dialogBox = builder.show();
            }else{
                dialogBox.show();
            }
            dialogBox.getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
                public void onClick(View v){
                    String boxFlag = boxServer.getText().toString();
                    binding.tvBoxFlag.setText(boxFlag);
                    CacheService.getInstance(context).saveCache(CACHE_BIND_CONFIG, "box_flag", boxFlag);
                    ToastUtils.showToast(context, "设置成功");
                    dialogBox.dismiss();
                }
            });
        });
    }

    private void updateInStock(){
        String in_stock_flag = CacheService.getInstance(context).getCache(CACHE_BIND_CONFIG, "in_stock_flag");
        if(!StringUtils.isEmpty(in_stock_flag)){
            binding.tvInstockFlag.setText(in_stock_flag);
        }
        binding.btnInstockUpdate.setOnClickListener(view->{
            inStockServer.setText(binding.tvInstockFlag.getText().toString());
            AlertDialog.Builder builder = new AlertDialog.Builder(context)
                    .setTitle("设置入库单编码")
                    .setIcon(R.mipmap.logo)
                    .setView(inStockServer)
                    .setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    })
                    .setPositiveButton(getString(R.string.sure), null);
            if(dialogInStock==null){
                dialogInStock = builder.show();
            }else{
                dialogInStock.show();
            }
            dialogInStock.getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
                public void onClick(View v){
                    String inStockFlag = inStockServer.getText().toString();
                    binding.tvInstockFlag.setText(inStockFlag);
                    CacheService.getInstance(context).saveCache(CACHE_BIND_CONFIG, "in_stock_flag", inStockFlag);
                    ToastUtils.showToast(context, "设置成功");
                    dialogInStock.dismiss();
                }
            });
        });
    }

    private void updateOutStock(){
        String out_stock_flag = CacheService.getInstance(context).getCache(CACHE_BIND_CONFIG, "out_stock_flag");
        if(!StringUtils.isEmpty(out_stock_flag)){
            binding.tvOutstockFlag.setText(out_stock_flag);
        }
        binding.btnOutstockUpdate.setOnClickListener(view->{
            outStockServer.setText(binding.tvOutstockFlag.getText().toString());
            AlertDialog.Builder builder = new AlertDialog.Builder(context)
                    .setTitle("设置出库单编码")
                    .setIcon(R.mipmap.logo)
                    .setView(outStockServer)
                    .setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    })
                    .setPositiveButton(getString(R.string.sure), null);
            if(dialogOutStock==null){
                dialogOutStock = builder.show();
            }else{
                dialogOutStock.show();
            }
            dialogOutStock.getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
                public void onClick(View v){
                    String outStockFlag = outStockServer.getText().toString();
                    binding.tvOutstockFlag.setText(outStockFlag);
                    CacheService.getInstance(context).saveCache(CACHE_BIND_CONFIG, "out_stock_flag", outStockFlag);
                    ToastUtils.showToast(context, "设置成功");
                    dialogOutStock.dismiss();
                }
            });
        });
    }

    @Override
    public void receiverTask(String barcode) {

    }

    @Override
    protected String getCommonTopTitle() {
        return "设备信息";
    }

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

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
