package com.sheep.gamegroup.view.activity;

import android.app.Activity;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.sheep.gamegroup.absBase.AbsChooseImageActivity;
import com.sheep.gamegroup.model.entity.BaseMessage;
import com.sheep.gamegroup.model.entity.TaskEty;
import com.sheep.gamegroup.model.entity.Release_task;
import com.sheep.gamegroup.model.util.EntityUtils;
import com.sheep.gamegroup.model.util.SheepSubscriber;
import com.sheep.gamegroup.util.DeviceUtil;
import com.sheep.gamegroup.util.Jump2View;
import com.sheep.gamegroup.util.MyListview;
import com.sheep.gamegroup.util.TimeUtil;
import com.sheep.gamegroup.util.UMConfigUtils;
import com.sheep.jiuyan.samllsheep.R;
import com.sheep.jiuyan.samllsheep.SheepApp;
import com.sheep.jiuyan.samllsheep.utils.G;
import com.sheep.jiuyan.samllsheep.utils.PackageUtil;
import com.sheep.jiuyan.samllsheep.utils.TitleBarUtils;
import com.tencent.smtt.export.external.interfaces.WebResourceRequest;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import java.util.Locale;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import io.reactivex.schedulers.Schedulers;

import static com.sheep.gamegroup.model.entity.TaskEty.TASK_TYPE_CREDIT_CARD;

/**
 * 信用卡任务详情页面
 * Created by realicing on 2018/4/26.
 */

public class TaskDetailCreditCardAct extends AbsChooseImageActivity {

    @BindView(R.id.icon_iv)
    ImageView iconIv;
    @BindView(R.id.name_tv)
    TextView nameTv;
    @BindView(R.id.date_tv)
    TextView dateTv;
    @BindView(R.id.price_tv)
    TextView priceTv;
    @BindView(R.id.detail_task_tv)
    TextView detailTaskTv;
    @BindView(R.id.web_text)
    WebView webText;
    @BindView(R.id.ll_infos)
    LinearLayout llInfos;
    @BindView(R.id.btn_task_item)
    TextView btnTaskItem;
    @BindView(R.id.btn_up_imag)
    TextView btnUpImag;
    @BindView(R.id.bottom_btn_layout)
    LinearLayout bottom_btn_layout;
    @BindView(R.id.detail_item_layout_2)
    LinearLayout detail_item_layout_2;
    @BindView(R.id.detail_item_layout_3)
    LinearLayout detail_item_layout_3;
    @BindView(R.id.detail_shrae_friend_layout)
    LinearLayout detail_shrae_friend_layout;
    @BindView(R.id.detail_task_listview)
    MyListview detail_task_listview;
    @BindView(R.id.item_layout)
    View item_layout;
    private Activity activity;

    private TaskEty taskEty;
    private Release_task taskReleaseEty;

    @Override
    protected int getLayoutId() {
        return R.layout.task_detail_layout;
    }

    @Override
    public void initView() {
        activity = this;
        id = getIntent().getIntExtra("id", 0);
        TitleBarUtils.getInstance()
                .setTitle(activity, "任务详情")
                .setTitleFinish(activity);
        btnUpImag.setVisibility(View.GONE);
    }

    private int id;

    @Override
    public void initListener() {

    }

    @Override
    public void initData() {
        if (taskEty == null) {
            netTaskSchedule();
            return;
        }
        item_layout.setBackgroundResource(R.drawable.sp_bg_white_solid_top);
        webText.setWebChromeClient(new WebChromeClient() {

        });
        detail_item_layout_2.setVisibility(View.VISIBLE);
        detail_item_layout_3.setVisibility(View.VISIBLE);
        detail_shrae_friend_layout.setVisibility(View.GONE);
        webText.getSettings().setJavaScriptEnabled(true);
// 1、LayoutAlgorithm.NARROW_COLUMNS ： 适应内容大小
// 2、LayoutAlgorithm.SINGLE_COLUMN:适应屏幕，内容将自动缩放
//        webText.getSettings().setUseWideViewPort(true);
//        webText.getSettings().setLoadWithOverviewMode(true);
//        webText.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
//        webText.setInitialScale(80);
        webText.setWebViewClient(new WebViewClient() {
            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                view.loadDataWithBaseURL(null, request.getUrl().toString(), "text/html", "utf-8", null);
                return true;
            }
        });
        //封装头文件
        String sHead = "<html><head><meta name=\"viewport\" content=\"width=device-width, " +
                "initial-scale=1.0, minimum-scale=0.5, maximum-scale=2.0, user-scalable=yes\" />" +
                "<style>img{max-width:100% !important;height:auto !important;}</style>"
                + "<style>body{max-width:100% !important;}</style>" + "</head><body>";
        webText.loadDataWithBaseURL(null, sHead + taskEty.getDesc() + "</body></html>", "text/html", "utf-8", null);
        nameTv.setText(taskReleaseEty.getName());
        priceTv.setText(String.format(Locale.CHINA, "+%s元", taskReleaseEty.getBonusText()));
        if(!taskReleaseEty.getDeadline().equals("永久")){
            dateTv.setText(TimeUtil.newInstance().TimeStamp2Date(Long.valueOf(taskReleaseEty.getDeadline()), "yyyy/MM/dd HH:mm"));
        }else {
            dateTv.setText("截至日期："+taskReleaseEty.getDeadline());
        }


        Glide.with(SheepApp.getInstance())
                .load(taskEty.getIcon())
                .apply(new RequestOptions().placeholder(R.drawable.icon)
                        .dontAnimate())
                .into(iconIv);

        if (taskEty.getRunTask() == 0 || taskEty.getInspect_type() == 1) {
            detailTaskTv.setVisibility(View.INVISIBLE);
            bottom_btn_layout.setVisibility(View.VISIBLE);
        } else {
            detailTaskTv.setVisibility(View.VISIBLE);
            bottom_btn_layout.setVisibility(View.VISIBLE);

        }
        detail_task_listview.setVisibility(View.GONE);
        if (taskEty.getTask_type() == TASK_TYPE_CREDIT_CARD) {
            btnTaskItem.setText("信用卡注册");
        }
    }

    private void netTaskSchedule() {
        if (!isShowing())
            showProgress();
        getDetail();
    }

    private void getDetail(){

        SheepApp.getInstance().getNetComponent().getApiService().taskDesc(id)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(activity) {
                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        taskReleaseEty = baseMessage.getData(Release_task.class);
                        if(taskReleaseEty == null){
                            baseMessage.setMsg("暂无数据");
                            onError(baseMessage);
                            return;
                        }
                        taskEty = taskReleaseEty.getTask();
                        initData();
                        taskSchedule();
                        hideProgress();
                    }

                    @Override
                    public void onError(BaseMessage baseMessage) {
                        hideProgress();
                        G.showToast(baseMessage.getMsg() + "");
                    }
                });
    }

    @OnClick({R.id.detail_task_tv, R.id.web_text, R.id.ll_infos, R.id.btn_task_item, R.id.btn_up_imag})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.detail_task_tv://查看任务截图
                if (TextUtils.isEmpty(taskEty.getScreenshots())) {
                    G.showToast("任务截图为空");
                    return;
                }
                Jump2View.getInstance().goWeb(activity, taskEty.getScreenshots(), "任务提交示意");
                break;
            case R.id.web_text:
                break;
            case R.id.ll_infos:
                break;
            case R.id.btn_task_item:
                showProgress();
                acceptTask();
//                if (taskReleaseEty == null || taskReleaseEty.getAccepted_task_id() == 0) {
//                    acceptTask();
//                } else {
//                    goWeb();
//                }
                break;
            case R.id.btn_up_imag:
                showChooseDialog(false, true, DEFAULT_MAX_COUNT);
                UMConfigUtils.onEvent(UMConfigUtils.Event.TASK_UPLOAD_PICTURE);
                break;
        }
    }

    private void acceptTask() {
        int release_task_id = taskReleaseEty.getId();
        String device_id = DeviceUtil.getDeviceId(SheepApp.getInstance());
        UMConfigUtils.Event.TASK_ACCEPT.onEvent("device_id", device_id, "release_task_id", release_task_id);
        JSONObject object = new JSONObject();
        object.put("device_id", device_id);
        object.put("release_task_id", release_task_id);
        SheepApp.getInstance().getNetComponent().getApiService().releaseTaskCreditCard(object)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(getApplicationContext()) {
                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        goWeb();
                    }

                    @Override
                    public void onError(BaseMessage baseMessage) {
                        if (baseMessage.getCode() == 1001) {//已经接受过该任务
                            onNext(baseMessage);
                        } else {
                            G.showToast(baseMessage);
                            hideProgress();
                        }
                    }
                });
    }

    private void goWeb() {
        Jump2View.getInstance().tryGoCreditCardWeb(activity,taskReleaseEty.getId(), EntityUtils.getExtInfo(taskEty.getExt()).getId(), new Action1<String>() {
            @Override
            public void call(String msg) {
                if (msg == null) {
                    netTaskSchedule();
                } else {
                    G.showToast(msg);
                    hideProgress();
                }
            }
        });
    }

    /**
     * 任务进度
     */
    private void taskSchedule() {
        llInfos.removeAllViews();
        if (taskEty != null && taskReleaseEty != null && taskReleaseEty.getAccepted_task_id() != 0) {
            llInfos.addView(getStep("领取任务", "已完成", 0));
            if (taskEty.getTask_type() == TASK_TYPE_CREDIT_CARD) {//信用卡
                llInfos.addView(getStep("信用卡注册", "待完成", 2 ));
            } else if (PackageUtil.isAppInstalled(SheepApp.getInstance(), taskEty.getPackage_names())) {
                llInfos.addView(getStep("下载游戏", "已完成", 0));
                llInfos.addView(getStep("完成任务", "进行中", 1));
            } else {
                llInfos.addView(getStep("下载游戏", "待完成", 2));
            }
        } else {
            llInfos.addView(getStep("领取任务", "待完成", 2));
        }
    }


    private View getStep(String step, String state, int color) {
        View view = View.inflate(this, R.layout.task_step_info, null);
        ImageView img = view.findViewById(R.id.img_tab);
        TextView tvStep = view.findViewById(R.id.tv_step);
        TextView tvStatus = view.findViewById(R.id.tv_status);
        if (color == 0) {
            img.setImageResource(R.drawable.garden_green);
            tvStep.setTextColor(getResources().getColor(R.color.green));
            tvStatus.setTextColor(getResources().getColor(R.color.green));
        } else if (color == 1) {
            img.setImageResource(R.drawable.garden_yellow);
            tvStep.setTextColor(getResources().getColor(R.color.yellow_text_light));
            tvStatus.setTextColor(getResources().getColor(R.color.yellow_text_light));
        } else {
            img.setImageResource(R.drawable.garden_gray);
            tvStep.setTextColor(getResources().getColor(R.color.black_text_gray));
            tvStatus.setTextColor(getResources().getColor(R.color.black_text_gray));
        }

        tvStep.setText(step);
        tvStatus.setText(state);
        return view;
    }


    public void releaseTaskCreditCardSuccess(BaseMessage baseMessage) {
        setLoaddingText("完成");
        dismissLoaddingDialog();
        G.showToast("提交成功，等待审核!");
        finish();
    }

    public void releaseTaskCreditCard(int id, JSONObject jsonObject) {
        SheepApp.getInstance().getNetComponent().getApiService().releaseTaskCreditCard(id, jsonObject)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onError(BaseMessage baseMessage) {
                        updateError(baseMessage.getErrorMsg());
                    }

                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        releaseTaskCreditCardSuccess(baseMessage);
                    }
                });
    }

    @Override
    protected void onNotGetImage(String msg) {
        G.showToast(msg);
    }

    @Override
    protected void onGetImage(String path) {

    }

    @Override
    protected void onSetNetImageUrl(String url) {
        setLoaddingText("提交中");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("screenshots", url);
        releaseTaskCreditCard(taskReleaseEty.getAccepted_task_id(), jsonObject);
        taskEty.setScreenshots(url);
    }

    @Override
    protected void onGetNetImageUrl(String url) {

    }
}
