package com.wd.workoffice.ui.activity.bat.store;

import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.wd.workoffice.R;
import com.wd.workoffice.app.BaseBean;
import com.wd.workoffice.app.WorkToolBarActivity;
import com.wd.workoffice.bean.FinancialTypeBean;
import com.wd.workoffice.bean.event.AddFinancialNumEvent;
import com.wd.workoffice.retrofit.RtfUtils;
import com.wd.workoffice.retrofit.WorkObserver;
import com.wd.workoffice.ui.adapter.FinancialAddAdapter;
import com.wd.workoffice.util.PickTimeUtils;
import com.wd.workoffice.util.UserKeeper;
import com.wd.workoffice.util.WorkUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

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

import androidx.recyclerview.widget.GridLayoutManager;
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.disposables.Disposable;

/**
 * 财税
 * author : flexible
 * email : lgd19940421@163.com
 * github: https://github.com/FlexibleXd
 **/
public class StoreFinancialAddActivity extends WorkToolBarActivity {

    @BindView(R.id.tv_submit)
    TextView tvSubmit;
    @BindView(R.id.tv_total)
    TextView tvTotal;
    @BindView(R.id.rl_bottom)
    RelativeLayout rlBottom;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.rl_time)
    RelativeLayout rlTime;
    @BindView(R.id.et_remark)
    EditText etRemark;
    @BindView(R.id.rv_data)
    RecyclerView rvData;
    private FinancialAddAdapter dataAdapter;
    private List<FinancialTypeBean> dataList;
    private Map<String, Object> param;

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        rvData.setLayoutManager(new GridLayoutManager(this,2,RecyclerView.VERTICAL,false));
    }

    @Override
    protected void initData() {
        param = WorkUtils.simpleParam();
        dataList = new ArrayList<>();
        dataAdapter = new FinancialAddAdapter(R.layout.item_financial_add, dataList);
        dataAdapter.bindToRecyclerView(rvData);
        dataAdapter.setEmptyView(R.layout.view_empty_content, rvData);
    }

    @Override
    protected void initEvent() {
        getData();
    }

    private void getData() {
        RtfUtils.getRtf().financialType(UserKeeper.getInstance().getUserDepId()).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<FinancialTypeBean> getList = JSON.parseArray(data.getData().toString(), FinancialTypeBean.class);
                dataList.clear();
                dataList.addAll(getList);
                dataAdapter.notifyDataSetChanged();
            }
        });
    }

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

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_history, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.history:
                startActivity(StoreFinancialActivity.class);
                break;
        }
        return super.onOptionsItemSelected(item);
    }


    @OnClick({R.id.tv_submit, R.id.rl_time})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_submit:
                String time = tvTime.getText().toString();
                String remark = etRemark.getText().toString();
                if (TextUtils.isEmpty(time)) {
                    toast("请选择缴费月份");
                    return;
                }
                changeNum();
                param.put("payDate", time);
                param.put("applyRemark", remark);
                param.put("payDept", UserKeeper.getInstance().getUserDepId());
                submit();
                break;
            case R.id.rl_time:
                PickTimeUtils.showPickTwo(this, new OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {
                        tvTime.setText(TimeUtils.date2String(date, new SimpleDateFormat("yyyyMM")));
                    }
                }).show();
                break;
        }
    }

    private void submit() {
        RtfUtils.getRtf().addFinancial(WorkUtils.convertMapToBody(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;
                }
                finish();
                toast("提交成功");
            }
        });
    }

    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe
    public void refresh(AddFinancialNumEvent event) {
        changeNum();
    }

    private void changeNum() {
        Map<Integer, String> num = dataAdapter.getNum();
        int total = 0;
        List<JSONObject> financeTaxItems = new ArrayList<>();
        for (Map.Entry<Integer, String> entry : num.entrySet()) {
            String value = entry.getValue();
            if (!TextUtils.isEmpty(value)) {
                total += Integer.valueOf(value);
                JSONObject data = new JSONObject();
                data.put("taxType", dataList.get(entry.getKey()).getId());
                data.put("amount", value);
                financeTaxItems.add(data);
            }
        }
        param.put("totalMoney", total);
        param.put("financeTaxItems", financeTaxItems);
        tvTotal.setText(total + "");
    }
}
