package com.fxy.net;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;

import com.fxy.BuildConfig;
import com.elvishew.xlog.XLog;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.fxy.baselibrary.language.other.MultiLanguageUtil;
import com.fxy.R;
import com.fxy.constant.SPCache;
import com.fxy.login.LoginActivity;

import org.json.JSONObject;

import es.dmoral.toasty.Toasty;


/**
 * ================================================
 * 作    者：jeasonlzy（廖子尧）
 * 版    本：1.0
 * 创建日期：2016/4/8
 * 描    述：我的Github地址  https://github.com/jeasonlzy0216
 * 修订历史：
 * ================================================
 */
public abstract class MyDialogCallback extends StringCallback {

    private Dialog dialog;
    private boolean needToken;
    private Context context;

    /**
     * 是否带token,是否显示dialog
     *
     * @param context
     * @param needToken
     * @param showDialog
     */
    public MyDialogCallback(Context context, boolean needToken, boolean showDialog) {
        this.needToken = needToken;
        this.context = context;
        if (showDialog) {
            showLoadDialog(context);
        }
    }

    /**
     * 是否带token
     *
     * @param context
     * @param needToken
     */
    public MyDialogCallback(Context context, boolean needToken) {
        this.needToken = needToken;
        showLoadDialog(context);
    }

    /**
     * 默认带token，显示dialog
     *
     * @param context
     */
    public MyDialogCallback(Context context) {
        this.needToken = true;
        showLoadDialog(context);
    }

    /**
     * 默认带token，不显示dialog
     */
    public void showLoadDialog(Context context) {
        this.context = context;
        LayoutInflater inflater = LayoutInflater.from(context);
        View v = inflater.inflate(R.layout.view_progress_dialog, null);// 得到加载view
        dialog = new Dialog(context, R.style.MyProgressDialog);// 创建自定义样式dialog
        dialog.setCancelable(true);// 不可以用“返回键”取消
        dialog.setCanceledOnTouchOutside(false);// 设置点击屏幕Dialog不消失
        dialog.setContentView(v, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));// 设置布局
    }

    @Override
    public void onStart(Request<String, ? extends Request> request) {
        // 获取系统语言
        String language = MultiLanguageUtil.getInstance().getLanguageWithCountry();
        // 设置请求头语言
        request.headers("lang",language);

        request.getHeaders().put("warehouse-id",SPCache.getInstance(context).getWareHouseId());
        request.getHeaders().put("version", BuildConfig.VERSION_API);

        // 请求是否携带token
        if (needToken) {
            request.getHeaders().put("token",SPCache.getInstance(context).getToken());
        }
        XLog.d(request.getUrl() + request.getParams());
        //网络请求前显示对话框
        if (dialog != null && !dialog.isShowing()) {
            dialog.show();
        }
    }

    @Override
    public void onFinish() {
        // 网络请求结束后闭对话框
        if (dialog != null && dialog.isShowing()) {
            try {
                dialog.dismiss();
            } catch (Exception e) {
                e.printStackTrace();
                XLog.e("接口返回"+e.getMessage());
            }

        }

    }

    @Override
    public void onSuccess(Response<String> response) {
        try {
            // 输出响应报文
            JSONObject object = new JSONObject(response.body());
            XLog.d(object);
            // 没有权限或者token过期(参照服务端约定code)
            int code = object.optInt("code");
            if (code == -5) {
                //Toasty.normal(context, context.getString(R.string.toast_common_token_lose)).show();
                XLog.d("登陆超时，token："+SPCache.getInstance(context).getToken());
                SPCache.getInstance(context).clearCache();
                context.startActivity(new Intent(context, LoginActivity.class).putExtra("type", 1));
            }
        } catch (Exception e1) {
            e1.printStackTrace();
            Toasty.error(context, context.getString(R.string.toast_common_service_inner_error)).show();
        }
    }

    @Override
    public void onError(Response<String> response) {
        super.onError(response);
        try {
            JSONObject object = new JSONObject(response.body());
            int code = object.optInt("code");
            // 没有权限或者token过期
            if (code == -5) {
                Toasty.normal(context, context.getString(R.string.toast_common_token_lose)).show();
                SPCache.getInstance(context).clearCache();
                context.startActivity(new Intent(context, LoginActivity.class).putExtra("type", 1));
            }
            else if(code != 1){
                Toasty.normal(context, object.optString("msg", context.getString(R.string.toast_common_net_fail) + code)).show();
            }
        } catch (Exception e1) {
            e1.printStackTrace();
            Toasty.error(context, context.getString(R.string.toast_common_lianjieshibai)).show();
        }
    }
}