package com.yueniuwang.yueniu.ui.stock.fragment;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import com.yueniuwang.yueniu.Config;
import com.yueniuwang.yueniu.MainActivity;
import com.yueniuwang.yueniu.R;
import com.yueniuwang.yueniu.commen.LazyPtrFragment;
import com.yueniuwang.yueniu.datamanager.TokenManager;
import com.yueniuwang.yueniu.eventmodel.OpChangedEvent;
import com.yueniuwang.yueniu.httpresoponse.AddOpStockResponse;
import com.yueniuwang.yueniu.httpresoponse.NormalResponse;
import com.yueniuwang.yueniu.net.WebService;
import com.yueniuwang.yueniu.httprequest.TokenRequest;
import com.yueniuwang.yueniu.httprequest.UpdataOptionStockRequest;
import com.yueniuwang.yueniu.rxfunction.CompletedAction0;
import com.yueniuwang.yueniu.rxfunction.FlatMapFunc1;
import com.yueniuwang.yueniu.rxfunction.ThrowableAction1;
import com.yueniuwang.yueniu.ui.commen.activity.SearchActivity;
import com.yueniuwang.yueniu.ui.stock.activity.EditOptionStockActivity;
import com.yueniuwang.yueniu.ui.stock.activity.StockStateDetailsActivity;
import com.yueniuwang.yueniu.ui.user.activity.UserLoginActivity;
import com.yueniuwang.yueniu.utils.PackParamsUtils;
import com.yueniuwang.yueniu.utils.ToastUtils;
import com.yueniuwang.yueniu.widget.NetProgressView;
import com.yueniuwang.yueniu.widget.ptrui.PtrClassicFrameLayout;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import java.io.Serializable;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
public class OptionalFragment extends LazyPtrFragment {
public ListView listView;
public PtrClassicFrameLayout ptrLayout;
private NetProgressView netProgressView;
private View contentView;
private TextView rbEdit;
private TextView cancelSort;
private ImageButton ib_search;
private TextView textPrice;
private TextView textPercent;
private View login;
private View addStock;
private OptionalStockAdapter optionalStockAdapter;
private List datas = new ArrayList<>();
private List originDatas = new ArrayList<>();
int priceSortTag = 0;//价格排序
int percentSortTag = 0;//涨点幅排序
private static final int OPTIONAL_FRAG = 1;
private static final String OP_STOCK = "opstock";
private TokenTag tokenTag = TokenTag.DEFAULT;
private enum TokenTag {//在没有token时,从其他界面的登录回到次界面要刷新数据
DEFAULT, NO_TOKEN
}
/**
* 编辑点击事件
*/
private View.OnClickListener EditOnClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
Bundle bundle = new Bundle();
bundle.putSerializable(OP_STOCK, (Serializable) originDatas);
Intent intent = new Intent(getActivity(), EditOptionStockActivity.class);
intent.putExtras(bundle);
startActivityForResult(intent, OPTIONAL_FRAG);
}
};
/**
* 取消排序点击事件
*/
private View.OnClickListener cancelSortOnClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
clearSort();
restoreArrorw();
rbEdit.setVisibility(View.VISIBLE);
cancelSort.setVisibility(View.GONE);
priceSortTag = 0;
percentSortTag = 0;
}
};
/**
* 搜索点击事件
*/
private View.OnClickListener searchOnClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
// clearBackground();
SearchActivity.startSearchActivity(getActivity(), Config.SEARCHFLAG);
}
};
/**
* 降序排列价格
*/
private Comparator descSort = new Comparator() {
@Override
public int compare(AddOpStockResponse.DataBean lhs, AddOpStockResponse.DataBean rhs) {
double price1 = Double.parseDouble(lhs.getPrice());
double price2 = Double.parseDouble(rhs.getPrice());
if (price2 > price1) {
return 1;
} else if (price2 < price1) {
return -1;
} else {
return 0;
}
}
};
/**
* 升序排列价格
*/
private Comparator asccSort = new Comparator() {
@Override
public int compare(AddOpStockResponse.DataBean lhs, AddOpStockResponse.DataBean rhs) {
double price1 = Double.parseDouble(lhs.getPrice());
double price2 = Double.parseDouble(rhs.getPrice());
if (price2 > price1) {
return -1;
} else if (price2 < price1) {
return 1;
} else {
return 0;
}
}
};
/**
* 降序排列跌幅比
*/
private Comparator descPercent = new Comparator() {
@Override
public int compare(AddOpStockResponse.DataBean lhs, AddOpStockResponse.DataBean rhs) {
double percent1 = Double.parseDouble(lhs.getPercent());
double percent2 = Double.parseDouble(rhs.getPercent());
if (percent1 > percent2) {
return -1;
} else if (percent1 < percent2) {
return 1;
} else {
return 0;
}
}
};
/**
* 升序排列跌幅比
*/
private Comparator ascPercent = new Comparator() {
@Override
public int compare(AddOpStockResponse.DataBean lhs, AddOpStockResponse.DataBean rhs) {
double percent1 = Double.parseDouble(lhs.getPercent());
double percent2 = Double.parseDouble(rhs.getPercent());
if (percent1 > percent2) {
return 1;
} else if (percent1 < percent2) {
return -1;
} else {
return 0;
}
}
};
@Override
protected void initLoadData() {
getdata();
}
@Override
protected PtrClassicFrameLayout initPtrLayout() {
return ptrLayout;
}
@Override
protected void startRefresh() {
getdata();
}
@Override
protected NetProgressView getNetProgressView() {
return netProgressView;
}
@Override
protected View getContentView() {
return contentView;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_optional, null);
EventBus.getDefault().register(this);
initView(view);
return view;
}
private void initView(View view) {
contentView = view.findViewById(R.id.content_view);
ptrLayout = (PtrClassicFrameLayout) view.findViewById(R.id.ptr_layout);
netProgressView = (NetProgressView) view.findViewById(R.id.net_progress_view);
textPrice = (TextView) view.findViewById(R.id.switch_price);
textPercent = (TextView) view.findViewById(R.id.switch_percent);
listView = (ListView) view.findViewById(R.id.optional_listView);
login = view.findViewById(R.id.login);
addStock = view.findViewById(R.id.add_stock);
//处理排序开关
view.findViewById(R.id.fl_switch_price).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
restoreArrorw();
percentSortTag = 0;
switch (priceSortTag) {
case 0:
Drawable drawable = getResources().getDrawable(R.drawable.ic_arrow_down_black_18dp);
drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
textPrice.setCompoundDrawables(null, null, drawable, null);
Collections.sort(datas, descSort);
if (optionalStockAdapter != null) {
optionalStockAdapter.notifyDataSetChanged();
}
priceSortTag = 1;
rbEdit.setVisibility(View.GONE);
cancelSort.setVisibility(View.VISIBLE);
break;
case 1:
Drawable drawableup = getResources().getDrawable(R.drawable.ic_arrow_up_black_18dp);
drawableup.setBounds(0, 0, drawableup.getMinimumWidth(), drawableup.getMinimumHeight());
textPrice.setCompoundDrawables(null, null, drawableup, null);
Collections.sort(datas, asccSort);
if (optionalStockAdapter != null) {
optionalStockAdapter.notifyDataSetChanged();
}
priceSortTag = 2;
break;
case 2:
Drawable drawabledown = getResources().getDrawable(R.drawable.ic_arrow_bottom_right_black_18dp);
drawabledown.setBounds(0, 0, drawabledown.getMinimumWidth(), drawabledown.getMinimumHeight());
textPrice.setCompoundDrawables(null, null, drawabledown, null);
datas.clear();
for (AddOpStockResponse.DataBean bean : originDatas) {
datas.add(bean);
}
if (optionalStockAdapter != null) {
optionalStockAdapter.notifyDataSetChanged();
}
priceSortTag = 0;
rbEdit.setVisibility(View.VISIBLE);
cancelSort.setVisibility(View.GONE);
break;
default:
break;
}
}
});
view.findViewById(R.id.fl_switch_percent).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
restoreArrorw();
priceSortTag = 0;
switch (percentSortTag) {
case 0:
Drawable drawable = getResources().getDrawable(R.drawable.ic_arrow_down_black_18dp);
drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
textPercent.setCompoundDrawables(null, null, drawable, null);
Collections.sort(datas, descPercent);
if (optionalStockAdapter != null) {
optionalStockAdapter.notifyDataSetChanged();
}
percentSortTag = 1;
rbEdit.setVisibility(View.GONE);
cancelSort.setVisibility(View.VISIBLE);
break;
case 1:
Drawable drawableup = getResources().getDrawable(R.drawable.ic_arrow_up_black_18dp);
drawableup.setBounds(0, 0, drawableup.getMinimumWidth(), drawableup.getMinimumHeight());
textPercent.setCompoundDrawables(null, null, drawableup, null);
Collections.sort(datas, ascPercent);
if (optionalStockAdapter != null) {
optionalStockAdapter.notifyDataSetChanged();
}
percentSortTag = 2;
break;
case 2:
Drawable drawabledown = getResources().getDrawable(R.drawable.ic_arrow_bottom_right_black_18dp);
drawabledown.setBounds(0, 0, drawabledown.getMinimumWidth(), drawabledown.getMinimumHeight());
textPercent.setCompoundDrawables(null, null, drawabledown, null);
datas.clear();
for (AddOpStockResponse.DataBean bean : originDatas) {
datas.add(bean);
}
if (optionalStockAdapter != null) {
optionalStockAdapter.notifyDataSetChanged();
}
percentSortTag = 0;
rbEdit.setVisibility(View.VISIBLE);
cancelSort.setVisibility(View.GONE);
break;
default:
break;
}
}
});
//点击添加自选股/
addStock.setOnClickListener(searchOnClickListener);
//点击登陆
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
clearBackground();
startActivity(new Intent(getActivity(), UserLoginActivity.class));
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView> parent, View view, int position, long id) {
AddOpStockResponse.DataBean dataBean = datas.get(position);
if (dataBean != null) {
//跳转详情
StockStateDetailsActivity.startStockDetailActivity(getContext(), dataBean.getStockcode(), dataBean.getStockname());
}
}
});
}
/**
* 每次进入检查token,处理退出登录并清空内存数据
*/
@Override
public void onResume() {
super.onResume();
checkToken();
}
@Subscribe(sticky = true)
public void onEvent(OpChangedEvent opChangedEvent) {
refreshDatas();
}
@Override
public void onDestroyView() {
EventBus.getDefault().unregister(this);
super.onDestroyView();
}
/**
* 返回时判断刷新数据
*/
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == OPTIONAL_FRAG) {
String sortStock = data.getStringExtra("sortStock");
if (!TextUtils.isEmpty(sortStock)) {
sortStockDatas(sortStock);
} else {
refreshDatas();
}
}
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//获取父fragment获取三个点击事件
MainActivity mainActivity = (MainActivity) getActivity();
Fragment opsFragment = mainActivity.getSupportFragmentManager().findFragmentByTag("R.id.navi_message");
if (opsFragment != null && opsFragment instanceof OptionalStockFragment) {
rbEdit = ((OptionalStockFragment) opsFragment).getRbEdit();
cancelSort = ((OptionalStockFragment) opsFragment).getCancelSort();
ib_search = ((OptionalStockFragment) opsFragment).getIb_search();
rbEdit.setOnClickListener(EditOnClickListener);
cancelSort.setOnClickListener(cancelSortOnClickListener);
ib_search.setOnClickListener(searchOnClickListener);
}
}
private void getdata() {
if (TextUtils.isEmpty(TokenManager.getInstance().getToken())) {
dealNoToken();
} else {
WebService.getInstance()
.retrofitService
.QueryOp(PackParamsUtils.getHash(new TokenRequest(TokenManager.getInstance().getToken())))
// .QueryOp(TokenManager.getInstance().getToken())
.flatMap(new FlatMapFunc1>())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1>() {
@Override
public void call(List dataBeen) {
clearBackground();
if (dataBeen == null || dataBeen.size() == 0) {
if (addStock.getVisibility() != View.VISIBLE) {
addStock.setVisibility(View.VISIBLE);
}
if (optionalStockAdapter != null) {
datas.clear();
originDatas.clear();
optionalStockAdapter.notifyDataSetChanged();
}
return;
}
datas.clear();
datas = dataBeen;
originDatas.clear();
for (AddOpStockResponse.DataBean bean : dataBeen) {
originDatas.add(bean);
}
optionalStockAdapter = new OptionalStockAdapter();
listView.setAdapter(optionalStockAdapter);
sortAdapter();
}
}, new ThrowableAction1(getActivity(), this), new CompletedAction0(this));
}
}
public class OptionalStockAdapter extends BaseAdapter {
@Override
public int getCount() {
return datas.size();
}
@Override
public Object getItem(int position) {
return datas.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(getActivity()).inflate(R.layout.optional_stock_list_item, null);
holder.marketName = (TextView) convertView.findViewById(R.id.market_name);
holder.marketcode = (TextView) convertView.findViewById(R.id.market_code);
holder.curdot = (TextView) convertView.findViewById(R.id.curdot);
holder.rate = (TextView) convertView.findViewById(R.id.rate);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
if (datas.get(position) != null) {
DecimalFormat df1 = new DecimalFormat("0.00");//格式化小数
holder.marketName.setText(datas.get(position).getStockname());
holder.marketcode.setText(datas.get(position).getStockcode());
if (!TextUtils.isEmpty(datas.get(position).getPrice())) {
holder.curdot.setText(df1.format(Double.valueOf(datas.get(position).getPrice())));
} else {
holder.curdot.setText("0.00");
}
String percent = datas.get(position).getPercent();
DecimalFormat df = new DecimalFormat("0.00%");//格式化百分数
percent = df.format(Double.valueOf(percent));
if (Double.parseDouble(datas.get(position).getPrice()) < 0.001) {
holder.rate.setBackgroundResource(R.drawable.shape_grey_background);
holder.rate.setText("停牌");
} else {
if (percent.contains("-")) {
holder.rate.setBackgroundResource(R.drawable.shape_green_background);
holder.rate.setText(percent);
} else if (percent.startsWith("0.00")) {
holder.rate.setBackgroundResource(R.drawable.shape_grey_background);
holder.rate.setText(percent);
} else {
holder.rate.setBackgroundResource(R.drawable.shape_red_background);
holder.rate.setText("+" + percent);
}
}
}
return convertView;
}
}
/**
* 处理编辑自选股界面回来的数据上传
*
* @param sortStock
*/
private void sortStockDatas(String sortStock) {
if (TextUtils.isEmpty(TokenManager.getInstance().getToken())) {
dealNoToken();
} else {
WebService.getInstance()
.retrofitService
.updateOpStock(PackParamsUtils.getHash(new UpdataOptionStockRequest(TokenManager.getInstance().getToken(), sortStock)))
// .updateOpStock(TokenManager.getInstance().getToken(), sortStock)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1() {
@Override
public void call(NormalResponse dataBean) {
clearBackground();
}
}, new ThrowableAction1(getActivity(), this) {
@Override
public void dealSpecial(Throwable throwable) {
ToastUtils.show(getActivity(), "自选股排序失败");
refreshDatas();
}
}, new CompletedAction0(this) {
@Override
public void dealSpecial() {
refreshDatas();
}
});
}
}
/**
* 根据当前页面已排的顺序,在重新请求数据的时候重新更新顺序
*/
private void sortAdapter() {
if (priceSortTag != 0 && percentSortTag == 0) {
switch (priceSortTag) {
case 1:
Collections.sort(datas, descSort);
if (optionalStockAdapter != null) {
optionalStockAdapter.notifyDataSetChanged();
}
return;
case 2:
Collections.sort(datas, asccSort);
if (optionalStockAdapter != null) {
optionalStockAdapter.notifyDataSetChanged();
}
return;
default:
return;
}
}
if (percentSortTag != 0 && priceSortTag == 0) {
switch (percentSortTag) {
case 1:
Collections.sort(datas, descPercent);
if (optionalStockAdapter != null) {
optionalStockAdapter.notifyDataSetChanged();
}
return;
case 2:
Collections.sort(datas, ascPercent);
if (optionalStockAdapter != null) {
optionalStockAdapter.notifyDataSetChanged();
}
return;
default:
return;
}
}
}
/**
* 刷新数据
*/
private void refreshDatas() {
// @Override
// public void run() {
// ptrLayout.autoRefresh();
// }
// });
getdata();
}
/**
* 清空排序
*/
private void clearSort() {
datas.clear();
for (AddOpStockResponse.DataBean bean : originDatas) {
datas.add(bean);
}
if (optionalStockAdapter != null) {
optionalStockAdapter.notifyDataSetChanged();
}
}
/**
* 复位箭头方向
*/
private void restoreArrorw() {
Drawable drawable = getResources().getDrawable(R.drawable.ic_arrow_bottom_right_black_18dp);
drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
textPrice.setCompoundDrawables(null, null, drawable, null);
Drawable drawabledown = getResources().getDrawable(R.drawable.ic_arrow_bottom_right_black_18dp);
drawabledown.setBounds(0, 0, drawabledown.getMinimumWidth(), drawabledown.getMinimumHeight());
textPercent.setCompoundDrawables(null, null, drawabledown, null);
}
/**
* resume检查是否有token,没有清楚当前界面所有数据
*/
private void checkToken() {
if (TextUtils.isEmpty(TokenManager.getInstance().getToken())) {
clearBackground();
ptrLayout.setEnabled(false);
if (login.getVisibility() != View.VISIBLE) {
login.setVisibility(View.VISIBLE);
}
if (datas != null) {//未登录不显示自选股
datas.clear();
originDatas.clear();
if (optionalStockAdapter == null) {
optionalStockAdapter = new OptionalStockAdapter();
listView.setAdapter(optionalStockAdapter);
} else {
optionalStockAdapter.notifyDataSetChanged();
}
}
finishLoading();
tokenTag = TokenTag.NO_TOKEN;
} else {
if (tokenTag == TokenTag.NO_TOKEN) {
refreshDatas();
tokenTag = TokenTag.DEFAULT;
}
ptrLayout.setEnabled(true);
}
}
/**
* 处理没有Token情况
*/
private void dealNoToken() {
clearBackground();
ptrLayout.setEnabled(false);
if (login.getVisibility() != View.VISIBLE) {
login.setVisibility(View.VISIBLE);
}
if (datas != null) {//未登录不显示自选股
datas.clear();
if (optionalStockAdapter == null) {
optionalStockAdapter = new OptionalStockAdapter();
listView.setAdapter(optionalStockAdapter);
} else {
optionalStockAdapter.notifyDataSetChanged();
}
}
finishLoading();
}
private void clearBackground() {
if (login.getVisibility() != View.GONE) {
login.setVisibility(View.GONE);
}
if (addStock.getVisibility() != View.GONE) {
addStock.setVisibility(View.GONE);
}
}
static class ViewHolder {
TextView marketName;
TextView marketcode;
TextView curdot;
TextView rate;
}
}