package com.sipai.jspatrol.Fault;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
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 androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.sipai.jspatrol.Bean.Fault;
import com.sipai.jspatrol.Bean.FaultFlow;
import com.sipai.jspatrol.Bean.User;
import com.sipai.jspatrol.Fault.adapter.FaultFlowAdapter;
import com.sipai.jspatrol.R;
import com.sipai.jspatrol.URL.MethodURL;
import com.sipai.jspatrol.utils.DateFormatUtils;
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 cn.pedant.SweetAlert.SweetAlertDialog;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class FaultFlowChartActivity extends AppCompatActivity {
    private Fault mFault;
    private List<FaultFlow> flows = new ArrayList<>();
    private SwipeRefreshLayout refreshLayout;
    private RecyclerView rc;
    private LinearLayoutManager manager;
    private FaultFlowAdapter adapter;

    public static void actionStart(Context context, Fault fault){
        Intent intent = new Intent(context, FaultFlowChartActivity.class);
        intent.putExtra("fault",fault);
        context.startActivity(intent);
    }

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

    /**
     * 初始化
     */
    private String mServer;
    private String mUsername;
    private String mPassword;
    private String mUserid;
    private String mCaption;
    private String mBizid;
    private String mGroup;
    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", "");
        mGroup=sharedPre.getString("group", "");
        if (getIntent().getSerializableExtra("fault")!=null){
            mFault    = (Fault) getIntent().getSerializableExtra("fault");
        }
    }

    private void initView() {
        TextView tv_title = findViewById(R.id.moudle_back_title_tv_title);
        tv_title.setText("处理流程");
        ImageView btn_back = findViewById(R.id.moudle_back_title_iv_back);
        btn_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        refreshLayout = findViewById(R.id.moudle_fault_flow_chart_refresh);
        refreshLayout.setColorSchemeResources(R.color.blue);
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getFlow();
            }
        });
        rc = findViewById(R.id.moudle_fault_flow_chart_rc);
        manager = new LinearLayoutManager(this);
        rc.setLayoutManager(manager);
    }

    private void getFlow() {
        if (!refreshLayout.isRefreshing()) {
            showRefresh();
        }
        HashMap<String,String> map = new HashMap<>();
        map.put("id",mFault.getId());
        OKHttpUtils.getClient().newCall(OKHttpUtils.OKHttpRequest(map, mServer, MethodURL.GetMaintenanceFlowChart_Method)).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                String a = e.toString();
                hideRefresh();
                if (!FaultFlowChartActivity.this.isFinishing()){
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            new SweetAlertDialog(FaultFlowChartActivity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("提示")
                                    .setContentText("流程图获取失败，请重试！")
                                    .setConfirmText("重试")
                                    .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                        @Override
                                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                                            sweetAlertDialog.dismissWithAnimation();
                                            getFlow();
                                        }
                                    }).show();
                        }
                    });
                }
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                hideRefresh();
                flows = parseFlow(res);
                updateFlow();
            }
        });
    }

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

    private void hideRefresh() {
        if (!FaultFlowChartActivity.this.isFinishing()){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    refreshLayout.setRefreshing(false);
                }
            });
        }
    }

    private void updateFlow() {
        if (!FaultFlowChartActivity.this.isFinishing()){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    adapter = new FaultFlowAdapter(FaultFlowChartActivity.this,flows);
                    rc.setAdapter(adapter);
                }
            });
        }
    }

    private List<FaultFlow> parseFlow(String res) {
        List<FaultFlow> list = new ArrayList<>();
        try {
            JSONArray array = new JSONArray(res);
            for (int i=0;i<array.length();i++){
                FaultFlow item = new FaultFlow();
                item.setId(array.getJSONObject(i).optString("id"));
                item.setProcessid(array.getJSONObject(i).optString("processid"));
                item.setRecord(array.getJSONObject(i).optString("record"));
                item.setTaskName(array.getJSONObject(i).optString("taskName"));
                item.setInsdt(DateFormatUtils.DateFormatMinString(array.getJSONObject(i).optString("insdt")));
                User user = new User();
                JSONObject jsonObject = array.getJSONObject(i).getJSONObject("user");
                user.setId(jsonObject.optString("id"));
                user.setCaption(jsonObject.optString("caption"));
                item.setUser(user);
                list.add(item);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return list;
    }
}