package com.sipai.jspatrol.Main.fragment.promFragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
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.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.gigamole.navigationtabstrip.NavigationTabStrip;
import com.sipai.jspatrol.Base.BaseFragmentView;
import com.sipai.jspatrol.Bean.Area;
import com.sipai.jspatrol.Bean.Measuringpoint;
import com.sipai.jspatrol.ProMonitoring.MeasurePointsAdapter;
import com.sipai.jspatrol.R;
import com.sipai.jspatrol.Service.IPatrolService;
import com.sipai.jspatrol.URL.MethodURL;
import com.sipai.jspatrol.utils.BroadCastManager;
import com.sipai.jspatrol.utils.OKHttpUtils;
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;

/**
 * created by lvliming on 2019/9/16
 */
public class ProMFragment extends BaseFragmentView<ProMFragmentPresenter, ProMFragmentContract.View> implements View.OnClickListener{
    private String mServer;
    private String mUsername;
    private String mPassword;
    private String mUserid;
    private String mCaption;
    private String mBizid;
    private String mGroup;
    private String mGroup_com;
    private String type_name = "";//type名称
    private Spinner area_sp;//区域sp
    private Spinner type_sp;//类别sp
    private Button iv_refresh;
    private BroadcastReceiver mReceiver;
    private BroadcastReceiver iReceiver;
    private BroadcastReceiver refreshReceiver;
    private SwipeRefreshLayout refreshLayout;
    private RecyclerView recyclerView;
    private ArrayAdapter<String> typeadapter;
    private static String[] types = {"全部信号","AI","DI"};
    private ArrayAdapter<String> areaadapter;
    private List<Area> areas = new ArrayList<>();
    private List<String> areaname = new ArrayList<>();
    private static final int AREAS = 1;
    private static final int POINTS = 2;
    private LinearLayoutManager manager;
    //上一个界面传过来的标志，用于判断返回
    private String b_mark;
    private String area_id = "";
    private List<Measuringpoint> points = new ArrayList<>();
    private MeasurePointsAdapter pointlistadapter;
    private SweetAlertDialog pDialog;
    private int area_locate = 0;//标记所选工艺段的下标
    private EmptyLayout emptyLayout;
    private NavigationTabStrip tab;
    private String[] tab_title = {"所有点","已收藏"};
    private String name = "";
    private int sel = 0;
    private EditText edt_search;
    private TextView tv_search,tv_show_search;
    private LinearLayout ll_search;
    private BroadcastReceiver pointReceiver;

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case AREAS:
                    if (isAdded()) {
                        if (!getActivity().isFinishing()) {
                            refreshLayout.setRefreshing(false);
                            areaadapter = new ArrayAdapter<String>(getActivity(), R.layout.item_down, R.id.tv_down_sp, areaname);
                            area_sp.setAdapter(areaadapter);
                            area_sp.setSelection(area_locate);
                        }
                    }
                    break;
                case POINTS:
                    if (isAdded()) {
                        if (!getActivity().isFinishing()) {
                            refreshLayout.setRefreshing(false);
                            if (points.size()>0) {
                                recyclerView.setVisibility(View.VISIBLE);
                                emptyLayout.setVisibility(View.GONE);
                                pointlistadapter = new MeasurePointsAdapter(getActivity(),points);
                                pointlistadapter.setOnCollecteListener(new MeasurePointsAdapter.onSwipeListener() {
                                    @Override
                                    public void onCollecte(int pos) {
                                        if (!points.get(pos).getUserid().isEmpty()&&!points.get(pos).getUserid().equals("null")){
                                            unCollectePoints(points.get(pos),pos);
                                        }else {
                                            collectePoints(points.get(pos),pos);
                                        }
                                    }
                                });
                                recyclerView.setAdapter(pointlistadapter);
                            }else {
                                recyclerView.setVisibility(View.GONE);
                                emptyLayout.setVisibility(View.VISIBLE);
                            }
                        }
                    }
                    break;
            }
        }
    };

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_pro_m,container,false);
        init();
        initView(view);
        initBroadcast();
//        getarea();
        return view;
    }

    private void initBroadcast() {
        IntentFilter filter_nv = new IntentFilter();
        filter_nv.addAction(IPatrolService.update_newvalue);
        pointReceiver = new NewValueReceiver();
        BroadCastManager.getInstance().registerReceiver(getActivity(), pointReceiver, filter_nv);
    }

    private void init() {
        SharedPreferences sharedPre = getActivity().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", "");
    }

    private void initView(View view) {
        pDialog = new SweetAlertDialog(getActivity(), SweetAlertDialog.PROGRESS_TYPE);
        pDialog.getProgressHelper().setBarColor(Color.parseColor("#419DE4"));
        pDialog.setTitleText("搜索中...");
        pDialog.setCancelable(false);
        pDialog.setCanceledOnTouchOutside(false);
        emptyLayout = view.findViewById(R.id.production_monitor_ui_empty);
        edt_search = view.findViewById(R.id.production_monitor_edt_search);
        ll_search = view.findViewById(R.id.moudle_pro_ll_search);
        tv_search = view.findViewById(R.id.production_tv_search);
        tv_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                page=1;
                getAllPoints(sel);
            }
        });
        tv_show_search = view.findViewById(R.id.production_tv_show_search);
        tv_show_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ll_search.getVisibility()==View.GONE){
                    tv_show_search.setText("隐藏");
                    ll_search.setVisibility(View.VISIBLE);
                }else {
                    tv_show_search.setText("搜索");
                    edt_search.setText("");
                    ll_search.setVisibility(View.GONE);
                }
            }
        });
        type_sp = view.findViewById(R.id.production_monitor_type_sp);
        typeadapter = new ArrayAdapter<String>(getActivity(),R.layout.item_down,R.id.tv_down_sp,types);
        type_sp.setAdapter(typeadapter);
        type_sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                type_name = types[position];
                if (type_name.equals("全部信号")){
                    type_name="全部";
                }
                if (area_id!=null&&!area_id.isEmpty()) {
                    getAllPoints(sel);
                }else {
                    area_id = "";
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
        tab = view.findViewById(R.id.moudle_fg_pro_management_tab);
        tab.setTitles(tab_title);
        tab.setTabIndex(0);
        tab.setOnTabStripSelectedIndexListener(new NavigationTabStrip.OnTabStripSelectedIndexListener() {
            @Override
            public void onStartTabSelected(String title, int index) {
                sel = index;
                getAllPoints(sel);
            }

            @Override
            public void onEndTabSelected(String title, int index) {

            }
        });

        pointlistadapter = new MeasurePointsAdapter(getActivity(),points);

        manager = new LinearLayoutManager(getActivity());
        area_sp = view.findViewById(R.id.production_monitor_area_sp);
        iv_refresh = view.findViewById(R.id.production_iv_refresh);
        iv_refresh.setOnClickListener(this);
        refreshLayout = view.findViewById(R.id.production_monitor_refresh);
        recyclerView = view.findViewById(R.id.production_monitor_recycleview);
        recyclerView.setLayoutManager(manager);
        recyclerView.setAdapter(pointlistadapter);
        refreshLayout.setColorSchemeResources(R.color.blue);
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getarea();
            }
        });
        areaadapter = new ArrayAdapter<String>(getActivity(),R.layout.item_down,R.id.tv_down_sp,areaname);
        area_sp.setAdapter(areaadapter);
        area_sp.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) {
                    if (type_name != null && !type_name.isEmpty()) {
//                        getAllPoints();
                    }
                }else {
                    area_id = areas.get(position).getId();
                    area_locate = position;
                    if (type_name != null && !type_name.isEmpty()) {
                        getAllPoints(sel);
                    }
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
//                Toast.makeText(ProductionMonitorActivity.this, ""+areaname.get(0), Toast.LENGTH_SHORT).show();
//                area_id = areas.get(0).getCode();
//                getAllPoints();
            }
        });
    }

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

    @Override
    public ProMFragmentContract.View getContract() {
        return null;
    }

    @Override
    public ProMFragmentPresenter getPresenter() {
        return new ProMFragmentPresenter();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        BroadCastManager.getInstance().unregisterReceiver(getActivity(),pointReceiver);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.production_iv_refresh:
                getarea();
                break;
        }
    }

    /**
     * 更新数据广播
     */
    class NewValueReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                String nValue = intent.getStringExtra("newvalue");
                parsenValue(nValue);
            } catch (Exception e) {

            }
        }
    }

    private void parsenValue(String nValue) {
        int cou=0;
        try {
            JSONArray array = new JSONArray(nValue);
            for (int i=0;i<array.length();i++){
                for (int a=0;a<points.size();a++){
                    if (points.get(a).getSid().equals(array.getJSONObject(i).optString("id"))){
                        cou+=1;
                        points.get(a).setCvalue(array.getJSONObject(i).optString("parmvalue"));
                    }
                }
            }
            if (cou>0) {
                updatePoints();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void updatePoints() {
        if (isAdded()&&!getActivity().isFinishing()){
            getActivity().runOnUiThread(()->{
                pointlistadapter.setData(points);
                pointlistadapter.notifyDataSetChanged();
            });
        }
    }

    private void getarea() {
        showDialog();
        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) {
                hideDialog();
                String a = e.toString();
                if (isAdded()) {
                    if (!getActivity().isFinishing()) {
                        refreshLayout.setRefreshing(false);
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                new SweetAlertDialog(getActivity(), 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);
                hideDialog();
                areaname.clear();
                areas = getAreaData(res);
                Log.i("areaname", "onSuccess: "+areas.size());
                if (areas!=null&&!areas.isEmpty()){
                    for (int i=0;i<areas.size();i++){
                        areaname.add(areas.get(i).getName());
                    }
                }else {
                    areaname.add("无");
                }
                Message message = new Message();
                message.what = AREAS;
                handler.sendMessage(message);
            }
        });
    }

    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 getAllPoints(int index) throws OutOfMemoryError{
        if (edt_search.getText()!=null){
            name = edt_search.getText().toString();
        }
        HashMap<String,String> map = new HashMap<>();
        map.put("bizid",mBizid);//厂id
        map.put("processSectionCode", area_id);//工艺段
        map.put("isCollected",String.valueOf(index==1));
        map.put("page","1");
        map.put("userId",mUserid);
        map.put("search_name",name);
        map.put("rows","300");
        map.put("type", type_name);//类型
        OKHttpUtils.getClient().newCall(OKHttpUtils.OKHttpRequest(map, mServer, MethodURL.GetAllCollectePoint_Method)).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                String a = e.toString();
                if (isAdded()){
                    if (!getActivity().isFinishing()){
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                refreshLayout.setRefreshing(false);
                                Toast.makeText(getActivity(), "测量点刷新失败，请重试！", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                }
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                points = getAreaPoints(res,type_name);
                Message message = new Message();
                message.what = POINTS;
                handler.sendMessage(message);
                isShowEmpty();
            }
        });
    }

    private List<Measuringpoint> getAreaPoints(String response,String type) {
        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"));
                    }
                    if (type_name.equals("全部")) {
                        list.add(item);
                    }else if (item.getType().equals(type_name)){
                        list.add(item);
                    }
                }
            }
        } catch (JSONException ex) {
            Log.e("JSON Error: ", ex.toString());
        }
        return list;
    }

    private void showDialog() {
        if (isAdded()){
            if (!getActivity().isFinishing()){
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        pDialog.show();
                    }
                });
            }
        }

    }

    private void hideDialog() {
        if (isAdded()){
            if (!getActivity().isFinishing()){
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (pDialog.isShowing()){
                            pDialog.hide();
                        }
                    }
                });
            }
        }
    }

    private void isShowEmpty() {
        if (isAdded()){
            if (!getActivity().isFinishing()){
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (points.size()>0){
                            recyclerView.setVisibility(View.VISIBLE);
                            emptyLayout.setVisibility(View.GONE);
                        }else {
                            recyclerView.setVisibility(View.GONE);
                            emptyLayout.setVisibility(View.VISIBLE);
                        }
                    }
                });
            }
        }
    }

    private void collectePoints(Measuringpoint point,int pos){
        HashMap<String,String> map = new HashMap<>();
        map.put("bizid",mBizid);//厂id
        map.put("userId",mUserid);
        map.put("mpid",point.getSid());
        OKHttpUtils.getClient().newCall(OKHttpUtils.OKHttpRequest(map, mServer, MethodURL.CollectePoint_Method)).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                String a = e.toString();
                showToast("co","fail",pos);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                if (res.equals("fail")){
                    showToast("co","fail",pos);
                }else if (res.equals("suc")){
                    showToast("co","suc",pos);
                }
            }
        });
    }

    private void unCollectePoints(Measuringpoint point,int pos){
        HashMap<String,String> map = new HashMap<>();
        map.put("bizid",mBizid);//厂id
        map.put("userId",mUserid);
        map.put("mpid",point.getSid());
        OKHttpUtils.getClient().newCall(OKHttpUtils.OKHttpRequest(map, mServer, MethodURL.UnCollectePoint_Method)).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                String a = e.toString();
                showToast("un","fail",pos);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                if (res.equals("fail")){
                    showToast("un","fail",pos);
                }else if (res.equals("suc")){
                    showToast("un","suc",pos);
                }
            }
        });
    }

    private void showToast(String mark,String st,int pos) {
        if (isAdded()){
            if (!getActivity().isFinishing()){
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (mark.equals("un")) {
                            if (st.equals("suc")) {
                                Toast.makeText(getActivity(), "取消收藏成功", Toast.LENGTH_SHORT).show();
                                if (sel==1){
                                    points.remove(pos);
                                    pointlistadapter.setData(points);
                                    pointlistadapter.notifyDataSetChanged();
                                    isShowEmpty();
                                }else {
                                    points.get(pos).setUserid("");
                                    pointlistadapter.notifyItemChanged(pos);
                                }
                            } else {
                                Toast.makeText(getActivity(), "取消收藏失败", Toast.LENGTH_SHORT).show();
                            }
                        }else if (mark.equals("co")){
                            if (st.equals("suc")) {
                                Toast.makeText(getActivity(), "收藏成功", Toast.LENGTH_SHORT).show();
                                points.get(pos).setUserid(mUserid);
                                pointlistadapter.notifyItemChanged(pos);
                            } else {
                                Toast.makeText(getActivity(), "收藏失败", Toast.LENGTH_SHORT).show();
                            }
                        }
                    }
                });
            }
        }
    }
}
