package com.sipai.jspatrol.Fault;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

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

import com.sipai.jspatrol.Bean.EquList;
import com.sipai.jspatrol.Bean.Measuringpoint;
import com.sipai.jspatrol.Bean.ProcessSection;
import com.sipai.jspatrol.R;
import com.sipai.jspatrol.URL.MethodURL;
import com.sipai.jspatrol.utils.OKHttpUtils;

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

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class SingleChoiceActivity extends AppCompatActivity implements View.OnClickListener {
    private ImageView iv_back;
    private EditText edt_name;
    private TextView tv_search;
    private String mark = "";
    private String mServer;
    private String mUsername;
    private String mPassword;
    private String mUserid;
    private String mCaption;
    private String mBizid, mBizName;
    private String name = "";
    private String sel_ps_id = "";
    private RecyclerView rc_list;
    private SwipeRefreshLayout refreshLayout;
    private List<EquList> equLists = new ArrayList<>();
    private PSSingleChoiceAdapter psAdapter;
    private EquSingleChoiceAdapter equAdapter;
    private LinearLayoutManager manager;
    private List<ProcessSection> processSections = new ArrayList<>();

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

    private void initView() {
        iv_back = findViewById(R.id.moudle_single_choice_iv_back);
        iv_back.setOnClickListener(this);
        edt_name = findViewById(R.id.moudle_single_choice_edt_equname);
        tv_search = findViewById(R.id.moudle_single_choice_tv_search);
        tv_search.setOnClickListener(this);
        rc_list = findViewById(R.id.moudle_single_choice_rc);
        refreshLayout = findViewById(R.id.moudle_single_choice_refresh);
        refreshLayout.setColorSchemeResources(R.color.blue);
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                startSearch();
            }
        });
    }

    private void init() {
        SharedPreferences sharedPre = this.getSharedPreferences("config", 0);
        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", "");
        if (getIntent().getStringExtra("mark")!=null&&!getIntent().getStringExtra("mark").isEmpty()){
            mark = getIntent().getStringExtra("mark");
        }
        if (getIntent().getStringExtra("psId")!=null&&!getIntent().getStringExtra("psId").isEmpty()){
            sel_ps_id = getIntent().getStringExtra("psId");
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.moudle_single_choice_iv_back:
                finish();
                break;
            case R.id.moudle_single_choice_tv_search:
                startSearch();
                break;
        }
    }

    private void startSearch() {
        if (edt_name.getText()!=null&&!edt_name.getText().toString().isEmpty()){
            name = edt_name.getText().toString();
        }
        judgeRefresh();
        if (mark.equals("equ")) {
            searchEqu(name);
        }else if(mark.equals("ps")){
            searchPS(name);
        }
    }

    private void judgeRefresh() {
        if (!SingleChoiceActivity.this.isFinishing()){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (!refreshLayout.isRefreshing()){
                        refreshLayout.setRefreshing(true);
                    }
                }
            });
        }
    }

    /**
     * 搜索工艺段
     * @param name
     */
    private void searchPS(String name) {
        HashMap<String,String> map = new HashMap<>();
        map.put("search_code",mBizid);
        map.put("search_name",name);
        map.put("rows","300");
        map.put("page","1");
        OKHttpUtils.getClient().newCall(OKHttpUtils.OKHttpRequest(map, mServer, MethodURL.GETPSLISt_Method)).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                if (!SingleChoiceActivity.this.isFinishing()){
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            refreshLayout.setRefreshing(false);
                            Toast.makeText(SingleChoiceActivity.this, "失败：" + e.toString(), Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                if (res.contains("total")&&res.contains("rows")) {
                    processSections = parsePS(res);
                }
                updatePSList();
            }
        });
    }

    private void updatePSList() {
        if (!SingleChoiceActivity.this.isFinishing()){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    refreshLayout.setRefreshing(false);
                    psAdapter = new PSSingleChoiceAdapter(SingleChoiceActivity.this, processSections, new PSSingleChoiceAdapter.onRecyclerViewItemClick() {
                        @Override
                        public void onItemClick(View v, int position) {
                            Intent intent = new Intent();
                            intent.putExtra("ps",processSections.get(position));
                            setResult(RESULT_OK,intent);
                            finish();
                        }
                    });
                    rc_list.setAdapter(psAdapter);
                    manager = new LinearLayoutManager(SingleChoiceActivity.this);
                    rc_list.setLayoutManager(manager);
                }
            });
        }
    }

    private List<ProcessSection> parsePS(String res) {
        List<ProcessSection> list = new ArrayList<>();
        try {
            JSONObject jsonObject = new JSONObject(res);
            JSONArray array = jsonObject.getJSONArray("rows");
            for (int i=0;i<array.length();i++){
                ProcessSection item = new ProcessSection();
                item.setSid(array.getJSONObject(i).optString("id"));
                item.setSname(array.getJSONObject(i).optString("sname"));
                item.setName(array.getJSONObject(i).optString("name"));
                list.add(item);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 搜索设备
     * @param name
     */
    private void searchEqu(String name) {
        HashMap<String,String> map = new HashMap<>();
        map.put("companyId",mBizid);
        map.put("equipmentName",name);
        map.put("processSectionId",sel_ps_id);
        map.put("rows","30");
        map.put("page","1");
        OKHttpUtils.getClient().newCall(OKHttpUtils.OKHttpRequest(map, mServer, MethodURL.GETEQULISt_Method)).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                if (!SingleChoiceActivity.this.isFinishing()){
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            refreshLayout.setRefreshing(false);
                            Toast.makeText(SingleChoiceActivity.this, "失败：" + e.toString(), Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                if (res.contains("total")&&res.contains("rows")) {
                    equLists = parseEqu(res);
                }
                updateEquList();
            }
        });
    }

    private void updateEquList() {
        if (!SingleChoiceActivity.this.isFinishing()){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    refreshLayout.setRefreshing(false);
                    equAdapter = new EquSingleChoiceAdapter(SingleChoiceActivity.this, equLists, new EquSingleChoiceAdapter.onRecyclerViewItemClick() {
                        @Override
                        public void onItemClick(View v, int position) {
                            Intent intent = new Intent();
                            intent.putExtra("ppid",equLists.get(position).getId());
                            intent.putExtra("class","equ");
                            intent.putExtra("equ",equLists.get(position));
                            setResult(RESULT_OK,intent);
                            finish();
                        }
                    });
                    rc_list.setAdapter(equAdapter);
                    manager = new LinearLayoutManager(SingleChoiceActivity.this);
                    rc_list.setLayoutManager(manager);
                }
            });
        }
    }

    private List<EquList> parseEqu(String res) {
        List<EquList> list = new ArrayList<>();
        try {
            JSONObject jsonObject = new JSONObject(res);
            JSONArray array = jsonObject.getJSONArray("rows");
            for (int i=0;i<array.length();i++){
                EquList item = new EquList();
                item.setId(array.getJSONObject(i).optString("id"));
                item.setEquipmentmanufacturer(array.getJSONObject(i).optString("equipmentmanufacturer"));
                item.setEquipmentname(array.getJSONObject(i).optString("equipmentname"));
                item.setEquipmentcardid(array.getJSONObject(i).optString("equipmentcardid"));
                item.setEquipmentmodel(array.getJSONObject(i).optString("equipmentmodelname"));
                if (!array.getJSONObject(i).optString("processSection").equals("null")&&!array.getJSONObject(i).optString("processSection").isEmpty()){
                    JSONObject js = new JSONObject(array.getJSONObject(i).optString("processSection"));
                    item.setProcessSection(js.optString("name"));
                    item.setProcesssectionid(js.optString("id"));
                }else {
                    item.setProcessSection("暂未配置");
                }
                if (!array.getJSONObject(i).optString("equipmentStatusManagement").equals("null")&&!array.getJSONObject(i).optString("equipmentStatusManagement").isEmpty()){
                    JSONObject js = new JSONObject(array.getJSONObject(i).optString("equipmentStatusManagement"));
                    item.setEquipmentStatusManagement(js.optString("name"));
                }else {
                    item.setEquipmentStatusManagement("未知");
                }
                if (!array.getJSONObject(i).optString("equipmentLevel").equals("null")&&!array.getJSONObject(i).optString("equipmentLevel").isEmpty()){
                    JSONObject js = new JSONObject(array.getJSONObject(i).optString("equipmentLevel"));
                    item.setEquipmentLevel(js.optString("levelname")+"类");
                }else {
                    item.setEquipmentLevel("未知");
                }
                item.setAreaid(array.getJSONObject(i).optString("areaid"));
                if (!array.getJSONObject(i).optString("company").equals("null")&&!array.getJSONObject(i).optString("company").isEmpty()){
                    JSONObject js = new JSONObject(array.getJSONObject(i).optString("company"));
                    item.setCompany(js.optString("name"));
                }else {
                    item.setCompany("暂未配置");
                }
                if (!array.getJSONObject(i).optString("equipmentTypeNumber").equals("null")&&!array.getJSONObject(i).optString("equipmentTypeNumber").isEmpty()){
                    JSONObject js = new JSONObject(array.getJSONObject(i).optString("equipmentTypeNumber"));
                    item.setEquipmentTypeNumber(js.optString("name"));
                }else {
                    item.setEquipmentTypeNumber("暂未配置");
                }
                if (!array.getJSONObject(i).optString("equipmentClass").equals("null")&&!array.getJSONObject(i).optString("equipmentClass").isEmpty()){
                    JSONObject js = new JSONObject(array.getJSONObject(i).optString("equipmentClass"));
                    item.setEquipmentClass(js.optString("name"));
                }else {
                    item.setEquipmentClass("暂未配置");
                }
                if (!array.getJSONObject(i).optString("equipmentClass").equals("null")&&!array.getJSONObject(i).optString("equipmentClass").isEmpty()){
                    JSONObject js = new JSONObject(array.getJSONObject(i).optString("equipmentClass"));
                    item.setEquipmentClass(js.optString("name"));
                }else {
                    item.setEquipmentClass("暂未配置");
                }
                if (!array.getJSONObject(i).optString("mPoint4APP").equals("null")&&!array.getJSONObject(i).optString("mPoint4APP").isEmpty()){
                    JSONArray arrayPoint = array.getJSONObject(i).getJSONArray("mPoint4APP");
                    List<Measuringpoint> points = new ArrayList<>();
                    for (int a=0;a<arrayPoint.length();a++){
                        Measuringpoint point = new Measuringpoint();
                        point.setSid(arrayPoint.getJSONObject(a).opt("id").toString());
                        point.setName(arrayPoint.getJSONObject(a).opt("parmname").toString());
                        point.setUnit(arrayPoint.getJSONObject(a).opt("unit").toString());
                        point.setCvalue(arrayPoint.getJSONObject(a).opt("parmvalue").toString());
                        point.setType(arrayPoint.getJSONObject(a).opt("signalType").toString());
                        point.setScadacode(arrayPoint.getJSONObject(a).opt("id").toString());
                        point.setAlarmmax(arrayPoint.getJSONObject(a).opt("alarmmax").toString());
                        point.setAlarmmin(arrayPoint.getJSONObject(a).opt("alarmmin").toString());
                        points.add(point);
                    }
                    item.setMeasuringpoints(points);
                }
                list.add(item);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return list;
    }
}
