package com.fxy.base;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;

import com.elvishew.xlog.XLog;
import com.jaredrummler.materialspinner.MaterialSpinner;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.fxy.baselibrary.base.BaseActivity;
import com.fxy.baselibrary.language.other.CommSharedUtil;
import com.fxy.BuildConfig;
import com.fxy.R;
import com.fxy.constant.BaseConfig;
import com.fxy.net.MyDialogCallback;
import com.fxy.net.Urls;

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

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * 服务设置
 * @author James.Jiang
 * @Date 2020-01-06
 */
public class ServiceSettingActivity extends BaseActivity {
    private Context mContext = this;
    //客户端服务区选择
    @BindView(R.id.ms_service_address)
    MaterialSpinner serviceAddressSpinner;

    @BindView(R.id.ms_env)
    MaterialSpinner envSpinner;

    @BindView(R.id.ll_env)
    LinearLayout llEnv;

    private Integer envSelectId=0;

    //客户端选择
    @BindView(R.id.ms_client)
    MaterialSpinner clientSpinner;

    private Unbinder unbinder;

    @BindView(R.id.btn_service_test)
    Button btnTest;

    @BindView(R.id.btn_service_save)
    Button btnSave;

    //仓库选中
    private Integer selectId=0;

    //客户端
    private Integer clientSelectId=0;

    private String selectAreaCode="";

    private String selectClientCode = "";

    private String serviceType = "PROD";

    private JSONArray clientArray =  new JSONArray() ;
    // 定义服务地址集合
    private List<Map<String, String>> clientMapList = new ArrayList<>();

    //环境集合
    private List<Map<String, String>> envMapList = new ArrayList<>();

    @Override
    public int getContentViewResId() {
        return R.layout.activity_setting;
    }

    @Override
    public boolean showToolBar() {
        return true;
    }

    @Override
    public boolean isPlayMusic() {
        return true;
    }

    @Override
    public boolean openEventBus() {
        return false;
    }

    @Override
    protected void getBundleExtras(Bundle extras) {

    }
    // 定义服务地址集合
    private List<Map<String, String>> addressMapList = new ArrayList<>();

    private  List<String> envSpinnerList = new ArrayList<String>();
    private  List<String> clientSpinnerList = new ArrayList<String>();
    private  List<String> addressSpinnerList = new ArrayList<String>();
    @Override
    protected void initView() {
        unbinder = ButterKnife.bind(this);

        //正式隐藏
        if (!BuildConfig.DEBUG){
            llEnv.setVisibility(View.GONE);
        }

        setTitleName(getString(R.string.str_setting));
        //不同客户端
        CommSharedUtil commSharedUtil = CommSharedUtil.getInstance(ServiceSettingActivity.this);
        selectAreaCode = commSharedUtil.getString(BaseConfig.AREA_CODE);
        selectClientCode = commSharedUtil.getString(BaseConfig.CLIENT_CODE);
        serviceType =  commSharedUtil.getString(BaseConfig.SERVICE_TYPE,"prod");

        loadClientData();
        initSpinner();
        initEnvSpinner();

        getFmsHost();

    }

    /**
     * 设置客户端类型
     */
    private void loadClientData(){
        try {
            String clientStr = "[{\"name\":\"返修易\",\"code\":\"fxy\"}]";


            JSONArray jsonArray = new JSONArray(clientStr);
            for (int i = 0;i < jsonArray.length(); i++){
                Map<String,String> hostMap = new HashMap<>();
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                hostMap.put("name",jsonObject.getString("name"));
                hostMap.put("code",jsonObject.getString("code"));
                clientMapList.add(hostMap);
                clientSpinnerList.add(jsonObject.getString("name"));
                //selectClientCode
                if (jsonObject.getString("code").equals(selectClientCode)){
                    clientSelectId = i;
                }
            }


            String envStr = "[{\"name\":\"正式环境\",\"code\":\"PROD\"},{\"name\":\"UAT环境\",\"code\":\"UAT\"}," +
                    "{\"name\":\"开发者环境\",\"code\":\"dev\"},{\"name\":\"测试环境\",\"code\":\"test\"}]";
            JSONArray envJsonArray = new JSONArray(envStr);

            
            for (int i = 0;i < envJsonArray.length(); i++){
                Map<String,String> hostMap = new HashMap<>();
                JSONObject jsonObject = envJsonArray.getJSONObject(i);
                hostMap.put("name",jsonObject.getString("name"));
                hostMap.put("code",jsonObject.getString("code"));
                envMapList.add(hostMap);
                envSpinnerList.add(jsonObject.getString("name"));
                //selectClientCode
                if (jsonObject.getString("code").equals(serviceType)){
                    envSelectId = i;
                }
            }
            
            
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    public void getFmsHost(){
        addressMapList = new ArrayList<>();
        addressSpinnerList.clear();
        OkGo.<String>get(Urls.getFmsHostUrl(mContext))
                .params("v", new Date().getTime())
                .execute(new MyDialogCallback(this,false,false) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        try {
                            JSONObject jsonBody = new JSONObject(response.body());
                            JSONObject hostList= jsonBody.getJSONObject(serviceType.toLowerCase());
                            for (Iterator item = hostList.keys();item.hasNext();) {
                                String areaCode = (String) item.next();
                                JSONObject tmpObject = hostList.getJSONObject(areaCode);
                                Map<String,String> hostMap = new HashMap<>();
                                hostMap.put("name",tmpObject.getString("name"));
                                hostMap.put("hostUrl",tmpObject.getString("hostUrl"));
                                hostMap.put("warehouse","[]");
                                hostMap.put("serve",serviceType);
                                hostMap.put("areaCode",areaCode);
                                addressMapList.add(hostMap);
                                addressSpinnerList.add(tmpObject.getString("name"));
                                if (selectAreaCode!=null && selectAreaCode.equals(areaCode)){
                                    selectId = addressMapList.size()-1;
                                }
                            }

                            initAddressSpinner();
                        } catch (Exception e) {
                            e.printStackTrace();
                            XLog.e("获取服务配置错误:",e);
                        }
                    }
                });
    }


    /**
     *  初始化下拉框控件值
     */
    private void initSpinner() {

        clientSpinner.setItems(clientSpinnerList);
        // 设置当前选中值
        clientSpinner.setSelectedIndex(clientSelectId);
        clientSpinner.setOnItemSelectedListener(new MaterialSpinner.OnItemSelectedListener(){
            @Override
            public void onItemSelected(MaterialSpinner view, int position, long id, Object item) {
                clientSelectId = position;
                //初始化默认
                selectId = 0;
                if (clientSelectId==1){
                    getFmsHost();
                }

            }
        });

        
    }
    private void initAddressSpinner() {
        serviceAddressSpinner.setItems(addressSpinnerList);
        // 设置当前选中值
        serviceAddressSpinner.setSelectedIndex(selectId);
        serviceAddressSpinner.setOnItemSelectedListener(new MaterialSpinner.OnItemSelectedListener() {
            @Override
            public void onItemSelected(MaterialSpinner view, int position, long id, Object item) {
                selectId = position;
            }
        });
    }

    //监听环境变化
    private void initEnvSpinner() {
        envSpinner.setItems(envSpinnerList);
        // 设置当前选中值
        envSpinner.setSelectedIndex(envSelectId);
        envSpinner.setOnItemSelectedListener(new MaterialSpinner.OnItemSelectedListener() {
            @Override
            public void onItemSelected(MaterialSpinner view, int position, long id, Object item) {
                envSelectId = position;
                selectId = 0;
                String currentServe = envMapList.get(position).get("code");
                //类型不一致更新
                if (!currentServe.equals(serviceType)){
                    serviceType = currentServe;
                    getFmsHost();
                }
            }
        });
    }


    /**
     * 根据名称获取服务地址
     * @param name
     * @return
     */
    private Map<String,String> getServiceAddress(String name){
        if(addressMapList.size() > 0){
            for (int i = 0; i < addressMapList.size();i++){
                String name1 = addressMapList.get(i).get("name");
                if( name1.equals(name)){
                    return addressMapList.get(i);
                }
            }
        }
        return null;
    }

    /**
     * 绑定按钮事件(测试&保存)
     * @param view
     * @throws Exception
     */
    @OnClick({R.id.btn_service_test,R.id.btn_service_save})
    public void onViewClicked(View view){
        try {
            String serviceName = serviceAddressSpinner.getText().toString();
            Map<String,String> mapService = getServiceAddress(serviceName);

            Map<String,String> mapClient = clientMapList.get(clientSelectId);
            String serviceAddress = mapService.get("hostUrl");
            String warehouse = mapService.get("warehouse");
//            if (mapClient.get("code").equals("dhwms")){
//                if (warehouse.equals("[]")){
//                    showWarningToast(getString(R.string.error_unusable_warehouse));
//                    return;
//                }
//            }
            switch (view.getId()) {
                // 服务测试
                case R.id.btn_service_test:
                    OkGo.<String>get(serviceAddress + Urls.CHECK_SERVICE)
                            .execute(new MyDialogCallback(this, false, false) {
                                @Override
                                public void onSuccess(Response<String> response) {
                                    showSuccessToast("服务连接正常");
                                }

                                @Override
                                public void onError(Response<String> response) {
                                    super.onError(response);
                                    showWarningToast(response.body());
                                }
                            });
                    break;
                // 服务保存
                case R.id.btn_service_save:
                    CommSharedUtil commSharedUtil = CommSharedUtil.getInstance(ServiceSettingActivity.this);
                    commSharedUtil.putString(BaseConfig.SERVICE_ADDRESS, serviceAddress);
                    commSharedUtil.putString(BaseConfig.WAREHOUSE_LIST, warehouse);

                    commSharedUtil.putString(BaseConfig.SERVICE_TYPE, mapService.get("serve"));
                    commSharedUtil.putString(BaseConfig.AREA_CODE, mapService.get("areaCode"));
                    commSharedUtil.putString(BaseConfig.CLIENT_CODE,  mapClient.get("code"));

                    showSuccessToast(getString(R.string.str_save_success));

                    Intent intent = new Intent();
                    setResult(200, intent);//返回值，2 是改返回的标志，也会返回
                    finish();

                    finish();
                    break;
            }
        } catch (Exception e) {

            e.printStackTrace();
        }
    }
    @Override
    protected void onDestroy() {
        unbinder.unbind();
        super.onDestroy();
    }
}
