package com.sipai.jspatrol.PointAnalysis;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

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

import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.ClassicsHeader;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.sipai.jspatrol.Bean.Area;
import com.sipai.jspatrol.Bean.Measuringpoint;
import com.sipai.jspatrol.R;
import com.sipai.jspatrol.URL.MethodURL;
import com.sipai.jspatrol.utils.OKHttpUtils;
import com.sipai.jspatrol.utils.ProgressForAll;
import com.sipai.jspatrol.utils.Utils;
import com.sipai.ui.EmptyLayout;

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

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

import cn.pedant.SweetAlert.SweetAlertDialog;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class SelPointListActivity extends AppCompatActivity {
    private String mServer,token;
    private String mBizid,mUserid;
    private ImageView iv_back;
    private EditText edt_search;
    private TextView tv_search,tv_compare;
    private String name = "";
    private String sourceType = "";
    private int page = 1;
    private int rows = 20;
    private int total = 0;
    private String[] source = {"全部","外部导入点","KPI计算点","手动测量点","自动转发测量点"};
    private LinearLayout ll_source;
    private Spinner sp_source;
    private ArrayAdapter<String> sourceadapter;
    private List<Measuringpoint> points = new ArrayList<>();
    private List<Measuringpoint> seledPoints = new ArrayList<>();
    private SmartRefreshLayout refreshLayout;
    private RecyclerView rc,rc_seled_point;
    private LinearLayoutManager manager,seled_manager;
    private MPointsAdapter pointsAdapter;
    private SeledAdapter seledAdapter;
    private EmptyLayout emptyLayout;
    private ArrayAdapter<String> areaadapter;
    private List<Area> areas = new ArrayList<>();
    private List<String> areaname = new ArrayList<>();
    private int area_locate = 0;//标记所选工艺段的下标
    private String area_id = "";
    private static final int AREAS = 1;

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sel_point_list);
        init();
        initView();
    }

    private void initView() {
        iv_back = findViewById(R.id.moudle_sel_point_iv_back);
        iv_back.setOnClickListener(v -> {
            finish();
        });
        edt_search = findViewById(R.id.moudle_sel_point_edt_pointname);
        tv_search = findViewById(R.id.moudle_sel_point_tv_search);
        tv_search.setOnClickListener(v -> {
            page=1;
            searchPoint();
        });
        tv_compare = findViewById(R.id.moudle_sel_point_tv_compare);
        tv_compare.setOnClickListener(v -> {
                PointAnalysisActivity.actionStart(SelPointListActivity.this,seledPoints);
        });
        emptyLayout = findViewById(R.id.moudle_sel_point_ui_empty);
        sp_source = findViewById(R.id.moudle_sel_point_sp_source);
        sourceadapter = new ArrayAdapter<String>(SelPointListActivity.this,R.layout.item_down,R.id.tv_down_sp,areaname);
        sp_source.setAdapter(areaadapter);
        sp_source.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//                Toast.makeText(ProductionMonitorActivity.this, ""+areaname.get(position), Toast.LENGTH_SHORT).show();
                if (areaname.get(position).equals("无")||areas.size()<1) {
                    searchPoint();
                }else {
                    area_id = areas.get(position).getId();
                    area_locate = position;
                    page=1;
                    searchPoint();
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
//                Toast.makeText(ProductionMonitorActivity.this, ""+areaname.get(0), Toast.LENGTH_SHORT).show();
//                area_id = areas.get(0).getCode();
//                getAllPoints();
            }
        });
        refreshLayout = findViewById(R.id.moudle_sel_point_refresh);
        refreshLayout.setRefreshHeader(new ClassicsHeader(this));
        refreshLayout.setRefreshFooter(new ClassicsFooter(this));
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page=1;
                searchPoint();
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page = page+1;
                searchPoint();
            }
        });
        rc_seled_point = findViewById(R.id.moudle_sel_point_rc_seled_point);
        rc = findViewById(R.id.moudle_sel_point_list_rc);
        manager = new LinearLayoutManager(this);
        rc.setLayoutManager(manager);
        pointsAdapter = new MPointsAdapter(points);
        rc.setAdapter(pointsAdapter);
    }

    @Override
    protected void onResume() {
        super.onResume();
        getarea();
    }

    private void getarea() {
        HashMap<String,String> map = new HashMap<>();
        map.put("page","1");
        map.put("rows","500");
        map.put("search_code",mBizid);
        OKHttpUtils.getClient().newCall(OKHttpUtils.OKHttpRequest(map, mServer, MethodURL.GETPSLISt_Method)).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                String a = e.toString();
                if (!SelPointListActivity.this.isFinishing()) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            new SweetAlertDialog(SelPointListActivity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("提示")
                                    .setContentText("工艺段数据获取失败请重试！")
                                    .setConfirmText("确认")
                                    .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                        @Override
                                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                                            sweetAlertDialog.dismissWithAnimation();
                                            getarea();
                                        }
                                    }).show();
                        }
                    });
                }
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                Log.i("areaname", "onSuccess: "+response);
                areaname.clear();
                areas = getAreaData(res);
                if (areas!=null&&!areas.isEmpty()){
                    for (int i=0;i<areas.size();i++){
                        areaname.add(areas.get(i).getName());
                    }
                }else {
                    areaname.add("无");
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        areaadapter = new ArrayAdapter<String>(SelPointListActivity.this, R.layout.item_down, R.id.tv_down_sp, areaname);
                        sp_source.setAdapter(areaadapter);
                        sp_source.setSelection(area_locate);
                    }
                });
            }
        });
    }

    private List<Area> getAreaData(String response) {
        List<Area> list = new ArrayList<>();
        try {
            JSONObject jsonObject = new JSONObject(response);

            JSONArray aNews = new JSONArray(jsonObject.getString("rows"));
            if (aNews != null && aNews.length() > 0) {
                for (int i = 0; i <aNews.length(); i++) {
                    Area item = new Area();
                    item.setId(aNews.getJSONObject(i).optString("id"));
                    item.setName(aNews.getJSONObject(i).optString("name"));
                    item.setCode(aNews.getJSONObject(i).optString("code"));
                    list.add(item);
                }
            }
        } catch (JSONException ex) {
            Log.e("JSON Error: ", ex.toString());
        }
        return list;
    }


    private void searchPoint() {
        ProgressForAll.showProgress(SelPointListActivity.this,"","数据加载中...");
        if (edt_search.getText()!=null&&!edt_search.getText().toString().isEmpty()){
            name = edt_search.getText().toString();
        }
        HashMap<String,String> map = new HashMap<>();
        map.put("bizid",mBizid);//厂id
        map.put("processSectionCode", area_id);//工艺段
        map.put("isCollected","1");
        map.put("page",String.valueOf(page));
        map.put("userId",mUserid);
        map.put("search_name",name);
        map.put("rows","50");
        map.put("type", "");//类型
        OKHttpUtils.OKCall(map, mServer, MethodURL.GetAllCollectePoint_Method).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                hidePg();
                noMore(false);
                showToast("请求失败！");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                if (res.contains("content1")) {
                    hidePg();
                    if (page==1) {
                        points = getAreaPoints(res);
                        updateList();
                    }else {
                        List<Measuringpoint> pList = getAreaPoints(res);
                        if (total>=(points.size()+pList.size())) {
                            points.addAll(pList);
                            updateList();
                        }else {
                            noMore(true);
                        }
                    }
                }else {
                    hidePg();
                }
            }
        });
    }

    private void updateList() {
        if (!SelPointListActivity.this.isFinishing()){
            runOnUiThread(()->{
                if (page==1){
                    if (points!=null&&points.size()>0){
                        emptyLayout.setVisibility(View.GONE);
                        rc.setVisibility(View.VISIBLE);
                        refreshLayout.finishRefresh(true);
                        manager = new LinearLayoutManager(this);
                        rc.setLayoutManager(manager);
                        pointsAdapter = new MPointsAdapter(points);
                        rc.setAdapter(pointsAdapter);
                    }else {
                        refreshLayout.finishRefresh(false);
                        emptyLayout.setVisibility(View.VISIBLE);
                        rc.setVisibility(View.GONE);
                    }
                }else {
                    refreshLayout.finishLoadMore(true);
                    pointsAdapter.notifyDataSetChanged();
                }
            });
        }
    }

    private List<Measuringpoint> getAreaPoints(String response) {
        List<Measuringpoint> list = new ArrayList<>();
        try {
            JSONObject jsonObject = new JSONObject(response);

            JSONArray aNews = new JSONArray(jsonObject.getString("content1"));
            if (aNews != null && aNews.length() > 0) {
                for (int i = 0; i <aNews.length(); i++) {
                    Measuringpoint item = new Measuringpoint();
                    item.setSid(aNews.getJSONObject(i).opt("id").toString());
                    item.setName(aNews.getJSONObject(i).opt("parmname").toString());
                    item.setUnit(aNews.getJSONObject(i).opt("unit").toString());
                    DecimalFormat df = new DecimalFormat("#.####");
                    if (!aNews.getJSONObject(i).optString("parmvalue").contains("-")) {
                        item.setCvalue(aNews.getJSONObject(i).optString("parmvalue"));
                    }else {
                        item.setCvalue(df.format(aNews.getJSONObject(i).opt("parmvalue")));
                    }
//                    item.setCvalue(aNews.getJSONObject(i).opt("parmvalue").toString());
                    item.setType(aNews.getJSONObject(i).opt("signalType").toString());
                    item.setScadacode(aNews.getJSONObject(i).opt("id").toString());
                    item.setAlarmmax(aNews.getJSONObject(i).opt("alarmmax").toString());
                    item.setAlarmmin(aNews.getJSONObject(i).opt("alarmmin").toString());
                    if (aNews.getJSONObject(i).optString("userid").isEmpty()){
                        item.setUserid("null");
                    }else {
                        item.setUserid(aNews.getJSONObject(i).optString("userid"));
                    }
                    list.add(item);
                }
            }
        } catch (JSONException ex) {
            Log.e("JSON Error: ", ex.toString());
        }
        return list;
    }

    private void noMore(boolean suc) {
        if (!SelPointListActivity.this.isFinishing()){
            runOnUiThread(()->{
                if (page==1) {
                    refreshLayout.finishRefresh(suc);
                }else {
                    refreshLayout.finishLoadMore(suc);
                }
            });
        }
    }

    private void showToast(String s) {
        if (!SelPointListActivity.this.isFinishing()){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(SelPointListActivity.this, s, Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    private void hidePg() {
        if (!SelPointListActivity.this.isFinishing()){
            runOnUiThread(()->{
                ProgressForAll.cancelProgress();
            });
        }
    }

    private void init(){
        SharedPreferences sharedPre = this.getSharedPreferences("config", 0);
        mServer = sharedPre.getString("server", "");
        mBizid = sharedPre.getString("bizid", "");
        mUserid = sharedPre.getString("userid","");
    }

    class MPointsAdapter extends RecyclerView.Adapter<MPointsAdapter.ViewHolder> {
        private List<Measuringpoint> list;

        public MPointsAdapter(List<Measuringpoint> list) {
            this.list = list;
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_measurepoint,parent,false);
            final ViewHolder viewHolder = new ViewHolder(view);
            return viewHolder;
        }

        public void setData(List<Measuringpoint> list){
            this.list = list;
        }

        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {
            Measuringpoint item = list.get(position);
            holder.name.setText(item.getName());
            holder.name.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (seledPoints!=null&&!seledPoints.contains(item)) {
                        seledPoints.add(item);
                        if (seledPoints.size()==1){
                            rc_seled_point.setVisibility(View.VISIBLE);
                            seled_manager = new LinearLayoutManager(SelPointListActivity.this);
                            seled_manager.setOrientation(RecyclerView.HORIZONTAL);
                            rc_seled_point.setLayoutManager(seled_manager);
                            seledAdapter = new SeledAdapter(SelPointListActivity.this, seledPoints, new SeledAdapter.onRecyclerViewItemClick() {
                                @Override
                                public void onItemClick(View v, int position) {
                                    seledPoints.remove(position);
                                    if (seledPoints.size()>0) {
                                        seledAdapter.notifyDataSetChanged();
                                    }else {
                                        seledAdapter.notifyDataSetChanged();
                                        rc_seled_point.setVisibility(View.GONE);
                                    }
                                }
                            });
                            rc_seled_point.setAdapter(seledAdapter);
                        }else {
                            seledAdapter.notifyDataSetChanged();
                        }
                    }else {
                        showToast("该点已在队列中！");
                    }
                }
            });
            holder.iv_logo.setImageResource(Utils.getpointPic(item.getName()));

            if (item.getUnit()!=null&&!item.getUnit().isEmpty()&&!item.getUnit().equals("null")) {
                holder.value.setText(item.getCvalue() + item.getUnit());
            }else if (item.getValuemeaning()==null||item.getValuemeaning().isEmpty()){
                holder.value.setText(item.getCvalue());
            }else {
                String[] types = new String[]{};
                types = holder.itemView.getContext().getResources().getStringArray(Utils.getValueArray(item.getValuemeaning()));
                if (types.length>0) {
                    holder.value.setText(types[Integer.parseInt(item.getCvalue())]);
                }else {
                    holder.value.setText(item.getCvalue() + item.getUnit());
                }
            }
            if (item.getAlarmmax()!=null&&!item.getAlarmmax().equals("null")&&!item.getAlarmmax().isEmpty()&&item.getAlarmmin()!=null&&!item.getAlarmmin().equals("null")&&!item.getAlarmmin().isEmpty()) {
                float max = Float.parseFloat(item.getAlarmmax());
                float min = Float.parseFloat(item.getAlarmmin());
                float value = Float.parseFloat(item.getCvalue());
                if (max==min){
                    holder.value.setTextColor(holder.point.getContext().getResources().getColor(R.color.gray04));
                }else {
                    if (value <= min || value >= max) {
                        holder.value.setTextColor(holder.point.getContext().getResources().getColor(R.color.red));
                    } else {
                        holder.value.setTextColor(holder.point.getContext().getResources().getColor(R.color.gray04));
                    }
                }
            }
            if (item.getType().equals("DI")){
                holder.value.setVisibility(View.GONE);
            }else if (item.getType().equals("AI")){
                holder.value.setVisibility(View.VISIBLE);
            }
            String info = item.getName();
            if(item.getType().equals("DI")){
                int id= Utils.getlight4mp(info,item.getCvalue());
                holder.iv_btn.setVisibility(View.VISIBLE);
                holder.iv_btn.setImageResource(id);
            }else {
                holder.iv_btn.setVisibility(View.GONE);
            }


        }

        @Override
        public int getItemCount() {
            return list.size();
        }

         class ViewHolder extends RecyclerView.ViewHolder{
            View point;
            TextView name,value;
            ImageView iv_btn,iv_logo;
            public ViewHolder(View itemView) {
                super(itemView);
                point = itemView;
                name = itemView.findViewById(R.id.point_name);
                value = itemView.findViewById(R.id.point_value);
                iv_btn = itemView.findViewById(R.id.point_btn);
                iv_logo = itemView.findViewById(R.id.moudle_measurepoint_iv);
            }
        }
    }

    static class SeledAdapter extends RecyclerView.Adapter<SeledAdapter.ViewHolder> {
        private Context context;
        private List<Measuringpoint> list;
        private onRecyclerViewItemClick mOnRcClick;

        public SeledAdapter(Context context, List<Measuringpoint> list, onRecyclerViewItemClick mOnRcClick) {
            this.context = context;
            this.list = list;
            this.mOnRcClick = mOnRcClick;
        }

        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_seled_nodes,parent,false);
            ViewHolder viewHolder = new ViewHolder(view);
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
            Measuringpoint item = list.get(position);
            holder.tv_name.setText(item.getName());
        }

        @Override
        public int getItemCount() {
            return list.size();
        }

        class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
            ImageView iv_cross;
            TextView tv_name;
            public ViewHolder(@NonNull View itemView) {
                super(itemView);
                iv_cross = itemView.findViewById(R.id.moudle_item_seled_nodes_iv_cross);
                iv_cross.setOnClickListener(this);
                tv_name = itemView.findViewById(R.id.moudle_item_seled_nodes_tv_name);
            }

            @Override
            public void onClick(View v) {
                if (mOnRcClick!=null){
                    mOnRcClick.onItemClick(v,getAdapterPosition());
                }
            }
        }

        public interface onRecyclerViewItemClick{
            void onItemClick(View v,int position);
        }
    }
}