package com.itant.shiwushu.ui.menu.sub;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.AppCompatImageView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.View;
import android.widget.FrameLayout;

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.library.recyclerview.CommonAdapter;
import com.itant.library.recyclerview.base.ViewHolder;
import com.itant.shiwushu.R;
import com.itant.shiwushu.base.LAFBaseFragment;
import com.itant.shiwushu.bean.City;
import com.itant.shiwushu.bean.LostFound;
import com.itant.shiwushu.constant.ServerHost;
import com.itant.shiwushu.manager.ToastManager;
import com.itant.shiwushu.manager.UserManager;
import com.itant.shiwushu.tool.ActivityTool;
import com.itant.shiwushu.tool.ColorTool;
import com.itant.shiwushu.tool.TimeTool;
import com.itant.shiwushu.ui.detail.PostDetailActivity;
import com.itant.shiwushu.widget.ColorSwipeRefreshLayout;
import com.itant.shiwushu.widget.SpacesItemDecoration;
import com.itant.shiwushu.widget.bottomlistener.OnRcvScrollListener;

import java.util.ArrayList;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;

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

public class PostFragment extends LAFBaseFragment implements PostContract.View, SwipeRefreshLayout.OnRefreshListener {
    private ColorSwipeRefreshLayout swipe_refresh_layout;

    private RecyclerView rv_post;
    private List<LostFound> postList;
    private CommonAdapter<LostFound> mAdapter;
    private int page;

    private int cityId = City.CITY_ALL;
    private int postType;
    private int lostType;
    private String keywords;
    public static final String KEY_KEYWORDS = "keywords";
    private PostPresenter presenter;

    private int mManColor;
    private int mGoodsColor;
    private int mPetsColor;

    private String userId;

    @Override
    public int getLayoutId() {
        return R.layout.fragment_post;
    }

    @Override
    public void initViews(View view) {
        mManColor = Color.parseColor(ColorTool.getColorHexString(activity, R.color.red_2));
        mGoodsColor = Color.parseColor(ColorTool.getColorHexString(activity, R.color.green_search_bg));
        mPetsColor = Color.parseColor(ColorTool.getColorHexString(activity, R.color.blue_light));

        Bundle bundle = getArguments();
        if (bundle != null) {
            cityId = bundle.getInt(City.KEY_CITY, City.CITY_ALL);
            keywords = bundle.getString(KEY_KEYWORDS, "");
            postType = bundle.getInt(LostFound.KEY_POST_TYPE, LostFound.POST_TYPE_LOST);
            lostType = bundle.getInt(LostFound.KEY_LOST_TYPE, LostFound.LOST_TYPE_ALL);
        }

        userId = UserManager.getInstance().getUser().getUserId();

        swipe_refresh_layout = view.findViewById(R.id.swipe_refresh_layout);

        postList = new ArrayList<>();
        rv_post = view.findViewById(R.id.rv_post);
        final LinearLayoutManager layoutManager = new LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false);
        rv_post.setLayoutManager(layoutManager);
        // 添加均等分割线，必须要添加LayoutManager之后才能起作用
        int dividerWidth = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, getResources().getDisplayMetrics());
        SpacesItemDecoration decoration = new SpacesItemDecoration(dividerWidth);
        rv_post.addItemDecoration(decoration);

        rv_post.addOnScrollListener(new OnRcvScrollListener() {
            @Override
            public void onBottom() {
                super.onBottom();
                // 如果到底部了，而且不是正在加载状态，就变为正在加载状态，并及时去加载数据
                if (!swipe_refresh_layout.isRefreshing()) {
                    // 加载更多
                    page++;
                    swipe_refresh_layout.setRefreshing(true);
                    presenter.getPost(cityId, postType, lostType, keywords, page);
                }
            }
        });

        mAdapter = new CommonAdapter<LostFound>(activity, R.layout.item_post, postList) {
            @Override
            protected void convert(ViewHolder holder, final LostFound lostFound, int position) {
                onPostLoad(holder, lostFound, position);
            }
        };

        rv_post.setAdapter(mAdapter);

        presenter = new PostPresenter(this);
        swipe_refresh_layout.setRefreshing(true);
        presenter.getPost(cityId, postType, lostType, keywords, page);
        swipe_refresh_layout.setOnRefreshListener(this);
    }

    private void onPostLoad(ViewHolder holder, final LostFound lostFound, int position) {
        // 点击进入详情
        holder.setOnClickListener(R.id.cv_post, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent detailIntent = new Intent(activity, PostDetailActivity.class);
                detailIntent.putExtra(PostDetailActivity.KEY_DETAIL_DATA, lostFound);
                ActivityTool.startActivity(activity, detailIntent);
            }
        });

        holder.setOnLongClickListener(R.id.cv_post, new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                boolean showDelete = false;
                if (TextUtils.equals("964161472@qq.com", userId)) {
                    showDelete = true;
                }

                if (lostType == LostFound.LOST_TYPE_PUBLISH) {
                    showDelete = true;
                }

                if (showDelete) {
                    // 退出当前账号
                    AlertDialog dialog = new AlertDialog.Builder(activity)
                    .setMessage("是否删除这条启事？")//设置对话框的内容
                    //设置对话框的按钮
                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    })
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            // 执行删除操作
                            presenter.deletePost(lostFound.getLostFoundId(), lostFound.getAuthorId());
                        }
                    }).create();
                    dialog.show();
                }

                return false;
            }
        });

        // 昵称
        holder.setText(R.id.tv_nickname, lostFound.getAuthorName());
        // 日期
        holder.setText(R.id.tv_date, TimeTool.getTimeFromMillis(lostFound.getPublishTimeMillis()));
        // 是否VIP
        holder.setVisible(R.id.tv_vip_flag, lostFound.isAuthorVip());
        // 悬赏
        if (lostFound.getMoney() > 0) {
            holder.setText(R.id.tv_money, "¥ " + lostFound.getMoney());
            holder.setVisible(R.id.tv_money, true);
        } else {
            holder.setText(R.id.tv_money, "");
            holder.setVisible(R.id.tv_money, false);
        }

        String postTag = "";
        if (postType == LostFound.POST_TYPE_LOST) {
            holder.setVisible(R.id.tv_type, true);
            switch (lostFound.getLostType()) {
                case LostFound.LOST_TYPE_MAN:
                    postTag = "【寻人】";
                    holder.setTextColor(R.id.tv_type, mManColor);
                    break;
                case LostFound.LOST_TYPE_GOODS:
                    postTag = "【寻物】";
                    holder.setTextColor(R.id.tv_type, mGoodsColor);
                    break;
                case LostFound.LOST_TYPE_PETS:
                    postTag = "【寻宠】";
                    holder.setTextColor(R.id.tv_type, mPetsColor);
                    break;
                default:
                    holder.setTextColor(R.id.tv_type, R.color.blue_light);
                    holder.setVisible(R.id.tv_type, false);
                    break;
            }
            holder.setText(R.id.tv_type, postTag);
        } else {
            holder.setVisible(R.id.tv_type, false);
        }

        // 内容
        holder.setText(R.id.tv_content, lostFound.getContent());
        // 地址
        holder.setText(R.id.tv_city_lost, lostFound.getCityName());
        // 浏览次数
        holder.setText(R.id.tv_browse_num, String.valueOf(lostFound.getBrowseNum()));

        // 头像
        final CircleImageView authorHead = holder.getView(R.id.iv_head);
        authorHead.setImageResource(R.mipmap.logo);
        if (!TextUtils.isEmpty(lostFound.getAuthorHeadUrl())) {
            String realHeadUrl = lostFound.getAuthorHeadUrl();
            if (!realHeadUrl.startsWith("http")) {
                realHeadUrl = ServerHost.URL_BASE + realHeadUrl;
            }
            final String finalRealHeadUrl = realHeadUrl;
            Glide.with(activity)
                    .load(realHeadUrl)
                    .apply(new RequestOptions()
                            .diskCacheStrategy(DiskCacheStrategy.ALL)
                            .placeholder(R.mipmap.logo)
                            .error(R.mipmap.logo)).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) {
                    if (TextUtils.equals(authorHead.getTag().toString(), finalRealHeadUrl)) {
                        authorHead.setImageDrawable(resource);
                    } else {
                        authorHead.setImageResource(R.mipmap.logo);
                    }
                    return false;
                }
            }).into(authorHead);
            authorHead.setTag(R.id.tag_head, realHeadUrl);


        } else {
            // 设置默认图片
            authorHead.setImageResource(R.mipmap.logo);
        }

        // 相关图片
        final AppCompatImageView relatedPhoto = holder.getView(R.id.aciv_related_photo);
        final FrameLayout fl_photo = holder.getView(R.id.fl_photo);
        if (!TextUtils.isEmpty(lostFound.getPhotoUrl())) {
            fl_photo.setVisibility(View.VISIBLE);

            String realPhotoUrl = lostFound.getPhotoUrl();
            if (!realPhotoUrl.startsWith("http")) {
                realPhotoUrl = ServerHost.URL_BASE + realPhotoUrl;
            }

            final String finalRealPhotoUrl = realPhotoUrl;
            Glide.with(activity)
                    .load(realPhotoUrl)
                    .apply(new RequestOptions()
                            .diskCacheStrategy(DiskCacheStrategy.ALL)
                            .placeholder(R.mipmap.logo)
                            .error(R.mipmap.logo)).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) {
                    if (TextUtils.equals(relatedPhoto.getTag().toString(), finalRealPhotoUrl)) {
                        relatedPhoto.setImageDrawable(resource);
                    } else {
                        relatedPhoto.setImageResource(R.mipmap.logo);
                    }
                    return false;
                }
            }).into(relatedPhoto);
            relatedPhoto.setTag(R.id.tag_photo, realPhotoUrl);

        } else {
            fl_photo.setVisibility(View.GONE);
            //relatedPhoto.setVisibility(View.GONE);
        }
    }

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

    @Override
    public void onGetPostSuccess(List<LostFound> lostList) {
        if (lostList != null && lostList.size() > 0) {
            if (page == 0) {
                // 是刷新或者第一次进来
                postList.clear();
                postList.addAll(lostList);
                mAdapter.notifyDataSetChanged();
                ToastManager.getInstance().toastShort("刷新成功");
            } else {
                // 是加载更多的
                int start = postList.size();
                postList.addAll(lostList);
                mAdapter.notifyItemRangeInserted(start, lostList.size());
            }
        } else {
            if (page == 0) {
                postList.clear();
                mAdapter.notifyDataSetChanged();
                ToastManager.getInstance().toastShort("刷新成功");
            } else {
                ToastManager.getInstance().toastShort("没有更多了");
            }
        }
    }

    @Override
    public void onGetPostFailed(String message) {
        ToastManager.getInstance().toastShort(message);
        if (page > 0) {
            page--;
        }
    }

    @Override
    public void onDeleteSuccess(String message) {
        ToastManager.getInstance().toastShort(message);
        swipe_refresh_layout.setRefreshing(true);
        presenter.getPost(cityId, postType, lostType, keywords, page);
    }

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

    @Override
    public void onRefresh() {
        page = 0;
        presenter.getPost(cityId, postType, lostType, keywords, page);
    }

    public void onCityIdChanged(int cityId) {
        this.cityId = cityId;
    }
}
