package com.danding.yang800;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.LayoutAnimationController;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.danding.yang800.Adapter.AbstractWheelTextAdapter;
import com.danding.yang800.Adapter.ArrayWheelAdapter;
import com.danding.yang800.Adapter.DetailsAdapter;
import com.danding.yang800.Adapter.RefundAdapter;
import com.danding.yang800.Adapter.RefundImagePickerAdapter;
import com.danding.yang800.Entity.DetailsInfo;
import com.danding.yang800.Entity.ImageItem;
import com.danding.yang800.Entity.RefundInfo;
import com.danding.yang800.General.GlideImageLoader;
import com.danding.yang800.General.ImagePicker;
import com.danding.yang800.General.Yang800App;
import com.danding.yang800.Presenter.RefundActivityPresenter;
import com.danding.yang800.Util.BitmapUtil;
import com.danding.yang800.Util.LogUtil;
import com.danding.yang800.Util.StatusColorUtil;
import com.danding.yang800.Util.ToastUtil;
import com.danding.yang800.View.CropImageView;
import com.danding.yang800.View.NetworkProgressDialog;
import com.danding.yang800.View.WheelView;
import com.danding.yang800.listener.OnWheelChangedListener;
import com.yanzhenjie.sofia.Sofia;

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

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class RefundActivity extends BaseActivity implements View.OnClickListener,
        OnWheelChangedListener, RefundImagePickerAdapter.OnRecyclerViewItemClickListener {
    private PopupWindow popupWindow;
    private int maxImgCount = 3;               //允许选择图片最大数
    private ArrayList<ImageItem> selImageList; //当前选择的所有图片
    public static final int IMAGE_ITEM_ADD = -1;
    private RefundImagePickerAdapter adapter;
    public static final int REQUEST_CODE_SELECT = 100;
    public static final int REQUEST_CODE_PREVIEW = 101;
    @BindView(R.id.refund_listLayout)
    LinearLayout refund_listLayout;
    @BindView(R.id.refund_listIv)
    ImageView refund_listIv;
    @BindView(R.id.refund_list)
    ListView refund_list;
    @BindView(R.id.refund_serverTypeLayout)
    LinearLayout refund_serverTypeLayout;
    @BindView(R.id.refund_serverTypeTV)
    TextView refund_serverTypeTV;
    @BindView(R.id.refund_serverTypIv)
    ImageView refund_serverTypIv;
    @BindView(R.id.refund_backTv)
    TextView refund_backTv;
    @BindView(R.id.refund_saveTv)
    TextView refund_saveTv;
    @BindView(R.id.refund_remarkEdit)
    EditText refund_remarkEdit;
    int showList = 0;
    RefundAdapter shopAdapter;
    private PopupWindow popupWindowRefundType;
    private WheelView bankWindow_Item;
    String server[] = {"仅退款", "退货退款"};
    private String itemType = "";
    private NetworkProgressDialog pd;
    RefundActivityPresenter presenter;
    String packageSn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        int type = StatusColorUtil.StatusBarLightMode(this);
//        if (type > 0) {
//            StatusColorUtil.setStatusBarColor(this, R.color.white);
//            StatusColorUtil.StatusBarLightMode(this, type);
//        }
        setContentView(R.layout.activity_refund);
        Sofia.with(this).statusBarDarkFont().statusBarBackground(ContextCompat.getColor(this, R.color.white));
        ButterKnife.bind(this);
        Intent intent = getIntent();
        packageSn = intent.getStringExtra("packageSn");
        ArrayList<DetailsInfo> list = (ArrayList<DetailsInfo>) intent.getSerializableExtra("adapter");
        presenter = new RefundActivityPresenter(this);
        AbstractWheelTextAdapter.DEFAULT_TEXT_SIZE = 20;
        initImagePicker();
        initWidget();
        shopAdapter = new RefundAdapter(this);
        for (DetailsInfo info :
                list) {
            RefundInfo reInfo = new RefundInfo(info, false);
            shopAdapter.getLists().add(reInfo);
        }
        if (sp.getString("uploadImgUrl", "").equals("")) {
            presenter.getUploadImgUrl();
        }
        refund_list.setAdapter(shopAdapter);

    }

    private void initImagePicker() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new GlideImageLoader());   //设置图片加载器
        imagePicker.setShowCamera(true);                      //显示拍照按钮
        imagePicker.setCrop(true);                            //允许裁剪（单选才有效）
        imagePicker.setSaveRectangle(true);                   //是否按矩形区域保存
        imagePicker.setSelectLimit(maxImgCount);              //选中数量限制
        imagePicker.setStyle(CropImageView.Style.RECTANGLE);  //裁剪框的形状
        imagePicker.setFocusWidth(800);                       //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight(800);                      //裁剪框的高度。单位像素（圆形自动取宽高最小值）
        imagePicker.setOutPutX(1000);                         //保存文件的宽度。单位像素
        imagePicker.setOutPutY(1000);                         //保存文件的高度。单位像素
    }

    private void initWidget() {
        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        selImageList = new ArrayList<>();
        adapter = new RefundImagePickerAdapter(this, selImageList, maxImgCount);
        adapter.setOnItemClickListener(this);
        recyclerView.setLayoutManager(new GridLayoutManager(this, 3));
        recyclerView.setHasFixedSize(true);
        recyclerView.setAdapter(adapter);
    }

    private void showWindow() {
        View contentView = LayoutInflater.from(this).inflate(
                R.layout.layout_popupwindows_camera, null);
        popupWindow = new PopupWindow(contentView, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT, true);
        TextView popupwindows_camera = (TextView) contentView
                .findViewById(R.id.popupwindows_camera);
        popupwindows_camera.setOnClickListener(this);
        TextView popupwindows_picture = (TextView) contentView
                .findViewById(R.id.popupwindows_picture);
        popupwindows_picture.setOnClickListener(this);
        TextView tv_popupwindows_off = (TextView) contentView
                .findViewById(R.id.tv_popupwindows_off);
        tv_popupwindows_off.setOnClickListener(this);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.showAtLocation(contentView, Gravity.BOTTOM, 0, 0);
    }

    private void showWindowRefundType() {
        View contentView = LayoutInflater.from(this).inflate(
                R.layout.popupwindows_bank, null);
        popupWindowRefundType = new PopupWindow(contentView, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT, true);
        popupWindowRefundType.setFocusable(true);
        popupWindowRefundType.setOutsideTouchable(true);
        popupWindowRefundType.setBackgroundDrawable(new BitmapDrawable());
        popupWindowRefundType.showAtLocation(contentView, Gravity.BOTTOM, 0, 0);
        TextView bankWindow_cancelTv = (TextView) contentView.findViewById(R.id.bankWindow_cancelTv);
        bankWindow_cancelTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindowRefundType.dismiss();
                refund_serverTypIv.setImageDrawable(getResources().getDrawable(
                        R.drawable.refunddown));
            }
        });
        TextView bankWindow_sureTv = (TextView) contentView.findViewById(R.id.bankWindow_sureTv);
        bankWindow_sureTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                refund_serverTypeTV.setText(itemType);
                refund_serverTypIv.setImageDrawable(getResources().getDrawable(
                        R.drawable.refunddown));

                popupWindowRefundType.dismiss();
            }
        });
        bankWindow_Item = (WheelView) contentView.findViewById(R.id.bankWindow_Item);
        bankWindow_Item.addChangingListener(this);
        bankWindow_Item.setViewAdapter(new ArrayWheelAdapter<String>(
                RefundActivity.this, server));
//        bankWindow_Item.setVisibleItems(7);
        // mViewCity.setVisibleItems(7);
        // mViewDistrict.setVisibleItems(7);
    }

    @OnClick({R.id.refund_listLayout, R.id.refund_serverTypeLayout, R.id.refund_backTv, R.id.refund_saveTv
    })
    public void onViewClicked(View view) {
        if (!Yang800App.wifiConnect) {
            ToastUtil.show(this, "当前无网络");
            return;
        }
        switch (view.getId()) {
            case R.id.refund_backTv:
                finish();
                break;
            case R.id.refund_listLayout:
                showList++;
                if (showList % 2 == 1) {
                    refund_list.setVisibility(View.GONE);
                    refund_listIv.setImageDrawable(getResources().getDrawable(
                            R.drawable.refunddown));
                } else {
                    refund_list.setVisibility(View.VISIBLE);
                    refund_listIv.setImageDrawable(getResources().getDrawable(
                            R.drawable.refundup));
                }
                break;
            case R.id.refund_serverTypeLayout:
                itemType = "仅退款";
                showWindowRefundType();
                refund_serverTypIv.setImageDrawable(getResources().getDrawable(
                        R.drawable.refundup));
                break;
            case R.id.refund_saveTv:
//                presenter.refund(getJson());
//                LogUtil.d();
                boolean checked = false;
                for (int i = 0; i < shopAdapter.getLists().size(); i++) {
                    if (shopAdapter.getItem(i).isChecked()) {
                        checked = true;
                    }
                }
                if (!checked) {
                    ToastUtil.show(RefundActivity.this, "请选择退货商品");
                    return;
                }

                List<ImageItem> list = adapter.getImages();
                if (list.size()>0) {
                    List<Bitmap> bitList = new ArrayList<>();
                    try {
                        for (int i = 0; i < list.size(); i++) {
                            Bitmap bitmap = BitmapUtil.revitionImageSize(list.get(0).path);
                            bitList.add(bitmap);
                        }
                        presenter.updateImg(bitList, sp.getString("uploadImgUrl", ""), "files");
                        LogUtil.d(sp.getString("uploadImgUrl", "")+"sahdasdasdasd");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }else {
                    if (refund_serverTypeTV.getText().toString().equals("仅退款")){
                        presenter.refund( getJson("1",null));
                    }else {
                        presenter.refund( getJson("2",null));
                    }
                }
                break;

        }
    }

    @Override
    public void onItemClick(View view, int position) {
        switch (position) {
            case IMAGE_ITEM_ADD:
                showWindow();
                break;
            default:
                //打开预览
                Intent intentPreview = new Intent(this, ImagePreviewDelActivity.class);
                intentPreview.putExtra(ImagePicker.EXTRA_IMAGE_ITEMS, (ArrayList<ImageItem>) adapter.getImages());
                intentPreview.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position);
                intentPreview.putExtra(ImagePicker.EXTRA_FROM_ITEMS, true);
                startActivityForResult(intentPreview, REQUEST_CODE_PREVIEW);
                break;

        }
    }

    @Override
    public void onItemClick(int position) {
        selImageList.remove(position);
        adapter.setImages(selImageList);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.popupwindows_camera:
                ImagePicker.getInstance().setSelectLimit(maxImgCount - selImageList.size());
                Intent intent = new Intent(RefundActivity.this, ImageGridActivity.class);
                intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, true); // 是否是直接打开相机
                startActivityForResult(intent, REQUEST_CODE_SELECT);
                popupWindow.dismiss();
                break;
            case R.id.popupwindows_picture:
                //打开选择,本次允许选择的数量
                ImagePicker.getInstance().setSelectLimit(maxImgCount - selImageList.size());
                Intent intent1 = new Intent(RefundActivity.this, ImageGridActivity.class);
                                /* 如果需要进入选择的时候显示已经选中的图片，
                                 * 详情请查看ImagePickerActivity
                                 * */
//                                intent1.putExtra(ImageGridActivity.EXTRAS_IMAGES,images);
                startActivityForResult(intent1, REQUEST_CODE_SELECT);
                popupWindow.dismiss();
                break;
            case R.id.tv_popupwindows_off:
                popupWindow.dismiss();
                break;
        }
    }

    ArrayList<ImageItem> images = null;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            //添加图片返回
            if (data != null && requestCode == REQUEST_CODE_SELECT) {
                images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (images != null) {
                    selImageList.addAll(images);
                    adapter.setImages(selImageList);
                }
            }
        } else if (resultCode == ImagePicker.RESULT_CODE_BACK) {
            //预览图片返回
            if (data != null && requestCode == REQUEST_CODE_PREVIEW) {
                images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_IMAGE_ITEMS);
                if (images != null) {
                    selImageList.clear();
                    selImageList.addAll(images);
                    adapter.setImages(selImageList);
                }
            }
        }
    }

    @Override
    public void onChanged(WheelView wheel, int oldValue, int newValue) {
        int pCurrent = wheel.getCurrentItem();
        itemType = server[pCurrent];

    }

    public void initDialog() {
        if (pd == null) {
            pd = NetworkProgressDialog.createDialog(this);
            if (!pd.isShowing()) {
                pd.show();
            }
        }
    }

    public void dismissDialog() {
        if (pd != null) {
            pd.dismiss();
            pd = null;
            NetworkProgressDialog.clear();
        }
    }

    public JSONObject getJson(String type,String imgInfo[]) {

        JSONObject object = new JSONObject();
        try {
            object.put("packageSn", packageSn);
            object.put("note", refund_remarkEdit.getText().toString().trim());
            object.put("type", type);
            JSONArray jsonarray = new JSONArray();
            for (int i = 0; i < shopAdapter.getLists().size(); i++) {
                if (shopAdapter.getItem(i).isChecked()) {
                    JSONObject jsonObj = new JSONObject();
                    jsonObj.put("itemId", shopAdapter.getLists().get(i).getInfo().getId());
                    jsonObj.put("count", shopAdapter.getLists().get(i).getInfo().getNumber());
                    jsonarray.put(jsonObj);
                }
            }
//            for (int i = 0; i < 1; i++) {
//                JSONObject jsonObj = new JSONObject();//pet对象，json形式
//                jsonObj.put("itemId", );//向pet对象里面添加值
//                jsonObj.put("count", "1");
//
//                // 把每个数据当作一对象添加到数组里
//                jsonarray.put(jsonObj);//向json数组里面添加pet对象
//            }
            object.put("itemList", jsonarray);//向总对象里面添加包含pet的数组
            if (imgInfo!=null) {
                JSONArray jsonarrayImg = new JSONArray();
                for (int i = 0; i < imgInfo.length; i++) {
                    jsonarrayImg.put(i, imgInfo[i]);
                }
                object.put("imgList", jsonarrayImg);
            }
//            JSONArray jsonarrayImg = new JSONArray();
//                jsonarrayImg.put(0, "1111");
//            object.put("imgList", jsonarrayImg);

        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return object;
    }

    public void updataImgInfo(String[] imgList) {
        if (refund_serverTypeTV.getText().toString().equals("仅退款")){
            presenter.refund( getJson("1",imgList));
        }else {
            presenter.refund( getJson("2",imgList));
        }


    }
}
