package com.sipai.jspatrol.Equ;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

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

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.PersistentCookieStore;
import com.loopj.android.http.RequestParams;
import com.sipai.jspatrol.Bean.InfoSel;
import com.sipai.jspatrol.R;

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

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import cn.pedant.SweetAlert.SweetAlertDialog;

public class SelActivity extends AppCompatActivity {
    private String type = "";
    private List<InfoSel> list = new ArrayList<>();
    private InfoSel sel_item;
    private RecyclerView rc_view;
    private SelAdapter adapter;
    private LinearLayoutManager manager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sel);
        init();
        initView();
        intentVisit();
    }

    private void intentVisit() {
        if (type.equals("assetclass")){
            getAssetClass();
        }else if (type.equals("equtypenum")){
            getEquTypeNum();
        }else if (type.equals("equclass")){
            getEquClass();
        }else if (type.equals("equspecification")){
            getEquSpecification();
        }else if (type.equals("equlevel")){
            getEquLevel();
        }
    }

    /**
     * 设备级别
     */
    private void getEquLevel() {
        PersistentCookieStore myCookieStore = new PersistentCookieStore(this);
        RequestParams params = new RequestParams();
        AsyncHttpClient client = new AsyncHttpClient();
        client.setCookieStore(myCookieStore);
        client.post(mServer + "equipment/equipmentLevel/getEquipmentLevelForSelect.do?", params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(String response) {
                super.onSuccess(response);
                list = parseData(response);
                UpdateUI();
            }

            @Override
            public void onStart() {
                super.onStart();
            }

            @Override
            public void onFailure(Throwable error) {
                super.onFailure(error);
                String a = error.toString();
                if(!SelActivity.this.isFinishing()) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            new SweetAlertDialog(SelActivity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("提示")
                                    .setContentText("资产类型列表获取失败请重试！")
                                    .setConfirmText("确认")
                                    .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                        @Override
                                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                                            sweetAlertDialog.dismissWithAnimation();
                                            getEquLevel();
                                        }
                                    }).show();
                        }
                    });
                }
            }

            @Override
            public void onFinish() {
                super.onFinish();
            }

        });
    }

    /**
     * 设备规格
     */
    private void getEquSpecification() {
        PersistentCookieStore myCookieStore = new PersistentCookieStore(this);
        RequestParams params = new RequestParams();
        AsyncHttpClient client = new AsyncHttpClient();
        client.setCookieStore(myCookieStore);
        client.post(mServer + "equipment/equipmentSpecification/getEquipmentSpecificationForSelect.do?", params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(String response) {
                super.onSuccess(response);
                list = parseData(response);
                UpdateUI();
            }

            @Override
            public void onStart() {
                super.onStart();
            }

            @Override
            public void onFailure(Throwable error) {
                super.onFailure(error);
                String a = error.toString();
                if(!SelActivity.this.isFinishing()) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            new SweetAlertDialog(SelActivity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("提示")
                                    .setContentText("资产类型列表获取失败请重试！")
                                    .setConfirmText("确认")
                                    .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                        @Override
                                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                                            sweetAlertDialog.dismissWithAnimation();
                                            getEquSpecification();
                                        }
                                    }).show();
                        }
                    });
                }
            }

            @Override
            public void onFinish() {
                super.onFinish();
            }

        });
    }

    /**
     * 设备类型
     */
    private void getEquClass() {
        PersistentCookieStore myCookieStore = new PersistentCookieStore(this);
        RequestParams params = new RequestParams();
        AsyncHttpClient client = new AsyncHttpClient();
        client.setCookieStore(myCookieStore);
        client.post(mServer + "equipment/equipmentClass/getEquipmentClassForSelect.do?", params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(String response) {
                super.onSuccess(response);
                Log.i("assetClass", "onSuccess: "+response);
                list = parseData(response);
                UpdateUI();
            }

            @Override
            public void onStart() {
                super.onStart();
            }

            @Override
            public void onFailure(Throwable error) {
                super.onFailure(error);
                String a = error.toString();
                if(!SelActivity.this.isFinishing()) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            new SweetAlertDialog(SelActivity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("提示")
                                    .setContentText("资产类型列表获取失败请重试！")
                                    .setConfirmText("确认")
                                    .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                        @Override
                                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                                            sweetAlertDialog.dismissWithAnimation();
                                            getEquClass();
                                        }
                                    }).show();
                        }
                    });
                }
            }

            @Override
            public void onFinish() {
                super.onFinish();
            }

        });
    }

    /**
     * 设备型号
     */
    private void getEquTypeNum() {
        PersistentCookieStore myCookieStore = new PersistentCookieStore(this);
        RequestParams params = new RequestParams();
        AsyncHttpClient client = new AsyncHttpClient();
        client.setCookieStore(myCookieStore);
        client.post(mServer + "equipment/equipmentTypeNumber/getEquipmentTypeNumberForSelect.do?", params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(String response) {
                super.onSuccess(response);
                Log.i("assetClass", "onSuccess: "+response);
                list = parseData(response);
                UpdateUI();
            }

            @Override
            public void onStart() {
                super.onStart();
            }

            @Override
            public void onFailure(Throwable error) {
                super.onFailure(error);
                String a = error.toString();
                if(!SelActivity.this.isFinishing()) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            new SweetAlertDialog(SelActivity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("提示")
                                    .setContentText("资产类型列表获取失败请重试！")
                                    .setConfirmText("确认")
                                    .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                        @Override
                                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                                            sweetAlertDialog.dismissWithAnimation();
                                            getEquTypeNum();
                                        }
                                    }).show();
                        }
                    });
                }
            }

            @Override
            public void onFinish() {
                super.onFinish();
            }

        });
    }

    /**
     * 资产类型
     */
    private void getAssetClass() {
        PersistentCookieStore myCookieStore = new PersistentCookieStore(this);
        RequestParams params = new RequestParams();
//        params.put("search_code", mBizid);
//        params.put("rows", "100");
//        params.put("page", "1");
        AsyncHttpClient client = new AsyncHttpClient();
        client.setCookieStore(myCookieStore);
        client.post(mServer + "equipment/assetClass/getAssetClassForSelect.do?", params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(String response) {
                super.onSuccess(response);
                Log.i("assetClass", "onSuccess: "+response);
                list = parseData(response);
                UpdateUI();
            }

            @Override
            public void onStart() {
                super.onStart();
            }

            @Override
            public void onFailure(Throwable error) {
                super.onFailure(error);
                String a = error.toString();
                if(!SelActivity.this.isFinishing()) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            new SweetAlertDialog(SelActivity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("提示")
                                    .setContentText("资产类型列表获取失败请重试！")
                                    .setConfirmText("确认")
                                    .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                        @Override
                                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                                            sweetAlertDialog.dismissWithAnimation();
                                            getAssetClass();
                                        }
                                    }).show();
                        }
                    });
                }
            }

            @Override
            public void onFinish() {
                super.onFinish();
            }

        });
    }

    private void UpdateUI() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                manager = new LinearLayoutManager(SelActivity.this);
                rc_view.setLayoutManager(manager);
                adapter = new SelAdapter(SelActivity.this, list, new SelAdapter.onRecyclerViewItemClick() {
                    @Override
                    public void onItemClick(View v, int position) {
                        sel_item = list.get(position);
                        Intent intent = new Intent();
                        intent.putExtra("sel",sel_item);
                        setResult(RESULT_OK,intent);
                        finish();
                    }
                });
                rc_view.setAdapter(adapter);
            }
        });
    }

    private List<InfoSel> parseData(String response) {
        List<InfoSel> list = new ArrayList<>();
        try {
            JSONArray array = new JSONArray(response);
            for (int i=0;i<array.length();i++){
                InfoSel item = new InfoSel();
                item.setId(array.getJSONObject(i).opt("id").toString());
                item.setText(array.getJSONObject(i).opt("text").toString());
                list.add(item);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return list;
    }

    private void initView() {
        TextView tv_title = (TextView) findViewById(R.id.moudle_back_title_tv_title);
        if (type.equals("assetclass")) {
            tv_title.setText("资产类型");
        }else if (type.equals("equtypenum")){
            tv_title.setText("设备型号");
        }else if (type.equals("equclass")){
            tv_title.setText("设备类型");
        }else if (type.equals("equspecification")){
            tv_title.setText("设备规格");
        }else if (type.equals("equlevel")){
            tv_title.setText("设备级别");
        }
        ImageView btn_back = (ImageView) findViewById(R.id.moudle_back_title_iv_back);
        btn_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        TextView tv_save = (TextView) findViewById(R.id.moudle_back_title_tv_save);
        tv_save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.putExtra("sel", (Serializable) sel_item);
                setResult(RESULT_OK,intent);
                finish();
            }
        });
        rc_view = findViewById(R.id.moudle_asset_class_sel_rc);
        manager = new LinearLayoutManager(SelActivity.this);
        rc_view.setLayoutManager(manager);
        adapter = new SelAdapter(SelActivity.this, list, new SelAdapter.onRecyclerViewItemClick() {
            @Override
            public void onItemClick(View v, int position) {
                sel_item = list.get(position);
            }
        });
        rc_view.setAdapter(adapter);
    }

    /**
     * 初始化
     */
    private String mServer;
    private String mUsername;
    private String mPassword;
    private String mUserid;
    private String mCaption;
    private String mBizid;
    private String mBizName;

    public void init(){
        SharedPreferences sharedPre=getSharedPreferences("config", MODE_PRIVATE);
        mServer=sharedPre.getString("server", "");
        mUsername=sharedPre.getString("username", "");
        mPassword=sharedPre.getString("password", "");
        mUserid=sharedPre.getString("userid", "");
        mCaption=sharedPre.getString("caption", "");
        mBizid=sharedPre.getString("bizid", "");
        mBizName=sharedPre.getString("bizname", "");
        type = getIntent().getStringExtra("type");
    }
}
