package com.zhilianxinke.schoolinhand.modules.users;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.utils.L;
import com.zhilianxinke.schoolinhand.AppContext;
import com.zhilianxinke.schoolinhand.R;
import com.zhilianxinke.schoolinhand.common.FastJsonRequest;
import com.zhilianxinke.schoolinhand.domain.AppChild;
import com.zhilianxinke.schoolinhand.domain.AppUser;
import com.zhilianxinke.schoolinhand.domain.SdkHttpResult;
import com.zhilianxinke.schoolinhand.modules.users.adapters.ChildAdapter;
import com.zhilianxinke.schoolinhand.rongyun.ui.WinToast;
import com.zhilianxinke.schoolinhand.util.UrlBuilder;
import com.zhilianxinke.schoolinhand.util.view.RoundImageView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import io.rong.imkit.RongIM;


public class UserFragment extends Fragment implements OnClickListener {
    public UserFragment() {
    }

    private View view;
    private String customerServiceId = "KEFU1426171503766";
    private TextView f_user_name;
    private TextView f_user_phone;
    private RoundImageView f_user_img;
    public RequestQueue requestQueue;
    private ChildAdapter _childAdapter;
    private LinkedList<AppChild> _dataList;
    private ListView f_user_ChildList;
    DisplayImageOptions options;        // DisplayImageOptions是用于设置图片显示的类
    private AppUser appUser;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_user, container, false);
        options = new DisplayImageOptions.Builder()
                .showStubImage(R.drawable.mantouxiang)          // 设置图片下载期间显示的图片
                .showImageForEmptyUri(R.drawable.mantouxiang)  // 设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(R.drawable.mantouxiang)       // 设置图片加载或解码过程中发生错误显示的图片
                .cacheInMemory()                        // 设置下载的图片是否缓存在内存中
                .cacheOnDisc()                          // 设置下载的图片是否缓存在SD卡中
                .build();
        f_user_name = (TextView) view.findViewById(R.id.f_user_name);
        f_user_phone = (TextView) view.findViewById(R.id.f_user_phone);
        f_user_img = (RoundImageView) view.findViewById(R.id.f_user_img);
        view.findViewById(R.id.btnCustomerService).setOnClickListener(this);
        view.findViewById(R.id.f_user_btnPhoto).setOnClickListener(this);
        view.findViewById(R.id.f_user_btnCourse).setOnClickListener(this);
        view.findViewById(R.id.f_user_btnSet).setOnClickListener(this);
        view.findViewById(R.id.f_user_btnPublish).setOnClickListener(this);
        view.findViewById(R.id.f_user_img).setOnClickListener(this);
        f_user_ChildList = (ListView) view.findViewById(R.id.f_user_ChildList);
        requestQueue = Volley.newRequestQueue(getActivity());
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        appUser = AppContext.getAppUser(getActivity());
        if (SetActivity.portraitPath != null) {
            Bitmap bitmap = BitmapFactory.decodeFile(SetActivity.portraitPath);
            f_user_img.setImageBitmap(bitmap);
            AppUser appUser = AppContext.getAppUser(getActivity());
            appUser.setPortrait(SetActivity.portraitPath);
            AppContext.cacheNews(getActivity(),appUser);
            SetActivity.portraitPath = null;
        }

        if (appUser != null) {
            //设置用户头像。。。
            if (appUser.getPortrait() == null || appUser.getPortrait().equals("")) {
                ImageLoader.getInstance().displayImage("http://7xlmvl.com2.z0.glb.qiniucdn.com/58c98d7e-e9cd-4393-b551-8cb769dc7256.jpg", f_user_img, options);
            } else {
                String path = UrlBuilder.thumbnailImageUrl(appUser.getPortrait());
                if (!path.contains("http://")) {
                    Bitmap bitmap = BitmapFactory.decodeFile(path);
                    f_user_img.setImageBitmap(bitmap);
                } else {
                    path.substring(path.lastIndexOf("http://"), path.length());
                    L.i("头像3" + path);
                    ImageLoader.getInstance().displayImage(path, f_user_img, options);
                }

            }
        }
        f_user_phone.setText(AppContext.getAppUser(getActivity()).getUuid());
        f_user_name.setText(AppContext.getAppUser(getActivity()).getName());
        if (AppContext.getAppUser(getActivity()).getGender() == 0) {
            f_user_name.setTextColor(Color.parseColor("#ff69b4"));
        } else {
            f_user_name.setTextColor(Color.parseColor("#ff5d79ea"));
        }
        getJSONVolley();
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                _childAdapter = new ChildAdapter(getActivity(), R.layout.de_item_child, _dataList);
                f_user_ChildList.setAdapter(_childAdapter);
            }
            super.handleMessage(msg);
        }
    };

    public String getJSONVolley() {
        AppUser appUser = AppContext.getAppUser(getActivity());
        Map<String, String> params = new HashMap<>(2);
        params.put("userId", appUser.getUuid());
        String baseUrl = UrlBuilder.Api_childrens;
        String url = UrlBuilder.build(baseUrl, params);
        FastJsonRequest<SdkHttpResult> fastJson = new FastJsonRequest<SdkHttpResult>(url, SdkHttpResult.class,
                new Response.Listener<SdkHttpResult>() {
                    @Override
                    public void onResponse(SdkHttpResult sdkHttpResult) {
                        if (sdkHttpResult != null && sdkHttpResult.getCode() == 200) {
                            String result = sdkHttpResult.getResult();
                            AppContext.saveSharedPreferences("user", result);//将家长孩子的信息保存到本地
                            ArrayList<AppChild> list = (ArrayList<AppChild>) JSON.parseArray(result, AppChild.class);
                            AppContext.saveChild(getActivity(),list);//保存孩子信息
                            _dataList = new LinkedList<AppChild>();
                            for (AppChild appChilds : list) {
                                _dataList.addFirst(appChilds);
                            }
                            handler.sendEmptyMessage(1);
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyError ve = error;
                if (ve != null) {
                    WinToast.toast(getActivity(), "请注意检查网络");
                    String result = AppContext.getSharedPreferences("user");
                    if (!result.equals("")) {
                        List<AppChild> list = JSON.parseArray(result, AppChild.class);
                        _dataList = new LinkedList<AppChild>();
                        for (AppChild appChilds : list) {
                            _dataList.addFirst(appChilds);
                        }
                        handler.sendEmptyMessage(1);
                    }
                }
            }
        });
        requestQueue.add(fastJson);
        return null;
    }

    // 用来实现 UI 线程的更新。
//    Handler mHandler;
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.f_user_btnSet: {
                //设置
                Intent intent = new Intent(getActivity(), SetActivity.class);
                startActivity(intent);
                break;
            }
            case R.id.f_user_btnCourse: {
                //宝贝相册
                // WinToast.toast(getActivity(), "功能暂未开通，敬请期待！");
                Intent intent = new Intent(getActivity(), BabyAlbumActivity.class);
                startActivity(intent);
                break;
            }
            case R.id.f_user_btnPhoto: {
                //宝贝课程
                Intent intent = new Intent(getActivity(), PhotoActivity.class);
                startActivity(intent);
                break;
            }
            case R.id.f_user_btnPublish: {
              /*  //我的动态
                Intent intent = new Intent(getActivity(), TrendsActivity.class);
                startActivity(intent);*/
                break;
            }
            case R.id.btnCustomerService:
                RongIM.getInstance().startCustomerServiceChat(getActivity(), customerServiceId, "客服");
                break;
        }
    }


}
