package com.sheep.gamegroup.view.adapter;

import android.app.Activity;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.mdad.sdk.mdsdk.AdManager;
import com.mdad.sdk.mdsdk.common.AdData;
import com.sheep.gamegroup.model.entity.AdDataSon;
import com.sheep.gamegroup.util.TimeUtil;
import com.sheep.jiuyan.samllsheep.R;
import com.sheep.jiuyan.samllsheep.SheepApp;

import org.afinal.simplecache.ACache;

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

/**
 * Created by hrs on 2018/6/6.
 */

public class AdListAdapter extends android.support.v7.widget.RecyclerView.Adapter<android.support.v7.widget.RecyclerView.ViewHolder> {

    private boolean isSign = false;
    private List<AdDataSon> mList;
    private Context mContext;
    private final int TYPE_APP_LAYOUT = 0;
    private final int TYPE_FOOTER_LAYOUT = 1;//底部加载更多动画样式
    //上拉加载更多状态-默认为0
    private int load_more_status = 0;

    //上拉加载更多
    public static final int PULLUP_LOAD_MORE = 0;
    //正在加载中
    public static final int LOADING_MORE = 1;
    //加载完成
    public static final int LOADING_FINISH = 2;

    public AdListAdapter(Context context, List<AdDataSon> list) {
        this.mContext = context;
        this.mList = new ArrayList<>();
        if (list != null)
            mList.addAll(list);
    }

    public AdListAdapter(Context context, List<AdDataSon> list, boolean isSign) {
        this.mContext = context;
        this.mList = new ArrayList<>();
        if (list != null)
            mList.addAll(list);
        this.isSign = isSign;
    }
    public void setSign(boolean isSign){
        this.isSign = isSign;
    }

    public void setData(List<AdDataSon> list) {
        mList.clear();
        if (list != null)
            mList.addAll(list);
    }

    public void removeData(String id) {
        int pos = -1;
        if (mList != null && mList.size() > 0) {
            for (int i = 0; i < mList.size(); i++) {
                AdDataSon data = mList.get(i);
                if (data.getAdData().getId().equals(id)) {
                    pos = i;
                    break;
                }
            }
            if (pos > -1) {
                mList.remove(pos);
                notifyDataSetChanged();
            }
        }
    }

    public void addData(List<AdDataSon> list) {
        if (list != null)
            mList.addAll(list);
    }

    @Override
    public android.support.v7.widget.RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view;
        switch (viewType) {
            case TYPE_APP_LAYOUT:
                view = LayoutInflater.from(mContext).inflate(R.layout.wall_list_item, parent, false);
//                view = LayoutInflater.from(mContext).inflate(R.layout.wall_list_item, parent, false);
                return new AppViewHolder(view);
            case TYPE_FOOTER_LAYOUT:
                view = new TextView(mContext);
                return new FootViewHolder(view);
        }
        return null;
    }

    @Override
    public void onBindViewHolder(android.support.v7.widget.RecyclerView.ViewHolder holder, final int position) {
        if (holder instanceof FootViewHolder) {
            FootViewHolder footViewHolder = (FootViewHolder) holder;
            footViewHolder.foot_view_item_tv.setText("");
        } else if (holder instanceof AppViewHolder) {
            final AppViewHolder appViewHolder = (AppViewHolder) holder;
            if (mList != null && mList.size() > 0) {
                final AdData data = mList.get(position).getAdData();
                if (data != null) {
                    appViewHolder.mTitleTv.setText(data.getName());
                    String description = data.getDescription();
                    if (TextUtils.isEmpty(description))
                        description = data.getSign_description();
                    if (TextUtils.isEmpty(description))
                        description = "";
                    appViewHolder.mDesTv.setText(description);
                    if (!TextUtils.isEmpty(data.getLogo())) {
                        Glide.with(mContext).load(data.getLogo()).into(appViewHolder.mIconIv);
                    }
                    appViewHolder.mRewardTv.setText("+" + data.getPrice());
                    String size = data.getSize();
                    if (size == null)
                        size = " ";
                    if (!isSign) {
                        setDownloadTvText(appViewHolder, data);
                    } else {
                        String todayTask = data.getDate();
                        if (todayTask != null && todayTask.equals(TimeStamp2Date(System.currentTimeMillis(), "yyyy-MM-dd"))) {
                            setDownloadTvText(appViewHolder, data);
                            appViewHolder.mDownloadTv.setEnabled(true);
                            appViewHolder.mDownloadTv.setBackgroundColor(Color.parseColor("#d12121"));
                        } else {
                            appViewHolder.mDownloadTv.setEnabled(false);
                            appViewHolder.mDownloadTv.setText("时间还没到喔");
                            appViewHolder.mDownloadTv.setBackgroundColor(Color.parseColor("#cccccc"));
                        }
                    }
                    if (!TextUtils.isEmpty(data.getTodayTask())) {
                        appViewHolder.mDateTv.setText(data.getTodayTask());
                        if(TimeUtil.newInstance().big2Today(data.getTodayTask(), TimeUtil.FORMAT_DD_LINE)){
                            appViewHolder.mDateTv.setEnabled(true);
                        }else {
                            appViewHolder.mDateTv.setEnabled(false);
                        }
                        appViewHolder.mDateTv.setVisibility(View.VISIBLE);
                    } else {
                        appViewHolder.mDateTv.setVisibility(View.GONE);
                    }
                    appViewHolder.mDownloadTv.setOnClickListener(new View.OnClickListener() {

                        @Override
                        public void onClick(View view) {
                            /**
                             * 签到任务传1，非签到任务传0
                             */
                            AdManager.getInstance(SheepApp.getInstance()).openOrDownLoadApps((Activity) mContext, data, isSign ? 1 : 0);
                        }
                    });
                }
            }
        }
    }

    private void setDownloadTvText(AppViewHolder appViewHolder, AdData data) {
        if (isAppInstalled(mContext, data.getPackage_name())) {
            appViewHolder.mDownloadTv.setText("继续体验");
        } else {
            String downloadState = ACache.get(SheepApp.getInstance()).getAsString(String.format(Locale.CHINA, "%s%s", AdManager.class.getSimpleName(), data.getId()));
            if (downloadState == null) {
                appViewHolder.mDownloadTv.setText("立即下载");
            } else {
                switch (downloadState) {
                    case "onDownloadStart":
                        appViewHolder.mDownloadTv.setText("正在下载");
                        break;
                    case "onDownloadSuccess":
                        appViewHolder.mDownloadTv.setText("立即安装");
                        break;
                    case "onDownloadFail":
                    default:
                        appViewHolder.mDownloadTv.setText("立即下载");
                        break;
                }
            }
        }
    }

    // 将Unix时间戳转变为日期，如调用TimeStampToDate("1252639886", "yyyy-MM-dd
    // HH:mm:ss")返回值：2009-11-09 11:31:26

    public static String TimeStamp2Date(Long timestamp, String formats) {
        String date = "";
        try {
            date = new java.text.SimpleDateFormat(formats).format(new java.util.Date(timestamp));

        } catch (NumberFormatException e) {

        }
        return date;
    }

    @Override
    public int getItemViewType(int position) {
        // 最后一个item设置为footerView
        if (position + 1 == getItemCount()) {
            return TYPE_FOOTER_LAYOUT;
        } else {
            return TYPE_APP_LAYOUT;
        }
    }

    public static boolean isAppInstalled(Context context, String packageName) {
        if (TextUtils.isEmpty(packageName))
            return false;
        try {
            ApplicationInfo info = context.getPackageManager().getApplicationInfo(packageName,
                    PackageManager.GET_UNINSTALLED_PACKAGES);
            if (info == null) {
                return false;
            } else {
                return true;
            }
        } catch (PackageManager.NameNotFoundException e) {
            return false;
        }
    }

    @Override
    public int getItemCount() {
        if (mList == null) return 1;
        return mList.size() + 1;
    }

    class AppViewHolder extends android.support.v7.widget.RecyclerView.ViewHolder {

        View view;
        TextView mTitleTv;
        TextView mDesTv;
        ImageView mIconIv;
        TextView mSizeIv;
        TextView mRewardTv;
        TextView mDateTv;
        TextView mTagTv;
        TextView mDownloadTv;
        ImageView my_money_item_recharge_amount_iv;

        public AppViewHolder(View itemView) {
            super(itemView);
            view = itemView;

            mTitleTv = (TextView) itemView.findViewById(R.id.tv_title);//标题
            mDesTv = (TextView) itemView.findViewById(R.id.tv_des);//标题
            mRewardTv = (TextView) itemView.findViewById(R.id.tv_reward);//标题
            mSizeIv = (TextView) itemView.findViewById(R.id.tv_size);//标题
            mDateTv = (TextView) itemView.findViewById(R.id.tv_date);//标题
            mTagTv = (TextView) itemView.findViewById(R.id.tv_tag);//标题
            mDownloadTv = (TextView) itemView.findViewById(R.id.tv_download);//标题
            mIconIv = (ImageView) itemView.findViewById(R.id.iv_icon);//标题
            my_money_item_recharge_amount_iv = (ImageView) itemView.findViewById(R.id.my_money_item_recharge_amount_iv);//标题

        }
    }

    /**
     * 底部FootView布局
     */
    public static class FootViewHolder extends android.support.v7.widget.RecyclerView.ViewHolder {
        private TextView foot_view_item_tv;

        public FootViewHolder(View view) {
            super(view);
            foot_view_item_tv = (TextView) view;
        }
    }
}