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


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
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.utils.LogUtils;
import com.rs.macall.androidx.basemodel.utils.StringUtil;
import com.rs.macall.androidx.basemodel.utils.ToastUtil;
import com.ycgis.macall.personalcenter.R;
import com.ycgis.macall.personalcenter.databinding.ActivityInitiateApplyForBinding;
import com.ycgis.macall.personalcenter.m.adapterbean.ApplyBean;
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 java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * 申请撤销应用权限
 */
public class InitiateApplyForActivity extends BaseViewBindActivity<ActivityInitiateApplyForBinding> {
    /**
     * 弃用
     * 用于缓存选择的用户和角色。
     * key：应用ID
     * value : {"应用名称","角色名"}
     */
//    @Deprecated
//    private Map<String, String[]> selectValue;

    private String[] selectCount;

    private String selectData;
    private String appId;
    private String data;

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

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

    @Override
    protected void init() {
        viewBinding.contentTitle.setText("申请应用");
        viewBinding.titleleft.setOnClickListener(customClickListener);
        viewBinding.btnSubmit.setOnClickListener(customClickListener);
        goneView(viewBinding.llRole);
    }

    @Override
    protected void readInstanceState(Bundle savedInstanceState) {
        if (savedInstanceState == null) {
            data = getIntent().getStringExtra("data");
        }
    }

    @Override
    protected void start() {
        if (StringUtil.hasContent(data)) {
            ApplyBean bean = new Gson().fromJson(data, ApplyBean.class);
            if (bean != null) {
                viewBinding.spSpinner.setText("撤销");
                viewBinding.tvReasonTitle.setText("撤销原因：");
                viewBinding.editReason.setHint("请输入撤销原因：");
                viewBinding.editPhone.setText(bean.getPhone());
                viewBinding.tvSelectApp.setText(String.format("%s(%s)",bean.getSysName(),bean.getRoleName()));
                viewBinding.tvSelectApp.setOnClickListener(null);
                viewBinding.tvSelectJs.setOnClickListener(null);
                appId = bean.getId();
                viewBinding.contentTitle.setText("撤销权限申请");
//                selectValue = new HashMap<>();
//                selectValue.put(appId,new String[]{bean.getSysName(),bean.getRoleName()});
            }
        }else {
            viewBinding.btnSelectApp.setOnClickListener(customClickListener);
            viewBinding.tvSelectJs.setOnClickListener(customClickListener);
        }
    }
    @Override
    protected void bindViewClick(View v) {
        switch (v.getId()) {
            case R.id.titleleft:
                isExit();
                break;
            case R.id.btn_select_app:
                Intent intent = new Intent(getContext(), SelectSystemActivity.class);
                intent.putExtra("operationType", 1);
                if (StringUtil.hasContent(selectData)){
                    intent.putExtra("data", selectData);
                }
                startActivityForResult(intent, 1015);
                break;
            case R.id.btn_submit:
                save();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == 1015) {//选择应用返回
                if (data == null) {
                    ToastUtil.centered(getContext(), "选择应用错误！");
                    return;
                }

               selectCount = data.getStringArrayExtra("selectContent");
                if (selectCount == null||StringUtil.isContainEmpty(selectCount)){
                    ToastUtil.centered(getContext(),"参数错误");
                    return;
                }
                    viewBinding.tvSelectApp.setText(selectCount[1]);

//                selectData = data.getStringExtra("selectData");
//                Type type = new TypeToken<Map<String, String[]>>() {
//                }.getType();
//                try {
//                    Map<String, String[]> selectValues = new Gson().fromJson(selectData, type);
//                    if (selectValues==null){
//                        ToastUtil.centered(getContext(),"Type conversion exception");
//                        return;
//                    }
//                    if (selectValue!=null){
//                        selectValue.clear();
//                    }
//                    selectValue = selectValues;
//                    Set<String> strings = selectValue.keySet();
//                    StringBuilder builder = new StringBuilder();
//                    String sp = "";
//                    for (String key : strings) {
//                        builder.append(sp);
//                        String[] strings1 = selectValue.get(key);
//                        builder.append(strings1[0]);
//                        builder.append("(");
//                        builder.append(strings1[1]);
//                        builder.append(")");
//                        sp = ";";
//                    }
//                    viewBinding.tvSelectApp.setText(builder.toString());
//                }catch (Exception e){
//                    e.printStackTrace();
//                    ToastUtil.centered(getContext(),"错误:"+e.getMessage());
//                }
            }
//            if (requestCode == 1016) {//选择角色返回
//                if (data == null) {
//                    ToastUtil.centered(getContext(), "选择角色错误！");
//                    return;
//                }
//                roleId = data.getStringExtra("roleId");
//                String appName = data.getStringExtra("roleName");
//                viewBinding.tvSelectJs.setText(appName);
//            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void isExit() {
        String reason = getEditText(viewBinding.editReason);
        String selectApp ="",phone="";
        if (StringUtil.isNullOrEmpty(data)){
            selectApp = getTextString(viewBinding.tvSelectApp);
            phone = getEditText(viewBinding.editPhone);
        }
        if (!StringUtil.isNullOrEmptyAll(phone, reason, selectApp)) {
            showNotSaveDialog();
            return;
        }
        finish();
    }

    private void save() {
        String selectApp = getTextString(viewBinding.tvSelectApp);
        if (StringUtil.isNullOrEmpty(selectApp)) {
            ToastUtil.centered(getContext(), "请先选择申请权限！");
            return;
        }
        String phone = getEditText(viewBinding.editPhone);
//        if (StringUtil.isNullOrEmpty(phone)) {
//            ToastUtil.centered(getContext(), "请输入联系电话！");
//            return;
//        }
        String reason = getEditText(viewBinding.editReason);
        if (StringUtil.isNullOrEmpty(reason)) {
            ToastUtil.centered(getContext(), "请输入原因！");
            return;
        }
        baseShowDialog("正在提交请稍后...");
        List<Map<String, Object>> requestData = new ArrayList<>();
//        Set<String> strings = selectValue.keySet();

        Map<String, Object> param = new HashMap<>();

        param.put("roleId", selectCount[0]);
        param.put("roleName", selectCount[1]);

        param.put("contact", phone);
        param.put("reason", reason);
        param.put("opType", getTextString(viewBinding.spSpinner));
//        for (String key : strings) {
//            String[] strings1 = selectValue.get(key);
//            Map<String, Object> param1 = new HashMap<>(param);
//            param1.put("appId", key);
//            param1.put("appName", strings1[0]);
//            param1.put("appRole", strings1[1]);
//            requestData.add(param1);
//        }
        MediaType mediaType = MediaType.Companion.parse("application/json;charset=utf-8");
        RequestBody stringBody = RequestBody.Companion.create(new Gson().toJson(param), mediaType);

        Map<String, String> headMap = new HashMap<>(1);
        headMap.put("app-yysq-token", RuanseeApplication.getAppCache().getApply_token());
        ApiModel.request(RetrofitService.getBaseInstance().applyPost(ApplyForMainActivity.BASE_URL + "apply/save", headMap, stringBody),
                new BaseRequestCallback<JsonObject>() {
                    @Override
                    public void onRequestFailure(String msg) {
                        LogUtils.e(TAG, msg);
                        baseDismissDialog();
                        ToastUtil.centered(getContext(), msg);
                    }

                    @Override
                    public void onRequestSuccess(JsonObject result) {
                        baseDismissDialog();
                        baseDismissDialog();
                        LogUtils.w(TAG, result.toString());
                        JsonElement code = result.get("code");
                        if (code == null) {
                            ToastUtil.centered(getContext(), result.get("msg").toString());
                            return;
                        }
                        String s = code.toString();
                        if ("200".equals(s)) {
                            ToastUtil.centered(getContext(), "操作成功！");
                            finish();
                            return;
                        }
                        ToastUtil.centered(getContext(), result.get("msg").toString());
                    }
                });
    }

    private void showNotSaveDialog() {
        new AlertDialog.Builder(getContext())
                .setTitle("温馨提示")
                .setMessage("您当前页面输入的内容未保存，退出后将清空页面数据，您是否坚持退出？")
                .setNegativeButton("坚持退出", (dialog, which) -> {
                    dialog.dismiss();
                    finish();
                })
                .setPositiveButton("取消", (dialog, which) -> dialog.dismiss())
                .create().show();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            isExit();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }
}