package com.ycgis.macall.personalcenter.v.activity.applyfo;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.rs.macall.androidx.basemodel.base.BaseViewBindActivity;
import com.rs.macall.androidx.basemodel.callback.CustomClickListener;
import com.rs.macall.androidx.basemodel.utils.StringUtil;
import com.rs.macall.androidx.basemodel.utils.ToastUtil;
import com.rs.macall.androidx.basemodel.utils.TypConversion;
import com.ycgis.macall.personalcenter.R;
import com.ycgis.macall.personalcenter.databinding.ActivityApplyDetailsBinding;
import com.ycgis.macall.personalcenter.m.adapterbean.ApplyAuditBean;
import com.ycgis.macall.personalcenter.m.adapterbean.ApplyBean;
import com.ycgis.macall.personalcenter.m.adapterbean.BaseBean;
import com.ycgis.macall.personalcenter.p.app.RuanseeApplication;
import com.ycgis.macall.personalcenter.p.callback.BaseRequestCallback;
import com.ycgis.macall.personalcenter.p.request.ApiModel;
import com.ycgis.macall.personalcenter.p.request.RetrofitService;
import com.ycgis.macall.personalcenter.v.adapter.ApplyAuditRecordAdapter;

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

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.RequestBody;

public class ApplyDetailsActivity extends BaseViewBindActivity<ActivityApplyDetailsBinding> {
    //2 待审核     3 审核详情
    private int operatingType;
    private String data, applyId;
    private ApplyAuditRecordAdapter adapter;

    @Override
    protected ActivityApplyDetailsBinding getViewBinding() {
        return ActivityApplyDetailsBinding.inflate(getLayoutInflater());
    }

    @Override
    protected boolean isImmersiveStatusBar() {
        return true;
    }

    @Override
    protected void init() {
        viewBinding.titleleft.setOnClickListener(new CustomClickListener() {
            @Override
            public void onSingleClick(View v) {
                finish();
            }
        });
        LinearLayoutManager manager = new LinearLayoutManager(getContext());
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        viewBinding.rvList.setLayoutManager(manager);
    }

    @Override
    protected void readInstanceState(Bundle savedInstanceState) {
        if (savedInstanceState == null) {
            data = getIntent().getStringExtra("data");
            operatingType = getIntent().getIntExtra("operatingType", 1);
            savePageCacheData("data", data);
            savePageCacheData("operatingType", operatingType);
        } else {
            data = savedInstanceState.getString("data");
            operatingType = savedInstanceState.getInt("operatingType");
        }
        if (operatingType == 1) {
            viewBinding.contentTitle.setText("记录详情");
            goneView(viewBinding.llOperation);
        } else if (operatingType == 2) {
            viewBinding.contentTitle.setText("审核申请");
            visibleView(viewBinding.llOperation);
            setViewOnClickListener(viewBinding.btnPass);
            setViewOnClickListener(viewBinding.btnReject);
        } else if (operatingType == 3) {
            viewBinding.contentTitle.setText("记录详情");
            goneView(viewBinding.llOperation);
            goneView(viewBinding.btnRevoke);
        }
    }

    @Override
    protected void start() {
        ApplyBean bean = new Gson().fromJson(data, ApplyBean.class);
        viewBinding.tvType.setText(bean.getTypeStr2());
        viewBinding.tvReasonTitle.setText(bean.getTypeStr2() + "原因：");
        viewBinding.tvApplicant.setText(String.format("%s(%s)", bean.getName(), bean.getCode()));
        viewBinding.tvDeptName.setText(bean.getDeptName());
        viewBinding.tvSelectApp.setText(bean.getSysName());
        viewBinding.tvSelectRole.setText(bean.getRoleName());
        viewBinding.tvUserIdCardNum.setText(bean.getIdCordNum());
        viewBinding.editPhone.setText(bean.getPhone());
        viewBinding.editReason.setText(bean.getApplyReason());
        applyId = bean.getId();
        getAuditRecord(applyId);
        if (bean.getState() == 1) {
            goneView(viewBinding.llOperation);
            if (operatingType != 3) {
                visibleView(viewBinding.btnRevoke);
                setViewOnClickListener(viewBinding.btnRevoke);
            }
        }
    }

    @Override
    protected void bindViewClick(View v) {
        if (v.getId() == R.id.btn_pass) {
            submit(true, "");
        } else if (v.getId() == R.id.btn_reject) {
            showDialog();
        } else if (v.getId() == R.id.btn_revoke) {//申请撤销
            Intent intent = new Intent(getContext(), InitiateApplyForActivity.class);
            intent.putExtra("data", data);
            startActivity(intent);
        }
    }

    /**
     * 不通过为0   通过为 1
     *
     * @param isPass 是否通过
     */
    private void submit(boolean isPass, String opinion) {
        baseShowDialog("正在提交，请稍后...");
        Map<String, String> param = new HashMap<>();
        param.put("applyId", applyId);
        param.put("auditStatus", String.valueOf(isPass ? 1 : 0));
        param.put("opinion", opinion);
        baseShowDialog("正在查询审核记录，请稍后...");
        Map<String, String> headMap = new HashMap<>(1);
        headMap.put("app-yysq-token", RuanseeApplication.getAppCache().getApply_token());
        MediaType mediaType = MediaType.Companion.parse("application/json;charset=utf-8");
        RequestBody stringBody = RequestBody.Companion.create(new Gson().toJson(param), mediaType);
        ApiModel.request(RetrofitService.getBaseInstance().applyPost(ApplyForMainActivity.BASE_URL + "audit/save", headMap, stringBody), new BaseRequestCallback<JsonObject>() {

            @Override
            public void onRequestFailure(String msg) {
                Log.e(TAG, msg);
                baseDismissDialog();
                ToastUtil.centered(getContext(), msg);
            }

            @Override
            public void onRequestSuccess(JsonObject result) {
                Log.w(TAG, result.toString());
                baseDismissDialog();
                //{"msg":"操作成功","code":200}
                try {
                    JSONObject object = new JSONObject(result.toString());
                    ToastUtil.centered(getContext(), TypConversion.getJsonStr(object, "msg"));
                    int code = TypConversion.getJsonInt(object, "code", -1);
                    if (code != 200) {
                        return;
                    }
                    setResult(Activity.RESULT_OK);
                    finish();
                } catch (JSONException e) {
                    e.printStackTrace();
                    ToastUtil.centered(getContext(), "msg");
                }
            }
        });


    }

    private void getErrorList(int type, String msg) {
        List<BaseBean> baseBeans = new ArrayList<>();
        BaseBean baseBean = new BaseBean() {
        };
        baseBean.setBaseType(type);
        baseBean.setBaseMessage(msg);
        baseBeans.add(baseBean);
        initData(baseBeans);
    }

    private void getAuditRecord(String applyId) {
        baseShowDialog("正在查询审核记录，请稍后...");
        Map<String, Object> param = new HashMap<>();
        param.put("pageNum", 1);
        param.put("pageSize", 10);
        param.put("applyId", applyId);
        Map<String, String> headMap = new HashMap<>(1);
        headMap.put("app-yysq-token", RuanseeApplication.getAppCache().getApply_token());
        ApiModel.request(RetrofitService.getBaseInstance().applyGet(ApplyForMainActivity.BASE_URL + "audit/dxlist", headMap, param),
                new BaseRequestCallback<JsonObject>() {
                    @Override
                    public void onRequestFailure(String msg) {
                        Log.e(TAG, msg);
                        baseDismissDialog();
                        ToastUtil.centered(getContext(), msg);
                        getErrorList(-1, msg);
                    }

                    @Override
                    public void onRequestSuccess(JsonObject result) {
                        Log.w(TAG, result.toString());
                        baseDismissDialog();
                        try {
                            JSONObject object = new JSONObject(result.toString());
                            int code = TypConversion.getJsonInt(object, "code", -1);
                            if (code != 200) {
                                getErrorList(-1, TypConversion.getJsonStr(object, "msg"));
                                return;
                            }
                            JSONArray rows = TypConversion.getJSONArray(object, "rows");
                            if (rows == null || rows.length() <= 0) {
                                getErrorList(0, "没有审核记录");
                                return;
                            }
                            Type type = new TypeToken<List<ApplyAuditBean>>() {
                            }.getType();
                            List<ApplyAuditBean> lsit = new Gson().fromJson(rows.toString(), type);
                            if (lsit == null || lsit.isEmpty()) {
                                getErrorList(0, "没有审核记录");
                                return;
                            }
                            List<BaseBean> dataList = new ArrayList<>();
                            for (ApplyAuditBean bean : lsit) {
                                bean.setBaseType(1);
                                dataList.add(bean);
                            }
                            initData(dataList);

                        } catch (JSONException e) {
                            e.printStackTrace();
                            getErrorList(-1, e.getMessage());
                        }
                    }
                });
    }

    private void initData(List<BaseBean> dataList) {
        if (adapter == null) {
            adapter = new ApplyAuditRecordAdapter(getContext(), dataList);
            viewBinding.rvList.setAdapter(adapter);
        } else {
            adapter.upData(dataList);
        }
    }

    private void showDialog() {
        View view = getLayoutInflater().inflate(R.layout.dialog_input, null, false);
        Dialog dialog = new AlertDialog.Builder(getContext())
                .setView(view).create();
        dialog.show();
        TextView tvTitle = dialog.findViewById(R.id.tv_title);
        tvTitle.setText("驳回原因");
        EditText viewById = dialog.findViewById(R.id.edit_input);
        viewById.setHint("请输入驳回原因");
        dialog.findViewById(R.id.btn_submit).setOnClickListener(new CustomClickListener() {
            @Override
            public void onSingleClick(View v) {
                Editable text = viewById.getText();
                if (text == null) {
                    ToastUtil.centered(getContext(), "请输入驳回原因！");
                    return;
                }
                if (StringUtil.isNullOrEmpty(text.toString())) {
                    ToastUtil.centered(getContext(), "请输入驳回原因！");
                    return;
                }
                dialog.dismiss();
                submit(false, text.toString());
            }
        });
    }
}