package com.mjsheng.myappstore.dialog;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okserver.download.DownloadManager;
import com.mjsheng.myappstore.R;
import com.mjsheng.myappstore.base.BaseFragmentActivity;
import com.mjsheng.myappstore.bean.AppContentInfo;
import com.mjsheng.myappstore.bean.AppData;
import com.mjsheng.myappstore.bean.AppDateInfo;
import com.mjsheng.myappstore.bean.AppDownloadInfo;
import com.mjsheng.myappstore.bean.JsonCallback;
import com.mjsheng.myappstore.bean.LzyResponse;
import com.mjsheng.myappstore.comm.CommonDatas;
import com.mjsheng.myappstore.download.StorageUtils;
import com.mjsheng.myappstore.fragment.AppRecommendFragment;
import com.mjsheng.myappstore.fragment.CommentsPageFragment;
import com.mjsheng.myappstore.fragment.IntroductionPageFragment;
import com.mjsheng.myappstore.image.ImageLoader;
import com.mjsheng.myappstore.utils.ApkUtils;
import com.mjsheng.myappstore.utils.Configure;
import com.mjsheng.myappstore.utils.MySQLData;
import com.mjsheng.myappstore.utils.Utils;
import com.mjsheng.myappstore.view.StarRatingBar;

import java.io.File;
import java.util.List;

import okhttp3.Call;
import okhttp3.Response;

/**
 * Created by Administrator on 2016/11/29.
 */

public class AppDetailDialog extends BaseFragmentActivity {

    private String title, appBaoming;
    private String userVip;
    private TextView detailTitleIv, appName, priceTv, appSize, updateTV;
    public ImageView downloadIv;
    public TextView downloadTv;
    private LinearLayout downloadLl;
    private ImageView appIcon;
    private StarRatingBar ratingBar;
    private RadioGroup radioGroup;
    private RadioButton commentBtn;
    private AppContentInfo info = new AppContentInfo();
    private AppDownloadInfo appDownloadInfo;
    private DownloadReceiver downloadReceiver;
    private FragmentManager mFragmentManager;
    private Fragment[] mFragments;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_appstore_appdetail);
        title = getIntent().getStringExtra("title");
        appBaoming = getIntent().getStringExtra("appBaoming");
        userVip = MySQLData.GetData(this, CommonDatas.SP_USER_VIP);
        init();
    }


    private void init() {

        detailTitleIv = (TextView) findViewById(R.id.tv_detail_title);
        detailTitleIv.setText(title);
        downloadLl = (LinearLayout) findViewById(R.id.llDownload);
        downloadIv = (ImageView) findViewById(R.id.ivDownload);
        downloadTv = (TextView) findViewById(R.id.tvDownload);
        appIcon = (ImageView) findViewById(R.id.detail_app_icon);
        appName = (TextView) findViewById(R.id.app_name);
        priceTv = (TextView) findViewById(R.id.price_tv);
        appSize = (TextView) findViewById(R.id.app_size);
        updateTV = (TextView) findViewById(R.id.app_update_time);
        ratingBar = (StarRatingBar) findViewById(R.id.ratingbar);
        ratingBar.setmClickable(false);
        radioGroup = (RadioGroup) findViewById(R.id.detail_radio_group);
        radioGroup.setOnCheckedChangeListener(new RadioGroupCheckedChangeListener());
        commentBtn = (RadioButton) findViewById(R.id.comments_btn);

        mFragments = new Fragment[3];
        mFragmentManager = getSupportFragmentManager();

        downloadReceiver = new DownloadReceiver();
        /* 注册广播 */
        IntentFilter mScreenOnFilter = new IntentFilter(Utils.DOWNLOAD_SERVICE_ACTION);
        registerReceiver(downloadReceiver, mScreenOnFilter);

        String s = java.net.URLEncoder.encode(appBaoming);
        OkGo.post(Configure.HTTP_TAG_APPDETAILS)
                .tag(this)
                .params("key", Configure.HTTP_KEY)
                .params("sn", Utils.getSerial())
                .params("package", s)
                .cacheKey(Configure.HTTP_TAG_APPDETAILS + s)
                .cacheMode(CacheMode.REQUEST_FAILED_READ_CACHE)
                .execute(new JsonCallback<LzyResponse<List<AppContentInfo>>>() {
                    @Override
                    public void onSuccess(LzyResponse<List<AppContentInfo>> listLzyResponse, Call call, Response response) {
                        info = listLzyResponse.data.get(0);
                        initData();
                    }

                    @Override
                    public void onCacheSuccess(LzyResponse<List<AppContentInfo>> listLzyResponse, Call call) {
                        onSuccess(listLzyResponse, call, null);
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        Log.e("mjsheng", "错误===============" + e.getMessage());
                    }
                });
    }


    private void sendIntent(String state, String URL) {
        if (state.equals("start")) {
            AppDateInfo dateInfo = new AppDateInfo();
            dateInfo.setApp_file(info.getApp_file());
            dateInfo.setApp_baoming(info.getApp_baoming());
            dateInfo.setApp_size(info.getApp_size());
            dateInfo.setApp_name(info.getApp_name());
            dateInfo.setApp_img(info.getApp_img());
            dateInfo.setApp_banben(info.getApp_banben());
            Intent msgIntent = new Intent(Utils.DOWNLOAD_START_ACTION);
            msgIntent.putExtra("URL", URL);
            msgIntent.putExtra("AppDateInfo", dateInfo);
            sendBroadcast(msgIntent);
            AppData.AddDownloadApp(this, Utils.system[Integer.parseInt("1") - 1], Utils.sonSystem[Integer.parseInt("11") - 1], info.getApp_baoming());

        } else if (state.equals("stop")) {
            Intent msgIntent = new Intent(Utils.DOWNLOAD_STOP_ACTION);
            msgIntent.putExtra("URL", URL);
            sendBroadcast(msgIntent);
        } else if (state.equals("initialize")) {
            Intent msgIntent = new Intent(Utils.DOWNLOAD_INITIALIZE_ACTION);
            msgIntent.putExtra("URL", URL);
            sendBroadcast(msgIntent);
        }
    }

    private void initData() {
        initDownloadButton();
        ImageLoader.getDefault().loadUrl(this, info.getApp_img(), appIcon);
        appName.setText(info.getApp_name());
        //        if (info.getApp_tag4().equals("4")) {
        //            priceTv.setText("含收费项目");
        //        }
        //by mjsheng 评分星星

        try {
            float f = Float.valueOf(info.getApp_pfen().trim()).floatValue();
            ratingBar.setStar(f);
        } catch (NumberFormatException nfe) {
            Log.e("NumberFormatException: ", nfe.getMessage());
        }
        long s = (long) Double.parseDouble(info.getApp_size());
        String totalLength = Utils.fmtSpace(s);
        //        Log.e("mjsheng", "long是多少：：：：：" + s + "----------totalLength---" + totalLength);
        if (!totalLength.isEmpty()) {
            appSize.setText(totalLength);
        }
        updateTV.setText(this.getResources().getString(R.string.app_update_time_text_format, info.getApp_down()));

        ((RadioButton) findViewById(R.id.introduction_btn)).setChecked(true);

        int commentCount = 0;
        commentBtn.setText(this.getResources().getString(
                R.string.app_detail_comments_text_format,
                commentCount > 0 ? "(" + commentCount + ")" : ""));

        switchContent(0);
    }

    private void initDownloadButton() {
        // 初始化下载状态
        sendIntent("initialize", info.getApp_file());
        downloadLl.setTag(info.getApp_file());
        isUpdate(info.getApp_baoming(), info.getApp_banben(), downloadLl, downloadIv, downloadTv);
        downloadLl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (userVip.equals("1")) {
                    if (v.getTag(R.string.download_btn_had) != null) {
                        ApkUtils.openApp(AppDetailDialog.this, v);
                        return;
                    }
                    if (appDownloadInfo != null) {
                        switch (appDownloadInfo.getState()) {
                            case DownloadManager.PAUSE:
                            case DownloadManager.NONE:
                            case DownloadManager.ERROR:
                                AppDateInfo dateInfo = new AppDateInfo();
                                dateInfo.setApp_file(info.getApp_file());
                                dateInfo.setApp_baoming(info.getApp_baoming());
                                dateInfo.setApp_size(info.getApp_size());
                                dateInfo.setApp_name(info.getApp_name());
                                dateInfo.setApp_img(info.getApp_img());
                                sendIntent("start", info.getApp_file());
                                break;
                            case DownloadManager.DOWNLOADING:
                            case DownloadManager.WAITING:
                                sendIntent("stop", info.getApp_file());
                                break;
                            case DownloadManager.FINISH:
                                //                                ApkUtils.install(AppDetailDialog.this, new File(appDownloadInfo.getTargetPath()));
                                ApkUtils.installRx(AppDetailDialog.this, appDownloadInfo.getPackageName(), appDownloadInfo.getTargetPath());
                                break;
                        }
                    } else {
//                        OkGo.post(Configure.HTTP_TAG_DOWNLOAD_URL)
//                                .params("key", Configure.HTTP_KEY)
//                                .params("sn", Utils.getSerial())
//                                .params("package", info.getApp_baoming())
//                                .tag(this)
//                                .cacheKey(Configure.HTTP_TAG_DOWNLOAD_URL + java.net.URLEncoder.encode(info.getApp_baoming()))
//                                .cacheMode(CacheMode.REQUEST_FAILED_READ_CACHE)
//                                .execute(new JsonCallback<LzyResponse<List<AppDateInfo>>>() {
//                                    @Override
//                                    public void onSuccess(LzyResponse<List<AppDateInfo>> listLzyResponse, Call call, Response response) {
                                        sendIntent("start", info.getApp_file());
//                                    }
//                                });
                    }
                } else {
                    Log.e("mjsheng", "AppDetailDialog未激活");
                }
            }
        });
    }

    private void isUpdate(String packageName, String banben, LinearLayout downloadLl, ImageView downloadIv, TextView downloadTv) {
        PackageInfo packageInfo = null;
        try {
            packageInfo = getPackageManager().getPackageInfo(packageName, 0);
        } catch (PackageManager.NameNotFoundException e) {
            packageInfo = null;
        }
        if (packageInfo != null) {
            try {
                if (Utils.isUpdate(packageInfo.versionName, banben) == true) {
                    downloadLl.setTag(R.string.download_btn_update, packageInfo.applicationInfo.name);
                    downloadTv.setText(getString(R.string.download_btn_update));
                    downloadIv.setBackgroundResource(R.drawable.download_update);
                    downloadLl.setBackgroundResource(R.drawable.update_btn_selector);
                } else {
                    downloadLl.setTag(R.string.download_btn_had, packageInfo.packageName);
                    downloadTv.setText(getString(R.string.open_text));
                    downloadIv.setBackgroundResource(R.drawable.download_open);
            downloadLl.setBackgroundResource(R.drawable.update_btn_selector);
                }
            } catch (Exception e) {
            }
        } else {
            downloadTv.setText(getString(R.string.download_start_text));
            downloadIv.setBackgroundResource(R.drawable.download_start);
                    downloadLl.setBackgroundResource(R.drawable.download_btn_selector);
        }
    }

    //更新当前进度
    private void updateProgress(AppDownloadInfo downloadInfo) {
        if (downloadInfo == null)
            return;
        if (info == null)
            return;
        if (info.getApp_file() == null)
            return;
        if (!info.getApp_file().equals(downloadInfo.getUrl()))
            return;
        appDownloadInfo = downloadInfo;
        if (downloadInfo.getState() == DownloadManager.NONE) {
            downloadTv.setText(R.string.download_continue_text);
            downloadLl.setBackgroundResource(R.drawable.update_btn_selector);
            downloadIv.setBackgroundResource(R.drawable.download_continue);
        } else if (downloadInfo.getState() == DownloadManager.ERROR) {
            downloadTv.setText(getString(R.string.download_start_text));
            downloadLl.setBackgroundResource(R.drawable.download_btn_selector);
            downloadIv.setBackgroundResource(R.drawable.download_start);
        } else if (downloadInfo.getState() == DownloadManager.PAUSE) {
            downloadTv.setText(getString(R.string.download_continue_text));
            downloadLl.setBackgroundResource(R.drawable.update_btn_selector);
            downloadIv.setBackgroundResource(R.drawable.download_continue);
        } else if (downloadInfo.getState() == DownloadManager.WAITING) {
            downloadTv.setText(getString(R.string.download_wait_text));
            downloadLl.setBackgroundResource(R.drawable.download_btn_selector);
            downloadIv.setBackgroundResource(R.drawable.download_continue);
        } else if (downloadInfo.getState() == DownloadManager.FINISH) {
            if (ApkUtils.isAvailable(this, new File(downloadInfo.getTargetPath()))) {
                downloadTv.setText(getString(R.string.open_text));
                downloadIv.setBackgroundResource(R.drawable.download_open);
                downloadLl.setBackgroundResource(R.drawable.update_btn_selector);
            } else {
                downloadTv.setText(getString(R.string.download_install_text));
                downloadLl.setBackgroundResource(R.drawable.update_btn_selector);
                downloadIv.setBackgroundResource(R.drawable.download_install);
            }
        } else if (downloadInfo.getState() == DownloadManager.DOWNLOADING) {
            downloadTv.setText((long) ((downloadInfo.getProgress() * 10000) * 1.0f / 100) + "%");
            downloadLl.setBackgroundResource(R.drawable.download_btn_selector);
            downloadIv.setBackgroundResource(R.drawable.download_start);
        } else if (downloadInfo.getState() == 10) {
            downloadInfo = null;
            isUpdate(downloadInfo.getPackageName(), downloadInfo.getVersion(), downloadLl, downloadIv, downloadTv);
        }
    }


    // 切换显示内容
    public void switchContent(int index) {
        FragmentTransaction transaction = mFragmentManager.beginTransaction();
        hideFragments(transaction);
        try {
            switch (index) {
                case 0:
                    if (mFragments[0] == null) {
                        mFragments[0] = new IntroductionPageFragment();
                        IntroductionPageFragment fragments = (IntroductionPageFragment) mFragments[0];
                        fragments.setIntroductionInfo(info);
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("info", info);
                        fragments.setArguments(bundle);
                        transaction.add(R.id.fl_fragmentlayout,
                                mFragments[0]);
                    } else {
                        transaction.show(mFragments[0]);
                    }
                    break;
                case 1:
                    if (mFragments[1] == null) {
                        mFragments[1] = new CommentsPageFragment();
                        CommentsPageFragment fragments = (CommentsPageFragment) mFragments[1];
                        fragments.setParentView(getCurrentFocus());
                        fragments.initDatas(info.getApp_baoming());
                        transaction.add(R.id.fl_fragmentlayout,
                                mFragments[1]);
                    } else {
                        transaction.show(mFragments[1]);
                    }
                    break;
                case 2:
                    if (mFragments[2] == null) {
                        mFragments[2] = new AppRecommendFragment();
                        AppRecommendFragment fragments = (AppRecommendFragment) mFragments[2];
                        fragments.setParentView(this);
                        fragments.initDatas(info.getApp_id());
                        transaction.add(R.id.fl_fragmentlayout,
                                mFragments[2]);
                    } else {
                        transaction.show(mFragments[2]);
                    }
                    break;
            }
            transaction.commit();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void hideFragments(FragmentTransaction transaction) {
        if (mFragments != null) {
            for (int i = 0; i < mFragments.length; i++) {
                if (mFragments[i] != null) {
                    transaction.hide(mFragments[i]);
                }
            }
        }
    }

    private class RadioGroupCheckedChangeListener implements
            RadioGroup.OnCheckedChangeListener {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            if (checkedId == R.id.introduction_btn) {
                RadioButton introductionBtn = (RadioButton) group.findViewById(R.id.introduction_btn);
                RadioButton commentBtn = (RadioButton) group.findViewById(R.id.comments_btn);
                RadioButton recommendBtn = (RadioButton) group.findViewById(R.id.recommend_btn);

                introductionBtn.setSelected(true);
                commentBtn.setSelected(false);
                recommendBtn.setSelected(false);
                //                introductionBtn.setBackgroundResource(R.drawable.rb_selected);
                introductionBtn.setTextColor(getResources().getColor(R.color.main_green_color));

                commentBtn.setBackgroundColor(Color.TRANSPARENT);
                commentBtn.setTextColor(getResources().getColor(R.color.black));
                //                recommendBtn.setBackgroundColor(Color.TRANSPARENT);
                recommendBtn.setTextColor(getResources().getColor(R.color.black));

                switchContent(0);
            } else if (checkedId == R.id.comments_btn) {
                RadioButton introductionBtn = (RadioButton) group.findViewById(R.id.introduction_btn);
                RadioButton commentBtn = (RadioButton) group.findViewById(R.id.comments_btn);
                RadioButton recommendBtn = (RadioButton) group.findViewById(R.id.recommend_btn);

                //                commentBtn.setBackgroundResource(R.drawable.rb_selected);
                commentBtn.setTextColor(getResources().getColor(R.color.main_green_color));

                //                recommendBtn.setBackgroundColor(Color.TRANSPARENT);
                recommendBtn.setTextColor(getResources().getColor(R.color.black));
                //                introductionBtn.setBackgroundColor(Color.TRANSPARENT);
                introductionBtn.setTextColor(getResources().getColor(R.color.black));

                introductionBtn.setSelected(false);
                commentBtn.setSelected(true);
                recommendBtn.setSelected(false);
                switchContent(1);
            } else if (checkedId == R.id.recommend_btn) {
                RadioButton introductionBtn = (RadioButton) group.findViewById(R.id.introduction_btn);
                RadioButton commentBtn = (RadioButton) group.findViewById(R.id.comments_btn);
                RadioButton recommendBtn = (RadioButton) group.findViewById(R.id.recommend_btn);

                //                recommendBtn.setBackgroundResource(R.drawable.rb_selected);
                recommendBtn.setTextColor(getResources().getColor(R.color.appstore_btn_color));

                //                introductionBtn.setBackgroundColor(Color.TRANSPARENT);
                introductionBtn.setTextColor(getResources().getColor(R.color.black));
                //                commentBtn.setBackgroundColor(Color.TRANSPARENT);
                commentBtn.setTextColor(getResources().getColor(R.color.black));
                introductionBtn.setSelected(false);
                commentBtn.setSelected(false);
                recommendBtn.setSelected(true);
                switchContent(2);
            }
        }
    }

    public class DownloadReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (Utils.DOWNLOAD_SERVICE_ACTION.equals(intent.getAction())) {
                AppDownloadInfo downloadInfo = (AppDownloadInfo) intent.getSerializableExtra("DownloadInfo");
                updateProgress(downloadInfo); //更新进度
            }
        }

    }


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