package com.danding.yang800;

import android.Manifest;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.danding.yang800.General.Yang800App;
import com.danding.yang800.Presenter.MainActivityPresenter;
import com.danding.yang800.Update.AppUpdateUtils;
import com.danding.yang800.Update.DownloadService;
import com.danding.yang800.Update.NumberProgressBar;
import com.danding.yang800.Update.OkGoUpdateHttpUtil;
import com.danding.yang800.Update.UpdateAppBean;
import com.danding.yang800.Update.UpdateAppManager;
import com.danding.yang800.Update.UpdateCallback;
import com.danding.yang800.Util.GeneralUtil;
import com.danding.yang800.Util.ToastUtil;
import com.danding.yang800.Util.XPermissionUtils;
import com.qiyukf.unicorn.api.ConsultSource;
import com.qiyukf.unicorn.api.ProductDetail;
import com.qiyukf.unicorn.api.Unicorn;
import com.zhy.autolayout.AutoRelativeLayout;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


public class MainActivity extends BaseActivity {
    @BindView(R.id.main_backIv)
    ImageView mainBackIv;
    @BindView(R.id.main_myHeadIv)
    ImageView mainMyHeadIv;
    @BindView(R.id.main_re)
    RelativeLayout mainRe;
    @BindView(R.id.main_newsIv)
    ImageView mainNewsIv;
    @BindView(R.id.main_shopNameTv)
    TextView mainShopNameTv;
    @BindView(R.id.main_selectGoodsLayout)
    AutoRelativeLayout mainSelectGoodsLayout;
    @BindView(R.id.main_profitLayout)
    AutoRelativeLayout mainProfitLayout;
    @BindView(R.id.main_shopLayout)
    AutoRelativeLayout mainShopLayout;
    @BindView(R.id.main_setLayout)
    AutoRelativeLayout mainSetLayout;
    @BindView(R.id.main_ordermanage)
    RelativeLayout main_ordermanage;
    @BindView(R.id.main_assureLayout)
    RelativeLayout main_assureLayout;
    @BindView(R.id.main_serviceLayout)
    RelativeLayout main_serviceLayout;
    //    @BindView(R.id.main_applyLayout)
//    RelativeLayout main_applyLayout;
    @BindView(R.id.main_marketLayout)
    RelativeLayout main_marketLayout;
    @BindView(R.id.main_noteLayout)
    RelativeLayout main_noteLayout;
    private long mkeyTime;
    SharedPreferences sp;
    MainActivityPresenter presenter;
    @BindView(R.id.main_allProfitTv)
    TextView main_allProfitTv;
    @BindView(R.id.main_todayProfitTv)
    TextView main_todayProfitTv;
    String storeId = "";
    @BindView(R.id.main_accessLogCountTv)
    TextView main_accessLogCountTv;
    @BindView(R.id.main_orderOfTodayTv)
    TextView main_orderOfTodayTv;
    @BindView(R.id.main_balanceTv)
    TextView main_balanceTv;
    private PopupWindow popupWindow;
    boolean update = false;
    private static final int MY_PERMISSIONS_WRITE_CONTACTS = 2;
//    boolean permisson = false;
    private PopupWindow popupshareWindow;
    String headUrl = "";
    boolean mustUpdate = false;
    @BindView(R.id.main_courseLayout)
    LinearLayout main_courseLayout;
    @BindView(R.id.main_mentorLayout)
    LinearLayout main_mentorLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            // 透明状态栏
            getWindow().addFlags(
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
        setContentView(R.layout.activity_main);
        Yang800App.iflogin = true;
        sp = getSharedPreferences("variable", Context.MODE_PRIVATE);
        ButterKnife.bind(this);
        storeId = sp.getString("storeId", "");
        presenter = new MainActivityPresenter(this);
        presenter.gethtmlUrl();
        getWritePermission();
//        presenter.getInfo(storeId);
//        presenter.getShopInfo(storeId);
//        presenter.accessLogCount(storeId);
//        presenter.orderOfToday(storeId);
//        presenter.balance(storeId);
        //  findView();
        updateDiy();
    }

    private void getWritePermission() {
//        XPermissionUtils.requestPermissions(this, 0x08,
//                new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
//                new XPermissionUtils.OnPermissionListener() {
//                    @Override
//                    public void onPermissionGranted() {
//                        permisson = true;
//                    }
//
//                    @Override
//                    public void onPermissionDenied(String[] deniedPermissions, boolean alwaysDenied) {
//                        ToastUtil.show(MainActivity.this, alwaysDenied + "");
//                        if (alwaysDenied) {
//                            permisson = false;
//                            GeneralUtil.showPermissionManagerDialog(MainActivity.this, "存储");
//                        }
//                    }
//                });
        if (Build.VERSION.SDK_INT >= 23) {
            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.READ_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                        MY_PERMISSIONS_WRITE_CONTACTS);
            } else {
//                permisson = true;
            }
        } else {
//            permisson = true;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {

            case MY_PERMISSIONS_WRITE_CONTACTS:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//                    permisson = true;
                } else if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                    builder.setTitle("获取存储权限被禁用")
                            .setMessage("请在 设置-应用管理-" + "洋800" + "-权限管理 (将存储权限打开)")
                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    finishAll();
                                }
                            })
                            .setPositiveButton("去设置", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                    intent.setData(Uri.parse("package:" + MainActivity.this.getPackageName()));
                                    MainActivity.this.startActivityForResult(intent, 10);
                                }
                            }).setCancelable(false).setOnKeyListener(new DialogInterface.OnKeyListener() {
                        @Override
                        public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {

                            if (keyCode == KeyEvent.KEYCODE_SEARCH) {
                                return true;
                            } else {
                                return false; //默认返回 false
                            }
                        }
                    }).show();
                } else {
                    getWritePermission();
                }
        }
//        if (requestCode == MY_PERMISSIONS_WRITE_CONTACTS) {
//            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//                permisson = true;
//            } else {
//
//            }
//
//            return;
//        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 10) {
            getWritePermission();
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        storeId = sp.getString("storeId", "");
    }

    @OnClick({R.id.main_backIv, R.id.main_re, R.id.main_newsIv,
            R.id.main_selectGoodsLayout, R.id.main_profitLayout,
            R.id.main_shopLayout, R.id.main_setLayout, R.id.main_ordermanage, R.id.main_assureLayout
            , R.id.main_serviceLayout, R.id.main_noteLayout, R.id.main_marketLayout, R.id.main_courseLayout
            , R.id.main_mentorLayout})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.main_profitLayout:
                startActivity(MyProfitActivity.class);
                break;
            case R.id.main_shopLayout:
                startActivity(MyShopActivity.class);
                break;
            case R.id.main_setLayout:
                startActivity(SetActivity.class);
                break;
            case R.id.main_newsIv:
                startActivity(NewsActivity.class);
                break;
            case R.id.main_selectGoodsLayout:
                startActivity(SelectGoodsActivity.class);
                break;
            case R.id.main_ordermanage:
                startActivity(OrderManageActivity.class);
                break;
            case R.id.main_assureLayout:
                startActivity(AssureActivity.class);
//                startActivity(HelpActivity.class);
                break;
            case R.id.main_noteLayout:
                Intent intent = new Intent(MainActivity.this, InviteNoteActivity.class);
                intent.putExtra("title", mainShopNameTv.getText().toString() + "邀请你免费开店");
                startActivity(intent);
                break;
            case R.id.main_marketLayout:
                startActivity(MarketActivity.class);
                break;
            case R.id.main_serviceLayout:
                String title = "洋800客服";
                ConsultSource source = new ConsultSource("", "555", "custom information string");
                ProductDetail.Builder pb = new ProductDetail.Builder();
                // pb.setUrl("http://www.163.com");
                source.productDetail = pb.create();
//                YSFUserInfo userInfo = new YSFUserInfo();
//                Unicorn.setUserInfo(userInfo);
                Unicorn.openServiceActivity(this, title, source);
                break;
//            case R.id.main_applyLayout:
//                LogUtil.d(sp.getString("htmlUrl", "") + "邀请");
//                if (GeneralUtil.isWXAppInstalledAndSupported(MainActivity.this)) {
////                    if (StringUtil.getString(goodsUrl)) {
//                    ShareBoardConfig config = new ShareBoardConfig();
//                    config.setTitleVisibility(false);
//                    config.setIndicatorVisibility(false);
//                    web = new UMWeb(sp.getString("htmlUrl", ""));
////                        LogUtil.d(goodsadapter.getItem(position).getStoreSkuSn() + "goodsadapter.getItem(position).getStoreSkuSn()");
//                    web.setTitle(mainShopNameTv.getText().toString()+"邀请你免费开店");
//                    web.setDescription("洋800是保税仓发货系统，提供进口正品货源，源头直采、合法清关、海关监管、正品保证！我邀请你来免费开店");//描述
////                        UMImage umImage = new UMImage(SelectGoodsActivity.this, goodsadapter.getItem(position).getUrl());
////                        web.setThumb(umImage);
//                    new ShareAction(MainActivity.this).setDisplayList(SHARE_MEDIA.WEIXIN)
//                            .setShareboardclickCallback(new ShareBoardlistener() {
//                                                            @Override
//                                                            public void onclick(SnsPlatform snsPlatform, SHARE_MEDIA share_media) {
//                                                                if (GeneralUtil.isWXAppInstalledAndSupported(MainActivity.this)) {
//                                                                    new ShareAction(MainActivity.this).setPlatform(share_media).setCallback(umShareListener)
//                                                                            .withMedia(web)
//                                                                            .share();
//                                                                } else {
//                                                                    ToastUtil.show(MainActivity.this, "未安装微信客户端");
//                                                                }
//                                                            }
//
//                                                        }
//
//                            ).
//                            open(config);
////                    }
//
//                } else {
//                    ToastUtil.show(MainActivity.this, "未安装微信客户端");
//                }
//                showshareWindow();
//                break;
            case R.id.main_courseLayout:
                startActivity(CourseActivity.class);
                break;
            case R.id.main_mentorLayout:
                startActivity(MentorActivity.class);
                break;
        }
    }


    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && update == true) {
            return true;
        }
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - mkeyTime) > 2000) {
                mkeyTime = System.currentTimeMillis();
                Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            } else {
                finishAll();
            }
        }
        return false;
    }

    @Override
    protected void onResume() {
        super.onResume();
        presenter.getInfo(storeId);
        presenter.getShopInfo(storeId);
        presenter.accessLogCount(storeId);
        presenter.orderOfToday(storeId);
        presenter.balance(storeId);
        if (sp.getString("htmlUrl", "").equals("")) {
            presenter.gethtmlUrl();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Unicorn.toggleNotification(true);
        Unicorn.logout();
    }

    public void updateProfit(String storeTotalIncome, String storeTodayIncome) {
        main_allProfitTv.setText(storeTotalIncome);
        main_todayProfitTv.setText(storeTodayIncome);
    }

    public void updateShopHead(String name, String headImg) {
        mainShopNameTv.setText(name);
        headUrl = headImg;
        if (headImg.equals("")) {
            mainMyHeadIv.setImageResource(R.drawable.main_myhead);
        } else {
            Glide.with(this).load(headImg).error(R.drawable.huisebeijing).diskCacheStrategy(DiskCacheStrategy.ALL).into(mainMyHeadIv);
        }
    }

    public void updateaccessLogCount(String data) {
        main_accessLogCountTv.setText(data);
    }

    public void updateorderOfToday(String data) {
        main_orderOfTodayTv.setText(data);
    }

    public void updateBalance(String balance) {
        main_balanceTv.setText(balance);
    }


    UpdateAppBean updateApp;

    public void updateDiy() {
        String path = Environment.getExternalStorageDirectory().getAbsolutePath();
        AppUpdateUtils.deleteFolderFile(path + File.separator + "app");
        new UpdateAppManager
                .Builder()
                .setActivity(this)
                .setHttpManager(new OkGoUpdateHttpUtil())
                .setUpdateUrl("appApk.getUpdateInfo")
                .setPost(false)
                .setTargetPath(path)
                .build()
                .checkNewApp(new UpdateCallback() {
                    @Override
                    protected UpdateAppBean parseJson(UpdateAppBean updateAppBean) {

                        return updateAppBean;
                    }

                    @Override
                    public void hasNewApp(UpdateAppBean update, UpdateAppManager updateAppManager, String update_log, String update_must) {
                        updateApp = update;
                        showWindow(update_log, update_must);
                    }

                    /**
                     * 网络请求之前
                     */
                    @Override
                    public void onBefore() {
                    }

                    /**
                     * 网路请求之后
                     */
                    @Override
                    public void onAfter() {
                    }

                    /**
                     * 没有新版本
                     */
                    @Override
                    public void noNewApp() {
                    }
                });
    }

    NumberProgressBar progressBar;
    Button btn_ok;

    public void showWindow(String update_log, final String update_must) {
        if (update_must.equals("1")) {
            update = true;
        }
        View contentView = LayoutInflater.from(this).inflate(
                R.layout.lib_update_app_dialog, null);
        popupWindow = new PopupWindow(contentView, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT, true);
        btn_ok = (Button) contentView.findViewById(R.id.btn_ok);
        progressBar = (NumberProgressBar) contentView.findViewById(R.id.progressBar);
        TextView tv_update_info = (TextView) contentView.findViewById(R.id.tv_update_info);
        tv_update_info.setText(update_log);
        btn_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getWritePermission();
//                if (permisson) {
                    if (update_must.equals("0")) {
//                        updateAppManager.download();
                        popupWindow.dismiss();
                        mustUpdate = false;
                        DownloadService.bindService(MainActivity.this, conn);
                    } else {
                        mustUpdate = true;
                        btn_ok.setVisibility(View.GONE);
                        progressBar.setVisibility(View.VISIBLE);
                        DownloadService.bindService(MainActivity.this, conn);
                    }
//                } else {
//                    Toast.makeText(MainActivity.this, "没有读取存储权限", Toast.LENGTH_SHORT).show();
//                }

            }

        });
        ImageView iv_close = (ImageView) contentView.findViewById(R.id.iv_close);
        iv_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (update_must.equals("0")) {
                    popupWindow.dismiss();
                } else {
                    finish();
                }

            }
        });
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.showAtLocation(contentView, Gravity.BOTTOM, 0, 0);
    }

    private ServiceConnection conn = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            startDownloadApp((DownloadService.DownloadBinder) service);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    };

    private void startDownloadApp(DownloadService.DownloadBinder binder) {
        // 开始下载，监听下载进度，可以用对话框显示
        if (updateApp != null) {

            binder.start(updateApp, new DownloadService.DownloadCallback() {
                @Override
                public void onStart() {
                    progressBar.setVisibility(View.VISIBLE);
                }

                @Override
                public void onProgress(float progress, long totalSize) {
                    if (mustUpdate) {
                        progressBar.setProgress(Math.round(progress * 100));
                        progressBar.setMax(100);
                    }
                }

                @Override
                public void setMax(long total) {

                }

                @Override
                public boolean onFinish(File file) {
                    if (mustUpdate)
                        popupWindow.dismiss();
                    return true;
                }

                @Override
                public void onError(String msg) {
                    if (mustUpdate)
                        popupWindow.dismiss();
                }
            });
        }
    }
}
