package ai.pai.client.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.common.executors.ThreadExecutor;
import com.android.common.utils.DeviceUtils;
import com.android.common.utils.JSONParseUtils;
import com.android.common.utils.LogHelper;
import com.android.common.utils.NetworkUtil;
import com.android.common.utils.TimeUtils;
import com.android.views.popup.InputMethodUtils;
import com.android.views.roundrect.RoundedImageView;
import com.tencent.mm.sdk.modelbase.BaseResp;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

import ai.pai.client.R;
import ai.pai.client.adapter.CommentListAdapter;
import ai.pai.client.adapter.DetailPhotoPageAdapter;
import ai.pai.client.beans.CommentBean;
import ai.pai.client.beans.GroupInfo;
import ai.pai.client.beans.GroupPhotoItem;
import ai.pai.client.db.DBService;
import ai.pai.client.db.Preferences;
import ai.pai.client.utils.GroupCreateUtils;
import ai.pai.client.utils.HttpPostTask;
import ai.pai.client.utils.PhotoLoader;
import ai.pai.client.utils.SystemUtils;
import ai.pai.client.utils.UmengEvent;
import ai.pai.client.utils.UrlContainer;
import ai.pai.client.views.CountView;
import ai.pai.client.views.InputPopup;
import ai.pai.client.views.NestedListView;
import ai.pai.client.views.PhotoSharePopup;
import ai.pai.client.wxapi.PayListenerManager;
import ai.pai.client.wxapi.PayResultListener;

public class PhotoDetailsActivity extends BaseActivity implements View.OnClickListener,ViewPager.OnPageChangeListener,PayResultListener {

    private ImageView groupAvatarImg;
    private TextView groupNameText;
    private ViewPager photoPager;
    private ImageView uploaderAvatarImg;
    private TextView uploaderNameText;
    private TextView uploadTimeText;
    private TextView photoCommentText;
    private TextView photoThumbupText;
    private View groupInfoLayout;
    private View uploaderInfoLayout;
    private ImageView thumbArrowImg;
    private ImageView commentArrowImg;

    private LinearLayout thumbAvatarsLayout;
    private NestedListView commentListView;

    private View bottomLayout;
    private View functionalPanel;
    private View getHDPhotoLayout;
    private View bottomLayoutForPaid;
    private CountView buyHDPhotoTextView;
    private View getWipeWaterPrintLayout;
    private CountView buyWipeWaterPrintTextView;
    private TextView getHDPhotoText;
    private TextView getWipeWaterPrintText;
    private View hdWrapperLayout;


    private UMShareAPI mShareAPI;
    private PhotoSharePopup sharePop;
    private InputPopup inputPopup;

    private HttpPostTask fetchThumbUpListTask;
    private HttpPostTask fetchCommentListTask;
    private HttpPostTask submitCommentTask;
    private HttpPostTask submitThumbUpTask;
    private HttpPostTask wxPayTask;
    private HttpPostTask getPriceTask;
    private HttpPostTask checkOrderTask;
    private HttpPostTask getPhotoOrderInfoTask;

    private ArrayList<GroupPhotoItem> photoList;
    private GroupPhotoItem currentPhotoItem;

    private IWXAPI wxAPI;

    private boolean fromGroupPage;

    private String orderId;

    private boolean isPayListenerRegistered;

    private static final String PAY_TYPE_NO_MARK = "nomark";

    private static final String PAY_TYPE_ORIGIN = "origin";

    private static final String APP_ID = "wx4e22a0c8ae6d766d";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_photo_details);
        SystemUtils.setImmerseLayout(this, findViewById(R.id.title_layout));
        currentPhotoItem = (GroupPhotoItem) getIntent().getSerializableExtra("photo_item");
        if (currentPhotoItem == null) {
            finish();
            return;
        }
        if(getIntent().getSerializableExtra("list")!=null){
            photoList = (ArrayList<GroupPhotoItem>)getIntent().getSerializableExtra("list");
        }
        if(photoList==null){
            photoList = new ArrayList<GroupPhotoItem>();
            photoList.add(currentPhotoItem);
        }
        fromGroupPage = getIntent().getBooleanExtra("fromGroup",false);
        initViews();
        DetailPhotoPageAdapter photoPageAdapter = new DetailPhotoPageAdapter(this,photoList);
        photoPager.setAdapter(photoPageAdapter);
        photoPager.addOnPageChangeListener(this);
        photoPager.setCurrentItem(photoList.indexOf(currentPhotoItem));
        updateDetailHead();
        updateDetailBottom();
        wxAPI = WXAPIFactory.createWXAPI(this, APP_ID,false);
        wxAPI.registerApp(APP_ID);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (isPayListenerRegistered) {
            PayListenerManager.getInstance().removePayResultListener("play");
            isPayListenerRegistered = false;
        }
        if (fetchThumbUpListTask != null) {
            fetchThumbUpListTask.cancel(true);
            fetchThumbUpListTask = null;
        }
        if (fetchCommentListTask != null) {
            fetchCommentListTask.cancel(true);
            fetchCommentListTask = null;
        }
        if (submitCommentTask != null) {
            submitCommentTask.cancel(true);
            submitCommentTask = null;
        }
        if (submitThumbUpTask != null) {
            submitThumbUpTask.cancel(true);
            submitThumbUpTask = null;
        }
        if(wxPayTask!=null){
            wxPayTask.cancel(true);
            wxPayTask = null;
        }
        if(checkOrderTask!=null){
            checkOrderTask.cancel(true);
            checkOrderTask = null;
        }
        if(getPriceTask!=null){
            getPriceTask.cancel(true);
            getPriceTask = null;
        }
    }

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

    private void initViews() {
        groupAvatarImg = (ImageView) findViewById(R.id.iv_group_avatar);
        groupNameText = (TextView) findViewById(R.id.tv_group_name);
        uploaderAvatarImg = (ImageView) findViewById(R.id.iv_uploader_avatar);
        uploaderNameText = (TextView) findViewById(R.id.tv_uploader_name);
        uploadTimeText = (TextView) findViewById(R.id.tv_create_time);
        photoPager = (ViewPager) findViewById(R.id.pager_photos);
        photoCommentText = (TextView)findViewById(R.id.tv_detail_comment_count);
        photoThumbupText = (TextView)findViewById(R.id.tv_detail_thumb_count);

        getWipeWaterPrintText = (TextView)findViewById(R.id.tv_wipe_water_print);
        getHDPhotoText = (TextView)findViewById(R.id.tv_get_hd_photo);

        thumbAvatarsLayout = (LinearLayout)findViewById(R.id.layout_thumb_avatars);
        commentListView = (NestedListView) findViewById(R.id.list_detail_comments);
        groupInfoLayout = findViewById(R.id.layout_detail_header);
        uploaderInfoLayout = findViewById(R.id.layout_uploader_info);
        bottomLayout = findViewById(R.id.layout_detail_bottom);
        bottomLayoutForPaid = findViewById(R.id.layout_detail_bottom_for_paid);
        getHDPhotoLayout = findViewById(R.id.layout_get_hd_photo);
        getWipeWaterPrintLayout = findViewById(R.id.layout_wipe_water_print);
        buyHDPhotoTextView = (CountView) findViewById(R.id.tv_buy_hd_photo);
        buyWipeWaterPrintTextView = (CountView)findViewById(R.id.tv_buy_wipe_water_print);
        functionalPanel = findViewById(R.id.layout_functional_panel);
        thumbArrowImg = (ImageView)findViewById(R.id.iv_thumbup_arrow);
        commentArrowImg = (ImageView)findViewById(R.id.iv_comment_arrow);
        hdWrapperLayout = findViewById(R.id.layout_hd_wrapper);
        ((TextView) findViewById(R.id.title_bar_middle_txt)).setText(R.string.photo_details);
        findViewById(R.id.title_bar_back_layout).setOnClickListener(this);
        findViewById(R.id.title_bar_option_layout).setVisibility(View.INVISIBLE);
        findViewById(R.id.tv_enter_group).setOnClickListener(this);
        findViewById(R.id.floating_btn_thumbup).setOnClickListener(this);
        findViewById(R.id.floating_btn_comment).setOnClickListener(this);
        findViewById(R.id.floating_btn_share).setOnClickListener(this);
        findViewById(R.id.layout_detail_comment).setOnClickListener(this);
        findViewById(R.id.layout_detail_thumb).setOnClickListener(this);
        findViewById(R.id.iv_share_paid_photo).setOnClickListener(this);
        getHDPhotoLayout.setOnClickListener(this);
        getWipeWaterPrintLayout.setOnClickListener(this);
        buyHDPhotoTextView.setOnClickListener(this);
        buyWipeWaterPrintTextView.setOnClickListener(this);
    }

    private void updateDetailHead() {
        if(TextUtils.isEmpty(currentPhotoItem.groupName)){
            groupInfoLayout.setVisibility(View.GONE);
            return;
        }else{
            groupInfoLayout.setVisibility(View.VISIBLE);
        }
        groupNameText.setText(currentPhotoItem.groupName);
        if (currentPhotoItem.groupDefaultAvatar >= 0) {
            groupAvatarImg.setImageResource(GroupCreateUtils.getDrawableIdForAvatar(currentPhotoItem.groupDefaultAvatar));
        } else {
            PhotoLoader.getInstance(this).displayImage(currentPhotoItem.groupAvatar, groupAvatarImg,PhotoLoader.getPhotoOptions());
        }
    }

    private void updateDetailBottom() {
        if(TextUtils.isEmpty(currentPhotoItem.uploaderName)){
            uploaderInfoLayout.setVisibility(View.GONE);
        }else{
            uploaderInfoLayout.setVisibility(View.VISIBLE);
            uploaderNameText.setText(currentPhotoItem.uploaderName);
            uploadTimeText.setText(TimeUtils.getFormattedTime(currentPhotoItem.captureTime));
            PhotoLoader.getInstance(this).displayImage(currentPhotoItem.uploaderAvatar, uploaderAvatarImg,PhotoLoader.getUserAvatarOptions());
        }
        if(currentPhotoItem.photoFrom ==0){
            bottomLayoutForPaid.setVisibility(View.GONE);
            bottomLayout.setVisibility(View.VISIBLE);
            functionalPanel.setVisibility(View.VISIBLE);
            photoCommentText.setText("("+String.valueOf(currentPhotoItem.commentNum)+")");
            photoThumbupText.setText("("+String.valueOf(currentPhotoItem.thumbupNum)+")");
            thumbAvatarsLayout.setVisibility(View.GONE);
            commentListView.setVisibility(View.GONE);
            thumbArrowImg.setImageResource(R.drawable.arrow_down);
            commentArrowImg.setImageResource(R.drawable.arrow_down);
            doFetchThumbListTask();
            doFetchCommentListTask();
        }else{
            bottomLayoutForPaid.setVisibility(View.VISIBLE);
            if(currentPhotoItem.originExpiredStamps<System.currentTimeMillis()){
                hdWrapperLayout.setVisibility(View.GONE);
            }else{
                hdWrapperLayout.setVisibility(View.VISIBLE);
            }
            bottomLayout.setVisibility(View.VISIBLE);
            functionalPanel.setVisibility(View.VISIBLE);
            photoCommentText.setText("("+String.valueOf(currentPhotoItem.commentNum)+")");
            photoThumbupText.setText("("+String.valueOf(currentPhotoItem.thumbupNum)+")");
            thumbAvatarsLayout.setVisibility(View.GONE);
            commentListView.setVisibility(View.GONE);
            thumbArrowImg.setImageResource(R.drawable.arrow_down);
            commentArrowImg.setImageResource(R.drawable.arrow_down);
            doFetchThumbListTask();
            doFetchCommentListTask();
            if(TextUtils.isEmpty(currentPhotoItem.mediumPhotoUrl)
                    ||(TextUtils.isEmpty(currentPhotoItem.rawPhotoUrl)&&currentPhotoItem.originExpiredStamps>System.currentTimeMillis() )){
                doGetPhotoOrderInfo();
            }
            updatePhotoPaidUI();
        }
    }

    private void updatePhotoPaidUI(){
        if(TextUtils.isEmpty(currentPhotoItem.mediumPhotoUrl)){
            getWipeWaterPrintText.setText(R.string.wipe_water_print_str);
        }else{
            getWipeWaterPrintText.setText(R.string.can_wipe_water_print_str);
        }
        if(TextUtils.isEmpty(currentPhotoItem.rawPhotoUrl)){
            getHDPhotoText.setText(R.string.get_hd_photo_str);
        }else{
            getHDPhotoText.setText(R.string.can_get_hd_photo_str);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_bar_back_layout:
                finish();
                break;
            case R.id.floating_btn_comment:
                MobclickAgent.onEvent(this, UmengEvent.detail_comment_btn_click);
                inputPopup = new InputPopup(this,this);
                inputPopup.showPopupWindow();
                break;
            case R.id.btn_comment_send:
                MobclickAgent.onEvent(this, UmengEvent.detail_comment_send_btn_click);
                if(inputPopup!=null){
                    InputMethodUtils.hideInputMethod(inputPopup.getInputView());
                    inputPopup.dismiss();
                    doPhotoCommentTask(inputPopup.getInputContent());
                }
                break;
            case R.id.iv_share_paid_photo:
            case R.id.floating_btn_share:
                MobclickAgent.onEvent(this, UmengEvent.detail_share_btn_click);
                sharePhoto();
                break;
            case R.id.floating_btn_thumbup:
                MobclickAgent.onEvent(this, UmengEvent.detail_thumb_btn_click);
                doPhotoThumbUpTask();
                break;
            case R.id.tv_enter_group:
                MobclickAgent.onEvent(this, UmengEvent.detail_enter_group_btn_click);
                if(fromGroupPage){
                    finish();
                }else{
                    GroupInfo info = new GroupInfo();
                    info.groupAvatarId = currentPhotoItem.groupDefaultAvatar;
                    info.groupId = currentPhotoItem.groupId;
                    info.groupName = currentPhotoItem.groupName;
                    Intent intent = new Intent(this,GroupActivity.class);
                    intent.putExtra("group",info);
                    startActivity(intent);
                    finish();
                }
                break;
            case R.id.layout_detail_comment:
                if(commentListView.getVisibility()==View.VISIBLE){
                    commentListView.setVisibility(View.GONE);
                    commentArrowImg.setImageResource(R.drawable.arrow_down);
                }else{
                    doFetchCommentListTask();
                }
                break;
            case R.id.layout_detail_thumb:
                if(thumbAvatarsLayout.getVisibility()==View.VISIBLE){
                    thumbArrowImg.setImageResource(R.drawable.arrow_down);
                    thumbAvatarsLayout.setVisibility(View.GONE);
                }else{
                    doFetchThumbListTask();
                }
                break;
            case R.id.layout_share_qq:
                sharePhotoTo(SHARE_MEDIA.QQ);
                break;
            case R.id.layout_share_weibo:
                sharePhotoTo(SHARE_MEDIA.SINA);
                break;
            case R.id.layout_share_wechat:
                sharePhotoTo(SHARE_MEDIA.WEIXIN);
                break;
            case R.id.layout_share_friend_circle:
                sharePhotoTo(SHARE_MEDIA.WEIXIN_CIRCLE);
                break;
            case R.id.layout_get_hd_photo:
                clickGetPhoto(PAY_TYPE_ORIGIN);
                break;
            case R.id.tv_buy_hd_photo:
                MobclickAgent.onEvent(this, UmengEvent.detail_buy_origin_btn_click);
                clickPay(buyHDPhotoTextView.getNumber(),PAY_TYPE_ORIGIN);
                break;
            case R.id.layout_wipe_water_print:
                clickGetPhoto(PAY_TYPE_NO_MARK);
                break;
            case R.id.tv_buy_wipe_water_print:
                MobclickAgent.onEvent(this, UmengEvent.detail_waterprint_btn_click);
                clickPay(buyWipeWaterPrintTextView.getNumber(),PAY_TYPE_NO_MARK);
                break;
            default:
                break;
        }
    }

    private void clickPay(float fee,String type){
        if(!NetworkUtil.isNetworkConnected(this)){
            Toast.makeText(this,R.string.network_disconnect,Toast.LENGTH_SHORT).show();
            return;
        }
        if (!isPayListenerRegistered) {
            PayListenerManager.getInstance().putPayResultListener("play",this);
            isPayListenerRegistered = true;
        }
        Toast.makeText(this,R.string.pay_create_order,Toast.LENGTH_SHORT).show();
        doWXPayTask(fee,type);
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        currentPhotoItem = photoList.get(position);
        updateDetailHead();
        updateDetailBottom();
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    private void sharePhoto() {
        sharePop = new PhotoSharePopup(this,this);
        sharePop.showPopupWindow();
    }

    private void sharePhotoTo(SHARE_MEDIA media){
        mShareAPI = UMShareAPI.get(this);
        String shareUrl = currentPhotoItem.shareUrl;
        if(TextUtils.isEmpty(shareUrl)){
            shareUrl = currentPhotoItem.photoUrl;
        }
        new ShareAction(this)
                .setPlatform(media)
                .setCallback(new UMShareListener() {
                    @Override
                    public void onResult(SHARE_MEDIA share_media) {

                    }

                    @Override
                    public void onError(SHARE_MEDIA share_media, Throwable throwable) {

                    }

                    @Override
                    public void onCancel(SHARE_MEDIA share_media) {

                    }
                }).withTitle(getString(R.string.app_name))
                .withText(getString(R.string.default_share_text)).withTargetUrl(shareUrl)
                .withMedia(new UMImage(this, currentPhotoItem.thumbnailUrl))
                .share();
        if(sharePop!=null){
            sharePop.dismiss();
        }
    }


    private void doCheckOrder(String transaction) {
        if (checkOrderTask != null && checkOrderTask.getStatus() == AsyncTask.Status.RUNNING) {
            checkOrderTask.cancel(true);
        }
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("order_id", orderId);
        if(!TextUtils.isEmpty(transaction)){
            params.put("transaction_id", transaction);
        }
        checkOrderTask = new HttpPostTask(this, params) {

            String toastMsg = "";
            @Override
            protected boolean parseResponse(Context context, String response) {
                try {
                    JSONObject json = new JSONObject(response);
                    int status = json.getInt("status");
                    toastMsg = json.getString("description");
                    if (status == 200) {
                        LogHelper.d(TAG, " doCheckOrder parseResponse status ok");
                        return true;
                    }
                } catch (Exception e) {
                    LogHelper.d(TAG, " doCheckOrder parseResponse error :" + e);
                }
                return false;
            }

            @Override
            protected void onPostFail(Context context) {
                super.onPostFail(context);
                if(!TextUtils.isEmpty(toastMsg)){
                    Toast.makeText(context,toastMsg,Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            protected void onPostSuccess(Context context) {
                super.onPostSuccess(context);
                if(!TextUtils.isEmpty(toastMsg)){
                    Toast.makeText(context,toastMsg,Toast.LENGTH_SHORT).show();
                }
                jumpWhenPaid();
            }

        };
        checkOrderTask.executeOnExecutor(ThreadExecutor.getInstance().getExecutor(),UrlContainer.QUERY_ORDER_URL);
    }

    private void doWXPayTask(float fee,String type) {
        if (wxPayTask != null && wxPayTask.getStatus() == AsyncTask.Status.RUNNING) {
            wxPayTask.cancel(true);
        }
        int feeInteger =(int)(fee *100);
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("photo_id", currentPhotoItem.photoId);
        params.put("user_id", Preferences.getInstance(this).getUserId());
//        params.put("total_fee",String.valueOf(feeInteger));
        params.put("total_fee","1");
        params.put("body",getString(R.string.order_body_buy_from,currentPhotoItem.uploaderName));
        params.put("trade_type","APP");
        params.put("photo_type",type);
        params.put("group_id",currentPhotoItem.groupId);
        wxPayTask = new HttpPostTask(this, params) {

            PayReq req = null;

            @Override
            protected boolean parseResponse(Context context, String response) {
                try {
                    JSONObject json = new JSONObject(response);
                    int status = json.getInt("status");
                    if (status == 200) {
                        LogHelper.d(TAG, " wxPayTask parseResponse status ok");
                        JSONObject info = json.getJSONObject("data");
                        orderId = info.getString("order_id");
                        req = new PayReq();
                        JSONObject wxParams = info.getJSONObject("wxpay_params");
                        req.appId = wxParams.getString("appid");
                        req.partnerId = wxParams.getString("partnerid");
                        req.packageValue =wxParams.getString("package");
                        req.prepayId = wxParams.getString("prepayid");
                        req.nonceStr = wxParams.getString("noncestr");
                        req.timeStamp = wxParams.getString("timestamp");
                        req.sign = wxParams.getString("sign");
                        return true;
                    }
                } catch (Exception e) {
                    LogHelper.d(TAG, " wxPayTask parseResponse error :" + e);
                }
                return false;
            }

            @Override
            protected void onPostFail(Context context) {
                super.onPostFail(context);
                Toast.makeText(getApplicationContext(), R.string.create_order_fail, Toast.LENGTH_SHORT).show();
            }

            @Override
            protected void onPostSuccess(Context context) {
                super.onPostSuccess(context);
                if(req!=null){
                    wxAPI.sendReq(req);
                }
            }

        };
        wxPayTask.executeOnExecutor(ThreadExecutor.getInstance().getExecutor(),UrlContainer.CREATE_ORDER_URL);
    }

    private void doGetPhotoOrderInfo() {
        if(!TextUtils.isEmpty(currentPhotoItem.mediumPhotoUrl)&&!TextUtils.isEmpty(currentPhotoItem.rawPhotoUrl)){
            return;
        }
        if (getPhotoOrderInfoTask != null && getPhotoOrderInfoTask.getStatus() == AsyncTask.Status.RUNNING) {
            getPhotoOrderInfoTask.cancel(true);
        }
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("user_id", Preferences.getInstance(this).getUserId());
        params.put("photo_id", currentPhotoItem.photoId);
        getPhotoOrderInfoTask = new HttpPostTask(this, params) {
            @Override
            protected boolean parseResponse(Context context, String response) {
                try {
                    JSONObject json = new JSONObject(response);
                    int status = json.getInt("status");
                    if (status == 200) {
                        LogHelper.d(TAG, " getPhotoOrderInfoTask parseResponse status ok");
                        JSONObject data = json.getJSONObject("data");
                        JSONObject porder = data.getJSONObject("porder");
                        if(porder.has("r_photo_url")){
                            String rPhotoUrl = JSONParseUtils.getJSONString(porder.getString("r_photo_url"));
                            currentPhotoItem.rawPhotoUrl = rPhotoUrl;                        }
                        if(porder.has("m_photo_url")){
                            String mPhotoUrl = JSONParseUtils.getJSONString(porder.getString("m_photo_url"));
                            currentPhotoItem.mediumPhotoUrl = mPhotoUrl;
                        }
                        return true;
                    }
                } catch (Exception e) {
                    LogHelper.d(TAG, " getPhotoOrderInfoTask parseResponse error :" + e);
                }
                return false;
            }

            @Override
            protected void onPostFail(Context context) {
                super.onPostFail(context);
            }

            @Override
            protected void onPostSuccess(Context context) {
                super.onPostSuccess(context);
                ArrayList<GroupPhotoItem> photos = new ArrayList<>();
                photos.add(currentPhotoItem);
                updatePhotoPaidUI();
                DBService.getInstance(getApplicationContext()).addGroupPhotoList(photos);
            }

        };
        getPhotoOrderInfoTask.executeOnExecutor(ThreadExecutor.getInstance().getExecutor(), UrlContainer.BOUGHT_PHOTO_URL);
    }

    private void clickGetPhoto(String type){
        if(type.equals(PAY_TYPE_NO_MARK)){
            if(!TextUtils.isEmpty(currentPhotoItem.mediumPhotoUrl)){
                jumpWhenPaid();
                return;
            }
        }else if(type.equals(PAY_TYPE_ORIGIN)){
            if(!TextUtils.isEmpty(currentPhotoItem.rawPhotoUrl)){
                jumpWhenPaid();
                return;
            }
        }
        doGetPrice(type);
    }
    private void doGetPrice(final String type) {

        if (getPriceTask != null && getPriceTask.getStatus() == AsyncTask.Status.RUNNING) {
            getPriceTask.cancel(true);
        }
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("photo_id", currentPhotoItem.photoId);
        params.put("user_id", Preferences.getInstance(this).getUserId());
        params.put("photo_type",type);
        getPriceTask = new HttpPostTask(this, params) {

            int price = 0;

            @Override
            protected boolean parseResponse(Context context, String response) {
                try {
                    JSONObject json = new JSONObject(response);
                    int status = json.getInt("status");
                    if (status == 200) {
                        JSONObject info = json.getJSONObject("data");
                        price = info.getInt("price");
                        LogHelper.d(TAG, " doGetPrice parseResponse status ok and price="+price);
                        return true;
                    }
                } catch (Exception e) {
                    LogHelper.d(TAG, " doGetPrice parseResponse error :" + e);
                }
                return false;
            }

            @Override
            protected void onPostFail(Context context) {
                super.onPostFail(context);
                Toast.makeText(context,R.string.get_price_fail,Toast.LENGTH_SHORT).show();
            }

            @Override
            protected void onPostSuccess(Context context) {
                super.onPostSuccess(context);
                if(type.equals(PAY_TYPE_NO_MARK)){
                    getWipeWaterPrintLayout.setVisibility(View.GONE);
                    buyWipeWaterPrintTextView.setVisibility(View.VISIBLE);
                    buyWipeWaterPrintTextView.setNumber(price/100.0f);
                }else if(type.equals(PAY_TYPE_ORIGIN)){
                    getHDPhotoLayout.setVisibility(View.GONE);
                    buyHDPhotoTextView.setVisibility(View.VISIBLE);
                    buyHDPhotoTextView.setNumber(price/100.0f);
                }
            }

        };
        getPriceTask.executeOnExecutor(ThreadExecutor.getInstance().getExecutor(),UrlContainer.GET_PRICE_URL);
    }

    private void doFetchCommentListTask() {
        if (fetchCommentListTask != null && fetchCommentListTask.getStatus() == AsyncTask.Status.RUNNING) {
            fetchCommentListTask.cancel(true);
        }
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("user_id", Preferences.getInstance(this).getUserId());
        params.put("group_id", currentPhotoItem.groupId);
        params.put("photo_id", currentPhotoItem.photoId);

        fetchCommentListTask = new HttpPostTask(this, params) {

            private ArrayList<CommentBean> commentsList;

            @Override
            protected boolean parseResponse(Context context, String response) {
                try {
                    JSONObject json = new JSONObject(response);
                    int status = json.getInt("status");
                    if (status == 200) {
                        LogHelper.d(TAG, " fetchCommentListTask parseResponse status ok");
                        JSONObject info = json.getJSONObject("data");
                        JSONArray commentArray = info.getJSONArray("comments");
                        if (commentArray != null && commentArray.length() > 0) {
                            int len = commentArray.length();
                            commentsList = new ArrayList<CommentBean>();
                            for (int k = 0; k < len; k++) {
                                JSONObject obj = commentArray.getJSONObject(k);
                                CommentBean bean = new CommentBean();
                                bean.avatarUrl = obj.getString("avatar");
                                bean.comment = obj.getString("comment");
                                bean.nickname = obj.getString("nickname");
                                bean.time = obj.getString("created_at");
                                bean.userId = obj.getString("user_id");
                                commentsList.add(bean);
                            }
                        }
                        return true;
                    }
                } catch (Exception e) {
                    LogHelper.d(TAG, " fetchCommentListTask parseResponse error :" + e);
                }
                return false;
            }

            @Override
            protected void onPostFail(Context context) {
                super.onPostFail(context);
//                Toast.makeText(getApplicationContext(), R.string.fetch_photo_comment_fail, Toast.LENGTH_SHORT).show();
            }

            @Override
            protected void onPostSuccess(Context context) {
                super.onPostSuccess(context);
                if (commentsList != null) {
                    photoCommentText.setText("("+String.valueOf(commentsList.size())+")");
                    commentListView.setVisibility(View.VISIBLE);
                    commentArrowImg.setImageResource(R.drawable.arrow_up);
                    CommentListAdapter adapter = new CommentListAdapter(PhotoDetailsActivity.this, commentsList);
                    commentListView.setAdapter(adapter);
                }
            }

        };
        fetchCommentListTask.executeOnExecutor(ThreadExecutor.getInstance().getExecutor(),UrlContainer.PHOTO_COMMENT_LIST_URL);
    }


    private void doFetchThumbListTask() {
        if (fetchThumbUpListTask != null && fetchThumbUpListTask.getStatus() == AsyncTask.Status.RUNNING) {
            fetchThumbUpListTask.cancel(true);
        }
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("user_id", Preferences.getInstance(this).getUserId());
        params.put("group_id", currentPhotoItem.groupId);
        params.put("photo_id", currentPhotoItem.photoId);

        fetchThumbUpListTask = new HttpPostTask(this, params) {

            private ArrayList<CommentBean> thumbupList;

            @Override
            protected boolean parseResponse(Context context, String response) {
                try {
                    JSONObject json = new JSONObject(response);
                    int status = json.getInt("status");
                    if (status == 200) {
                        LogHelper.d(TAG, " fetchThumbUpListTask parseResponse status ok");
                        JSONObject info = json.getJSONObject("data");
                        thumbupList = new ArrayList<CommentBean>();
                        JSONArray commentArray = info.getJSONArray("thumbups");
                        if (commentArray != null && commentArray.length() > 0) {
                            int len = commentArray.length();
                            for (int k = 0; k < len; k++) {
                                JSONObject obj = commentArray.getJSONObject(k);
                                CommentBean bean = new CommentBean();
                                bean.avatarUrl = obj.getString("avatar");
                                bean.nickname = obj.getString("nickname");
                                bean.userId = obj.getString("user_id");
                                thumbupList.add(bean);
                            }
                        }
                        return true;
                    }
                } catch (Exception e) {
                    LogHelper.d(TAG, " fetchThumbUpListTask parseResponse error :" + e);
                }
                return false;
            }

            @Override
            protected void onPostFail(Context context) {
                super.onPostFail(context);
//                Toast.makeText(getApplicationContext(), R.string.fetch_photo_like_fail, Toast.LENGTH_SHORT).show();
            }

            @Override
            protected void onPostSuccess(Context context) {
                super.onPostSuccess(context);
                if(thumbupList.size()>0){
                    photoThumbupText.setText("("+String.valueOf(thumbupList.size())+")");
                    thumbAvatarsLayout.setVisibility(View.VISIBLE);
                    thumbArrowImg.setImageResource(R.drawable.arrow_up);
                    thumbAvatarsLayout.removeAllViews();
                    for(CommentBean bean : thumbupList){
                        RoundedImageView avatar = new RoundedImageView(context);
                        avatar.setBorderWidth((float)DeviceUtils.dip2px(context, 1));
                        avatar.setBorderColor(Color.parseColor("#F7F7F7"));
                        avatar.setCornerRadius(DeviceUtils.dip2px(context, 5));
                        thumbAvatarsLayout.addView(avatar);
                        PhotoLoader.getInstance(context).displayImage(bean.avatarUrl, avatar,PhotoLoader.getUserAvatarOptions());
                        ViewGroup.LayoutParams params = avatar.getLayoutParams();
                        params.width = DeviceUtils.dip2px(context,40);
                        params.height = DeviceUtils.dip2px(context,40);
                        avatar.setLayoutParams(params);
                        avatar.setPadding(DeviceUtils.dip2px(context, 6),0,DeviceUtils.dip2px(context, 6),DeviceUtils.dip2px(context, 12));
                    }
                }
            }

        };
        fetchThumbUpListTask.executeOnExecutor(ThreadExecutor.getInstance().getExecutor(), UrlContainer.PHOTO_LIKE_LIST_URL);
    }

    private String processingThumbPhotoId;

    private void doPhotoThumbUpTask() {
        if(currentPhotoItem.thumbUp){
            Toast.makeText(this,R.string.already_thumb_up,Toast.LENGTH_SHORT).show();
            return;
        }
        if(currentPhotoItem.photoId.equals(processingThumbPhotoId)){
            return;
        }
        if (submitThumbUpTask != null && submitThumbUpTask.getStatus() == AsyncTask.Status.RUNNING) {
            submitThumbUpTask.cancel(true);
        }
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("user_id", Preferences.getInstance(this).getUserId());
        params.put("group_id", currentPhotoItem.groupId);
        params.put("photo_id", currentPhotoItem.photoId);

        processingThumbPhotoId = currentPhotoItem.photoId;

        submitThumbUpTask = new HttpPostTask(this, params) {
            @Override
            protected boolean parseResponse(Context context, String response) {
                try {
                    JSONObject json = new JSONObject(response);
                    int status = json.getInt("status");
                    if (status == 200) {
                        LogHelper.d(TAG, " submitThumbUpTask parseResponse status ok");
                        return true;
                    }
                } catch (Exception e) {
                    LogHelper.d(TAG, " submitThumbUpTask parseResponse error :" + e);
                }
                return false;
            }

            @Override
            protected void onPostFail(Context context) {
                super.onPostFail(context);
                processingThumbPhotoId = null;
                Toast.makeText(getApplicationContext(), R.string.photo_like_fail, Toast.LENGTH_SHORT).show();
            }

            @Override
            protected void onPostSuccess(Context context) {
                super.onPostSuccess(context);
                photoThumbupText.setText("("+String.valueOf(currentPhotoItem.commentNum+1)+")");
                if(processingThumbPhotoId!=null && currentPhotoItem!=null && processingThumbPhotoId.equals(currentPhotoItem.photoId)){
                    currentPhotoItem.thumbUp = true;
                }
                processingThumbPhotoId = null;
                doFetchThumbListTask();
            }

        };
        submitThumbUpTask.executeOnExecutor(ThreadExecutor.getInstance().getExecutor(), UrlContainer.PHOTO_LIKE_URL);
    }

    private void doPhotoCommentTask(String comment) {
        if(TextUtils.isEmpty(comment)){
            return;
        }
        if (submitCommentTask != null && submitCommentTask.getStatus() == AsyncTask.Status.RUNNING) {
            submitCommentTask.cancel(true);
        }
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("user_id", Preferences.getInstance(this).getUserId());
        params.put("group_id", currentPhotoItem.groupId);
        params.put("photo_id", currentPhotoItem.photoId);
        params.put("comment", comment);
        submitCommentTask = new HttpPostTask(this, params) {
            @Override
            protected boolean parseResponse(Context context, String response) {
                try {
                    JSONObject json = new JSONObject(response);
                    int status = json.getInt("status");
                    if (status == 200) {
                        LogHelper.d(TAG, " submitCommentTask parseResponse status ok");
                        return true;
                    }
                } catch (Exception e) {
                    LogHelper.d(TAG, " submitCommentTask parseResponse error :" + e);
                }
                return false;
            }

            @Override
            protected void onPostFail(Context context) {
                super.onPostFail(context);
                Toast.makeText(getApplicationContext(), R.string.photo_comment_fail, Toast.LENGTH_SHORT).show();
            }

            @Override
            protected void onPostSuccess(Context context) {
                super.onPostSuccess(context);
                photoCommentText.setText("("+String.valueOf(currentPhotoItem.commentNum+1)+")");
                doFetchCommentListTask();
            }

        };
        submitCommentTask.executeOnExecutor(ThreadExecutor.getInstance().getExecutor(),UrlContainer.PHOTO_COMMENT_URL);
    }

    @Override
    public void onResult(String transaction,int code) {
        switch (code){
            case BaseResp.ErrCode.ERR_OK:
                jumpWhenPaid();
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
            case BaseResp.ErrCode.ERR_COMM:
            case BaseResp.ErrCode.ERR_SENT_FAILED:
            case BaseResp.ErrCode.ERR_UNSUPPORT:
                Toast.makeText(this,R.string.wx_pay_check,Toast.LENGTH_SHORT).show();
                doCheckOrder(transaction);
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                break;
        }
    }

    private void jumpWhenPaid(){
        Intent intent = new Intent(this, PaidPhotoActivity.class);
        intent.putExtra("photo_item",currentPhotoItem);
        startActivity(intent);
    }

}
