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

import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wd.workoffice.R;
import com.wd.workoffice.app.BaseBean;
import com.wd.workoffice.app.WorkToolBarActivity;
import com.wd.workoffice.bean.FinancailDetailBean;
import com.wd.workoffice.bean.FinancialBean;
import com.wd.workoffice.bean.LogisticDetailBean;
import com.wd.workoffice.bean.event.CheckFinancialEvent;
import com.wd.workoffice.bean.event.CheckLogisticEvent;
import com.wd.workoffice.bean.workEnum.PagePermissionType;
import com.wd.workoffice.retrofit.RtfUtils;
import com.wd.workoffice.retrofit.WorkObserver;
import com.wd.workoffice.ui.adapter.FinancialDetailAdapter;
import com.wd.workoffice.ui.adapter.WorkLogisticDetailAdapter;
import com.wd.workoffice.util.WorkUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import androidx.appcompat.app.AlertDialog;
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 io.reactivex.disposables.Disposable;

/**
 * 财税详情
 * author : flexible
 * email : lgd19940421@163.com
 * github: https://github.com/FlexibleXd
 **/
public class StoreFinancialDetailActivity extends WorkToolBarActivity {
    @BindView(R.id.tv_refuse)
    TextView tvRefuse;
    @BindView(R.id.tv_agree)
    TextView tvAgree;
    @BindView(R.id.ll_bottom)
    LinearLayout llBottom;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.tv_status)
    TextView tvStatus;
    @BindView(R.id.tv_remark)
    TextView tvRemark;
    @BindView(R.id.rv_data)
    RecyclerView rvData;
    private List<FinancailDetailBean> dataList;
    private FinancialDetailAdapter dataAdapter;
    private Map<String, Object> param;

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

    @Override
    protected void initData() {
        FinancialBean.RecordsBean info = JSON.parseObject(getIntent().getStringExtra("info"), FinancialBean.RecordsBean.class);
        getData(info.getId() + "");
        tvTime.setText(info.getPayDate() + "");
        tvRemark.setText(info.getApplyRemark());
        tvStatus.setText(WorkUtils.getFinancialStatus(Integer.valueOf(info.getStatus())));
        if (TextUtils.equals(info.getStatus(), "0") || TextUtils.equals(info.getStatus(), "3")) {
            llBottom.setVisibility(View.VISIBLE);
            changePermission();
        } else {
            llBottom.setVisibility(View.GONE);
        }
        dataList = new ArrayList<>();
        dataAdapter = new FinancialDetailAdapter(R.layout.item_financial_detail, dataList, info.getStatus());
        dataAdapter.bindToRecyclerView(rvData);
        param = new HashMap<>();
        param.put("id", info.getId());
    }

    private void changePermission() {
        boolean hasPermission = WorkUtils.hasPermission(PagePermissionType.FINANCE_DETAIL.getPermission());
        if (!hasPermission) {
            tvRefuse.setVisibility(View.GONE);
            tvAgree.setVisibility(View.GONE);
        }
    }

    private void getData(String id) {
        RtfUtils.getRtf().storeFinancialDetail(id).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<FinancailDetailBean> dataBean = JSON.parseArray(JSON.parseObject(data.getData().toString()).getString("financeTaxItems"), FinancailDetailBean.class);
                dataList.addAll(dataBean);
                dataAdapter.notifyDataSetChanged();
            }
        });
    }

    @Override
    protected void initEvent() {
    }

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


    @OnClick({R.id.tv_refuse, R.id.tv_agree})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_refuse:
                if (!checkAddParam(2)) {
                    return;
                }
                checkDialog(2);
                break;
            case R.id.tv_agree:
                if (!checkAddParam(1)) {
                    return;
                }
                checkDialog(1);
                break;
        }
    }


    private void checkDialog(int status) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View view = LayoutInflater.from(this).inflate(R.layout.view_check, null);
        TextView tvOk = view.findViewById(R.id.tv_ok);
        TextView tvDesc = view.findViewById(R.id.tv_desc);
        tvDesc.setText(status == 1 ? "同意" : "拒绝");
        TextView tvNum = view.findViewById(R.id.tv_num);
        TextView tvCancel = view.findViewById(R.id.tv_cancel);
        EditText etRemark = view.findViewById(R.id.et_content);
        WorkUtils.addNumListener(etRemark, tvNum);
        builder.setView(view);
        AlertDialog addCartDialog = builder.create();
        tvOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (status != 1&&TextUtils.isEmpty(etRemark.getText().toString())) {
                    toast("请填写备注");
                    return;
                }
                check(status, etRemark.getText().toString());
                addCartDialog.dismiss();
            }
        });
        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addCartDialog.dismiss();
            }
        });
        addCartDialog.show();
    }


    private void check(int status, String remark) {
        param.put("status", status);
        param.put("auditRemark", remark);
        RtfUtils.getRtf().storeFinancialCheck(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;
                }
                EventBus.getDefault().post(new CheckFinancialEvent());
                toast("操作成功");
                finish();

            }
        });
    }

    private boolean checkAddParam(int status) {
        Map<Integer, String> errorMap = dataAdapter.getErrorMap();
        Set<Map.Entry<Integer, String>> entries = errorMap.entrySet();
        if (entries.size() == 0 && status == 2) {
            toast("请标记错误并填写错误原因");
            return false;
        }
        List<JSONObject> financeTaxItems = new ArrayList<>();

        for (int i = 0; i < dataList.size(); i++) {
            JSONObject data = new JSONObject();
            if (errorMap.containsKey(i)) {
                data.put("auditRemark", dataList.get(i).getAuditRemark());
                data.put("id", dataList.get(i).getId());
                data.put("status", 2);
                if (TextUtils.isEmpty(dataList.get(i).getAuditRemark())) {
                    toast("请标记错误并填写错误原因");
                    return false;
                }
            } else {
                data.put("auditRemark", dataList.get(i).getAuditRemark());
                data.put("id", dataList.get(i).getId());
                data.put("status", 1);
            }
            financeTaxItems.add(data);
        }
        param.put("financeTaxItems", financeTaxItems);
        return true;
    }

}
