package com.sipai.jspatrol.Statement;

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

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 android.widget.Toast;

import com.gigamole.navigationtabstrip.NavigationTabStrip;
import com.sipai.jspatrol.Bean.Statement;
import com.sipai.jspatrol.R;
import com.sipai.jspatrol.URL.MethodURL;
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.util.ArrayList;
import java.util.HashMap;
import java.util.List;

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

public class StatementListActivity extends AppCompatActivity {
    private String mServer;
    private String mBizid;
    private String classId;
    private String title;
    private NavigationTabStrip tab;
    private String[] tab_title = new String[]{"报表生成","报表浏览"};
    private SwipeRefreshLayout refresh;
    private RecyclerView rc_view;
    private EmptyLayout emptyLayout;
    private LinearLayoutManager manager;
    private StatementAdapter adapter;
    private List<Statement> statements = new ArrayList<>();
    private String requestUrl;

    public static void actionStart(Context context,String id,String title){
        Intent intent = new Intent(context,StatementListActivity.class);
        intent.putExtra("classId",id);
        intent.putExtra("title",title);
        context.startActivity(intent);
    }

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

    private void initView() {
        TextView tv_title = (TextView) findViewById(R.id.moudle_back_title_tv_title);
        tv_title.setText(title);
        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();
            }
        });
        tab = findViewById(R.id.moudle_statement_list_tab);
        tab.setTitles(tab_title);
        tab.setOnTabStripSelectedIndexListener(new NavigationTabStrip.OnTabStripSelectedIndexListener() {
            @Override
            public void onStartTabSelected(String title, int index) {
                if (title.equals("报表生成")){
                    requestUrl = MethodURL.GetStatementList_Method;
                }else if (title.equals("报表浏览")){
                    requestUrl = MethodURL.GetViewStatementList_Method;
                }else if (title.equals("审核中")){
                    requestUrl = MethodURL.GetAuditStatementList_Method;
                }
                getStatementList();
            }

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

            }
        });
        tab.setTabIndex(0);
        emptyLayout = findViewById(R.id.moudle_statement_list_ui_empty);
        refresh = findViewById(R.id.moudle_statement_list_refresh);
        refresh.setColorSchemeResources(R.color.blue);
        refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getStatementList();
            }
        });
        rc_view = findViewById(R.id.moudle_statement_list_rc);
        manager = new LinearLayoutManager(StatementListActivity.this);
        rc_view.setLayoutManager(manager);
    }

    private void getStatementList() {
        HashMap<String,String> map = new HashMap<>();
        map.put("page","1");
        map.put("rows","50");
        map.put("sort","rptdt");
        map.put("order","desc");
        map.put("stdt","");
        map.put("eddt","");
        map.put("st","");
        map.put("unitId", mBizid);
        map.put("classId", classId);
        OKHttpUtils.getClient().newCall(OKHttpUtils.OKHttpRequest(map, mServer, requestUrl)).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                errorResponse();
                showEmpty();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                if (res.contains("total")&&res.contains("rows")){
                    statements = parseStatement(res);
                    showStatement();
                }else {
                    showEmpty();
                }
            }
        });
    }

    private void showStatement() {
        if (!StatementListActivity.this.isFinishing()){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    refresh.setRefreshing(false);
                    manager = new LinearLayoutManager(StatementListActivity.this);
                    rc_view.setLayoutManager(manager);
                    adapter = new StatementAdapter(StatementListActivity.this,statements);
                    rc_view.setAdapter(adapter);
                }
            });
        }
    }

    private List<Statement> parseStatement(String res) {
        List<Statement> list = new ArrayList<>();
        try {
            JSONObject jsonObject = new JSONObject(res);
            JSONArray array = jsonObject.getJSONArray("rows");
            for (int i=0;i<array.length();i++){
                Statement item = new Statement();
                item.setId(array.getJSONObject(i).optString("id"));
                item.setRptdt(array.getJSONObject(i).optString("rptdt"));
                item.setRptname(array.getJSONObject(i).optString("rptname"));
                item.setInputusername(array.getJSONObject(i).optString("inputusername"));
                item.setInsdt(array.getJSONObject(i).optString("insdt"));
                item.setRptsetId(array.getJSONObject(i).optString("rptsetId"));
                item.setMeno(array.getJSONObject(i).optString("memo"));
                list.add(item);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return list;
    }

    private void errorResponse() {
        if (!StatementListActivity.this.isFinishing()){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(StatementListActivity.this, "列表获取失败！", Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    private void showEmpty() {
        if (!StatementListActivity.this.isFinishing()){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    refresh.setRefreshing(false);
                    rc_view.setVisibility(View.GONE);
                    emptyLayout.setVisibility(View.VISIBLE);
                }
            });
        }
    }

    private void init() {
        requestUrl = MethodURL.GetStatementList_Method;
        SharedPreferences sharedPre=this.getSharedPreferences("config", 0);
        mServer=sharedPre.getString("server", "");
        mBizid=sharedPre.getString("bizid", "");
        classId = getIntent().getStringExtra("classId");
        title = getIntent().getStringExtra("title");
    }
}