package com.wd.workoffice.ui.activity.user;

import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.wd.workoffice.R;
import com.wd.workoffice.app.BaseBean;
import com.wd.workoffice.app.WorkToolBarActivity;
import com.wd.workoffice.bean.FlowBean;
import com.wd.workoffice.bean.UserMoneyBean;
import com.wd.workoffice.retrofit.RtfUtils;
import com.wd.workoffice.retrofit.WorkObserver;
import com.wd.workoffice.ui.activity.bat.work.WorkAccountFlowDetailActivity;
import com.wd.workoffice.ui.adapter.WorkFlowAdapter;
import com.wd.workoffice.util.MathUtils;
import com.wd.workoffice.util.PickTimeUtils;
import com.wd.workoffice.util.WorkUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import flexible.xd.android_base.network.rtfhttp.Transformer;
import flexible.xd.android_base.utils.TimeUtils;
import io.reactivex.Observable;
import io.reactivex.disposables.Disposable;

/**
 * 我的 - 财务詳情
 * author : flexible
 * email : lgd19940421@163.com
 * github: https://github.com/FlexibleXd
 **/
public class UserMoneyDetailActivity extends WorkToolBarActivity {
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_dep_price)
    TextView tvDepPrice;
    @BindView(R.id.tv_price_desc)
    TextView tvPriceDesc;
    @BindView(R.id.tv_dep_freeze_price)
    TextView tvDepFreezePrice;
    @BindView(R.id.ll_bottom)
    LinearLayout llBottom;
    @BindView(R.id.tv_month)
    TextView tvMonth;
    @BindView(R.id.ll_month)
    LinearLayout llMonth;
    @BindView(R.id.tv_income)
    TextView tvIncome;
    @BindView(R.id.tv_expenditure)
    TextView tvExpenditure;
    @BindView(R.id.rv_data)
    RecyclerView rvData;
    private Map<String, Object> param;
    int page;
    private List<FlowBean.RecordsBean> clientList;
    private WorkFlowAdapter clientAdapter;
    private UserMoneyBean userMoneyBean;

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        rvData.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
        tvMonth.setText(TimeUtils.getNowString(new SimpleDateFormat("yyyy-MM")));
        param = WorkUtils.pageKey();
        param.put("deptId", getIntent().getStringExtra("id"));
        page = 1;
        param.put("current", page);
        addMonthParam(TimeUtils.getNowString(new SimpleDateFormat("yyyy-MM")));
    }

    private void addMonthParam(String nowString) {
        param.put("searchStartTime", nowString + "-01 00:00:00");
        String nextMonth = (Integer.valueOf(nowString.split("-")[1]) + 1) + "";
        String nextMonthString = Integer.valueOf(nowString.split("-")[0]) + "-" + (nextMonth.length() == 2 ? nextMonth : "0" + nextMonth + "-01 00:00:00");
        param.put("searchEndTime", nextMonthString);
    }

    @Override
    protected void initData() {
        clientList = new ArrayList<>();
        clientAdapter = new WorkFlowAdapter(R.layout.item_work_flow, clientList,1);
        clientAdapter.bindToRecyclerView(rvData);
        clientAdapter.setEmptyView(R.layout.view_empty_content, rvData);
        getAccountData();
    }

    private void getAccountData() {
        Observable<BaseBean> observable;
        switch (getIntent().getStringExtra("type")) {
            case "1":
                observable = RtfUtils.getRtf().depMoney();
                break;
            case "2":
                observable = RtfUtils.getRtf().groupMoney();
                break;
            case "3":
                observable = RtfUtils.getRtf().taxMoney();
                break;
            case "4":
                observable = RtfUtils.getRtf().bankMoney();
                break;
            default:
                observable = RtfUtils.getRtf().depMoney();
                break;
        }
        observable.compose(Transformer.schedule()).subscribe(new WorkObserver<BaseBean>() {
            @Override
            public void doOnSubscribe(Disposable d) {
            }

            @Override
            public void onFail(String errorMsg) {
                hideLoading();
                toast(errorMsg);
            }

            @Override
            public void onSuccess(BaseBean data) {
                hideLoading();
                if (data.getCode() != 0) {
                    toast(data.getMessage());
                    return;
                }
                userMoneyBean = JSON.parseObject(data.getData().toString(), UserMoneyBean.class);
                tvDepPrice.setText(MathUtils.converData(userMoneyBean.getBalance(), 3));
                tvDepFreezePrice.setText(MathUtils.converData(userMoneyBean.getFrozenAmount(), 3));
                tvName.setText(userMoneyBean.getName());
                tvIncome.setText(String.format("收入：¥%s", MathUtils.converData(userMoneyBean.getTotalIncome(), 3)));
                tvExpenditure.setText(String.format("支出：¥%s", MathUtils.converData(userMoneyBean.getTotalExpenditure(), 3)));
                getFlow();
            }
        });
    }

    private void getFlow() {
        param.put("deptId", userMoneyBean.getDeptId());
        RtfUtils.getRtf().getFlow(param).compose(Transformer.schedule()).subscribe(new WorkObserver<BaseBean>() {
            @Override
            public void doOnSubscribe(Disposable d) {
            }

            @Override
            public void onFail(String errorMsg) {
                hideLoading();
                toast(errorMsg);
            }

            @Override
            public void onSuccess(BaseBean data) {
                hideLoading();
                if (data.getCode() != 0) {
                    toast(data.getMessage());
                    return;
                }
                List<FlowBean.RecordsBean> dataList = JSON.parseObject(data.getData().toString(), FlowBean.class).getRecords();
                if (page == 1) {
                    clientList.clear();
                    clientList.addAll(dataList);
                    clientAdapter.notifyDataSetChanged();
                    clientAdapter.loadMoreComplete();
                } else {
                    clientAdapter.loadMoreComplete();
                    clientList.addAll(dataList);
                    clientAdapter.notifyDataSetChanged();
                }
                if (dataList.size() == 0) {
                    clientAdapter.loadMoreEnd();
                } else {
                    page++;
                }
            }
        });
    }


    @Override
    protected void initEvent() {
        clientAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                startActivity(WorkAccountFlowDetailActivity.class,"detail",JSON.toJSONString(clientList.get(position)));
            }
        });
    }


    @Override
    protected int layoutId() {
        return R.layout.activity_user_money_detail;
    }


    @OnClick(R.id.ll_month)
    public void onViewClicked() {
        PickTimeUtils.showPickTwo(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View view) {
                String month = TimeUtils.date2String(date, new SimpleDateFormat("yyyy-MM"));
                tvMonth.setText(month);
                addMonthParam(month);
                page = 1;
                param.put("current", page);
                getFlow();
            }
        },true).show();
    }
}
