package com.yutou.jianr_mg.Adapters;

import android.content.Context;
import android.content.Intent;
import androidx.appcompat.widget.PopupMenu;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.yutou.jianr_mg.Data.AppData;
import com.yutou.jianr_mg.Data.TMod;
import com.yutou.jianr_mg.Data.TModtype;
import com.yutou.jianr_mg.Data.ZsShipType;
import com.yutou.jianr_mg.Interfaces.HttpInterface;
import com.yutou.jianr_mg.Network.HttpApi;
import com.yutou.jianr_mg.Network.HttpUtils;
import com.yutou.jianr_mg.R;
import com.yutou.jianr_mg.Tools.Log;
import com.yutou.jianr_mg.Tools.ModUtils;
import com.yutou.jianr_mg.Tools.Utils;
import com.yutou.jianr_mg.views.ModActivity;

import org.angmarch.views.NiceSpinner;
import org.json.JSONObject;

import java.util.List;

import cn.lemon.view.adapter.BaseViewHolder;
import cn.lemon.view.adapter.RecyclerAdapter;
import me.drakeet.materialdialog.MaterialDialog;


/**
 * Created by 58381 on 2018/1/20.
 */

public class ModRecyclerAdapter extends RecyclerAdapter<TMod> {
    private ImageLoader imageLoader;
    private CardRecordHolder holder;

    public ModRecyclerAdapter(Context context) {
        super(context);
        imageLoader = Utils.initImageLoader(getContext());
    }

    @Override
    public BaseViewHolder onCreateBaseViewHolder(ViewGroup parent, int viewType) {
        holder = new CardRecordHolder(parent, R.layout.item_mod_item);
        return holder;
    }

    private class CardRecordHolder extends BaseViewHolder<TMod> {
        private ImageView icon, select;
        private TextView title;
        private PopupMenu menu;
        private List<TModtype> modtypes;
        private List<ZsShipType> shipTypes;
        CardRecordHolder(ViewGroup parent, int layoutId) {
            super(parent, layoutId);
            icon = findViewById(R.id.icon);
            title = findViewById(R.id.title);
            select = findViewById(R.id.select);
            menu = new PopupMenu(getContext(), select);
            if (AppData.user.getPower() == 0)
                menu.inflate(R.menu.mod_menu_notadmin);
            else
                menu.inflate(R.menu.mod_menu);
            if (getContext().getClass().getName().contains("FavoritesActivity"))
                for (int i = 0; i < menu.getMenu().size(); i++) {
                    if (menu.getMenu().getItem(i).getItemId() == R.id.collection) {
                        menu.getMenu().getItem(i).setTitle("取消收藏");
                        break;
                    }
                }
            menu.setOnMenuItemClickListener(item -> {
                if (item.getSubMenu() != null) {
                    menu.show();
                    return true;
                }
                switch (item.getItemId()) {
                    case R.id.audit_ok:
                        setMod("1");
                        break;
                    case R.id.audit_no:
                        setMod("0");
                        break;
                    case R.id.move:
                        setMod("move");
                        break;
                    case R.id.collection:
                        try {
                            String url=HttpApi.MOD_COLLCETION;
                            if (getContext().getClass().getName().contains("FavoritesActivity")){
                                url=HttpApi.MOD_REMOE_COLLCET;
                            }
                            JSONObject json = new JSONObject();
                            json.put("uid", AppData.user.getId());
                            json.put("mid", getData().getId() + "");
                            HttpUtils.post(HttpApi.HOME_URL + url, json, new HttpInterface() {
                                private String state = "取消收藏失败,未知错误";

                                @Override
                                public void httpGetData(String string, int code) {

                                    try {
                                        JSONObject json = new JSONObject(string);
                                        state = json.getString("msg");
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                        Log.e(e, ModRecyclerAdapter.this);
                                    }
                                    AppData.handler.post(() -> Utils.toast(getContext(), state));
                                }

                                @Override
                                public void httpError(Exception e) {

                                }
                            });
                        } catch (Exception e) {
                            e.printStackTrace();
                            Log.e(e, ModRecyclerAdapter.this);
                        }
                        break;
                    case R.id.download:
                        ModUtils.init(getContext()).installMod(getData(), (flag, type) -> AppData.handler.post(() -> Utils.toast(getContext(), "flag:" + flag + " type:" + type)));
                        break;
                    case R.id.admin:
                        break;
                }
                return true;
            });
            select.setOnClickListener(view -> menu.show());
        }

        @Override
        public void setData(TMod data) {
            super.setData(data);
            try {
                imageLoader.displayImage(AppData.appConfig.getDownloadhome() + data.getIcon(), icon);
            }catch (Exception e){
                e.printStackTrace();
            }

            title.setText(data.getTitle());
        }

        @Override
        public void onItemViewClick(TMod data) {
            super.onItemViewClick(data);
            Intent intent = new Intent(getContext(), ModActivity.class);
            intent.putExtra("mod", JSON.toJSONString(data));
            getContext().startActivity(intent);
        }
        private void setMod(String type){
            if(!type.equals("move")){
                setMod(type,-1,-1);
                return;
            }
            HttpUtils.get(HttpApi.HOME_URL + HttpApi.MOD_GET_TYPEINFO, new HttpInterface() {
                @Override
                public void httpGetData(String string, int code) {
                        try{
                            JSONObject json=new JSONObject(string);
                            JSONObject data=json.getJSONObject("data");
                            modtypes=JSON.parseArray(data.get("mType").toString(),TModtype.class);
                            shipTypes=JSON.parseArray(data.get("jType").toString(),ZsShipType.class);
                            AppData.handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    final MaterialDialog dialog=new MaterialDialog(getContext());
                                    dialog.setTitle("移动分区");
                                    View view= LayoutInflater.from(getContext()).inflate(R.layout.item_mod_move,null);
                                    final NiceSpinner modSpinner=view.findViewById(R.id.mod_spinner);
                                    final NiceSpinner jianSprinner=view.findViewById(R.id.jian_spinner);
                                    modSpinner.attachDataSource(TModtype.toStringList(modtypes));
                                    jianSprinner.attachDataSource(ZsShipType.toStringList(shipTypes));
                                    dialog.setContentView(view);
                                    dialog.setPositiveButton("确定", v -> {
                                        setMod("move",modSpinner.getSelectedIndex(),jianSprinner.getSelectedIndex());
                                        dialog.dismiss();
                                    });
                                    dialog.setNegativeButton("取消", v -> dialog.dismiss());
                                    dialog.show();
                                }
                            });
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                }

                @Override
                public void httpError(Exception e) {

                }
            });
        }
        private void setMod(String type,int mType,int jType){
           try{
               JSONObject json=new JSONObject();
               json.put("mid",getData().getId());
               json.put("type",type);
               json.put("mType",mType==-1?"":modtypes.get(mType).getId());
               json.put("jType",jType==-1?"":shipTypes.get(jType).getId());
               HttpUtils.post(HttpApi.HOME_URL + HttpApi.MOD_MOVE, json, new HttpInterface() {
                   @Override
                   public void httpGetData(String string, int code) {
                       try{
                           JSONObject json=new JSONObject(string);
                           final  String data=json.getString("msg");
                           AppData.handler.post(new Runnable() {
                               @Override
                               public void run() {
                                    Utils.toast(getContext(),data);
                               }
                           });
                       }catch (Exception e){
                           e.printStackTrace();
                       }
                   }

                   @Override
                   public void httpError(Exception e) {

                   }
               });
           }catch (Exception e){
               e.printStackTrace();
           }
        }
    }
}
