package com.itant.shiwushu.ui.detail;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.AppCompatImageView;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;
import com.itant.shiwushu.R;
import com.itant.shiwushu.base.BaseSkinActivity;
import com.itant.shiwushu.bean.FavoriteResult;
import com.itant.shiwushu.bean.LostFound;
import com.itant.shiwushu.bean.User;
import com.itant.shiwushu.constant.ServerHost;
import com.itant.shiwushu.manager.ToastManager;
import com.itant.shiwushu.manager.UserManager;
import com.itant.shiwushu.tool.DialogTool;
import com.itant.shiwushu.tool.StringTool;
import com.itant.shiwushu.tool.TimeTool;
import com.itant.shiwushu.tool.UITool;
import com.itant.shiwushu.widget.ColorSwipeRefreshLayout;

import de.hdodenhof.circleimageview.CircleImageView;

/**
 * Created by Jason on 2018/10/12.
 */

public class PostDetailActivity extends BaseSkinActivity implements View.OnClickListener, FavoriteContract.View, SwipeRefreshLayout.OnRefreshListener {
    public static final String KEY_DETAIL_DATA = "detail";
    private LostFound lostFound;
    private TextView tv_browse_num;
    private ImageView iv_favorite;
    private ColorSwipeRefreshLayout srl_detail;

    private static final int FAVORITE_STATUS_NO = 0;
    private static final int FAVORITE_STATUS_YES = 1;
    private static final int FAVORITE_STATUS_NOT_INIT = -1;
    private int favoriteStatus = FAVORITE_STATUS_NOT_INIT;

    private FavoritePresenter presenter;
    private User user;
    private String relatedPhoto;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_post_detail);

        user = UserManager.getInstance().getUser();

        lostFound = (LostFound) getIntent().getSerializableExtra(KEY_DETAIL_DATA);
        if (lostFound != null) {
            initDetail();
        } else {
            ToastManager.getInstance().toastShort("数据异常");
        }
    }

    // 展示详情数据
    private void initDetail() {
        findViewById(R.id.aciv_back).setOnClickListener(this);
        findViewById(R.id.ll_bottom).setOnClickListener(this);
        findViewById(R.id.aciv_report).setOnClickListener(this);

        // 标题
        TextView tv_title = findViewById(R.id.tv_title);
        if (lostFound.getPostType() == LostFound.POST_TYPE_FOUND) {
            tv_title.setText("招领启事");
        } else {
            switch (lostFound.getLostType()) {
                case LostFound.LOST_TYPE_MAN:
                    tv_title.setText("寻人启事");
                    break;

                case LostFound.LOST_TYPE_GOODS:
                    tv_title.setText("寻物启事");
                    break;

                case LostFound.LOST_TYPE_PETS:
                    tv_title.setText("寻宠启事");
                    break;

                default:
                    tv_title.setText("失物启事");
                    break;
            }
        }

        // 头像
        CircleImageView iv_head = findViewById(R.id.iv_head);
        String headUrl = lostFound.getAuthorHeadUrl();
        if (!TextUtils.isEmpty(headUrl)) {
            if (!headUrl.startsWith("http")) {
                headUrl = ServerHost.URL_BASE + headUrl;
            }

            Glide.with(this).load(headUrl).into(iv_head);
        }

        // 昵称
        TextView tv_nickname = findViewById(R.id.tv_nickname);
        tv_nickname.setText(lostFound.getAuthorName());

        // 日期
        TextView tv_date = findViewById(R.id.tv_date);
        tv_date.setText(TimeTool.getTimeFromMillis(lostFound.getPublishTimeMillis()));

        // 是否VIP
        TextView tv_vip_flag = findViewById(R.id.tv_vip_flag);
        if (lostFound.isAuthorVip()) {
            tv_vip_flag.setVisibility(View.VISIBLE);
        } else {
            tv_vip_flag.setVisibility(View.GONE);
        }

        // 悬赏
        LinearLayout ll_money = findViewById(R.id.ll_money);
        TextView tv_money = findViewById(R.id.tv_money);
        if (lostFound.getMoney() > 0) {
            tv_money.setText("¥ " + lostFound.getMoney());
            ll_money.setVisibility(View.VISIBLE);
        } else {
            tv_money.setText("");
            ll_money.setVisibility(View.GONE);
        }

        // 内容
        TextView tv_content = findViewById(R.id.tv_content);
        tv_content.setText(lostFound.getContent());

        // 地址
        TextView tv_city_lost = findViewById(R.id.tv_city_lost);
        tv_city_lost.setText(lostFound.getCityName());

        // 浏览次数
        tv_browse_num = findViewById(R.id.tv_browse_num);
        tv_browse_num.setText("浏览 " + lostFound.getBrowseNum());

        // 是否已收藏
        iv_favorite = findViewById(R.id.iv_favorite);
        iv_favorite.setOnClickListener(this);


        // 相关图片 todo 点击图片放大和保存
        FrameLayout fl_photo = findViewById(R.id.fl_photo);
        final AppCompatImageView aciv_related_photo = findViewById(R.id.aciv_related_photo);
        aciv_related_photo.setOnClickListener(this);
        relatedPhoto = lostFound.getPhotoUrl();
        if (!TextUtils.isEmpty(relatedPhoto)) {
            fl_photo.setVisibility(View.VISIBLE);
            if (!relatedPhoto.startsWith("http")) {
                relatedPhoto = ServerHost.URL_BASE + relatedPhoto;
            }

            Glide.with(this)
                    .load(relatedPhoto)
                    .apply(new RequestOptions()
                            .diskCacheStrategy(DiskCacheStrategy.ALL))
                    .listener(new RequestListener<Drawable>() {
                @Override
                public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                    return false;
                }

                @Override
                public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                    // 铺满屏幕
                    int width = resource.getIntrinsicWidth();
                    int height = resource.getIntrinsicHeight();
                    int fullWidthPadding = (int) (UITool.getScreenWidth(PostDetailActivity.this) -
                                                2 * TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 16, PostDetailActivity.this.getResources().getDisplayMetrics()));
                    int fullHeight = fullWidthPadding * height / width;
                    ViewGroup.LayoutParams layoutParams = aciv_related_photo.getLayoutParams();
                    layoutParams.width = fullWidthPadding;
                    layoutParams.height = fullHeight;
                    aciv_related_photo.setLayoutParams(layoutParams);
                    aciv_related_photo.setImageDrawable(resource);
                    aciv_related_photo.setScaleType(ImageView.ScaleType.FIT_XY);
                    return false;
                }
            }).into(aciv_related_photo);
        } else {
            fl_photo.setVisibility(View.GONE);
        }

        // 获取浏览次数，查看是否已经收藏该帖子
        presenter = new FavoritePresenter(this);
        srl_detail = findViewById(R.id.srl_detail);
        srl_detail.setOnRefreshListener(this);

        presenter.getFavorite(lostFound.getLostFoundId());
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.aciv_back:
                finish();
                break;

            case R.id.iv_favorite:
                if (favoriteStatus == FAVORITE_STATUS_NOT_INIT) {
                    ToastManager.getInstance().toastShort("请下拉刷新后重试");
                } else {
                    // 去收藏或取消
                    presenter.goFavorite(lostFound.getLostFoundId());
                }
                break;

            case R.id.ll_bottom:
                StringTool.copyText(this, lostFound.getPhoneNumber());
                ToastManager.getInstance().toastShort("复制成功");
                break;

            case R.id.aciv_report:
                // 举报
                DialogTool.showFeedbackDialog(this, user.getUserId(), user.getNickName(), lostFound.getAuthorId(), lostFound.getAuthorName());
                break;

            case R.id.aciv_related_photo:
                // 查看大图
                Intent photoIntent = new Intent(this, PhotoActivity.class);
                photoIntent.putExtra(PhotoActivity.KEY_URL, relatedPhoto);
                startActivity(photoIntent);
                break;
        }
    }

    @Override
    public void onRequestComplete() {
        srl_detail.setRefreshing(false);
    }

    @Override
    public void onGetFavoriteSuccess(FavoriteResult result) {
        tv_browse_num.setText("浏览 " + result.getBrowseNum());
        if (result.isFavorite()) {
            favoriteStatus = FAVORITE_STATUS_YES;
            iv_favorite.setImageResource(R.mipmap.favorite_selected);
        } else {
            favoriteStatus = FAVORITE_STATUS_NO;
            iv_favorite.setImageResource(R.mipmap.favorite_normal);
        }
    }

    @Override
    public void onGetFavoriteFailed(String message) {
        ToastManager.getInstance().toastShort(message);
    }

    @Override
    public void goFavoriteSuccess(String message) {
        if (favoriteStatus == FAVORITE_STATUS_NO) {
            ToastManager.getInstance().toastShort("收藏成功");
            favoriteStatus = FAVORITE_STATUS_YES;
            iv_favorite.setImageResource(R.mipmap.favorite_selected);
        } else {
            ToastManager.getInstance().toastShort("取消收藏");
            favoriteStatus = FAVORITE_STATUS_NO;
            iv_favorite.setImageResource(R.mipmap.favorite_normal);
        }
    }

    @Override
    public void goFavoriteFailed(String message) {
        ToastManager.getInstance().toastShort("操作失败");
    }

    @Override
    public void onRefresh() {
        presenter.getFavorite(lostFound.getLostFoundId());
    }
}
