package com.bjzc.bhzhgd.activity.sbxj;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.util.Log;
import android.view.WindowManager;
import android.widget.GridView;

import com.bjzc.bhzhgd.DBModel.Profession;
import com.bjzc.bhzhgd.DBModel.ProfessionList;
import com.bjzc.bhzhgd.DBModel.Xjjh;
import com.bjzc.bhzhgd.DBModel.XjjhList;
import com.bjzc.bhzhgd.R;
import com.bjzc.bhzhgd.adapter.GridViewAdapter;
import com.bjzc.bhzhgd.base.BaseActivity;
import com.bjzc.bhzhgd.bean.GridViewBean;
import com.bjzc.bhzhgd.bean.XsRequestInfo;
import com.bjzc.bhzhgd.contans.Contans;
import com.bjzc.bhzhgd.utils.GsonUtils;
import com.bjzc.bhzhgd.utils.HttpListener;
import com.bjzc.bhzhgd.utils.NoProgresshttpUtils;
import com.bjzc.bhzhgd.utils.RSAUtils;
import com.bjzc.bhzhgd.utils.SPUtils;
import com.bjzc.bhzhgd.utils.StatusBarUtil;
import com.google.gson.Gson;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.RequestMethod;
import com.yolanda.nohttp.rest.Request;
import com.yolanda.nohttp.rest.Response;

import org.litepal.crud.DataSupport;

import java.util.ArrayList;
import java.util.List;

import static com.bjzc.bhzhgd.utils.GsonUtils.GsonToBean;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;

/**
 * 巡视抄表管理
 */
public class XscbglActivity extends BaseActivity {

    GridView gv;

//    private String[] str = {"巡检任务", "巡检工作","燃料周期详情"};
//    private int[] imageId = {R.mipmap.icon_xs1, R.mipmap.icon6,R.mipmap.icon8};
//    private int[] colors = {R.drawable.radius_b1, R.drawable.radius_a4,R.drawable.radius_c1};
//    private String[] str = {"巡检任务", "巡检工作", "巡检统计"};
//    private int[] imageId = {R.mipmap.icon_xs1, R.mipmap.icon6,R.mipmap.icon13};
//    private int[] colors = {R.drawable.radius_b1, R.drawable.radius_a4,R.drawable.radius_b1};
    private  List<String> str =  new ArrayList<>();
    private  List<Integer> imageId =  new ArrayList<>();
    private  List<Integer> colors =  new ArrayList<>();
    private GridViewAdapter adapter;
    private String type = null;
    private  String username;
    private BroadcastReceiver myReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (Contans.ACTION_REFRESHDOWNLOADPLAN.equals(action)) {
                //刷新页面
                requestDatas();
            }
        }
    };

    @Override
    public int getContentViewID() {
        return R.layout.activity_xscbgl;
    }

    @Override
    protected void initView() {
        gv = findViewById(R.id.gv);
        Intent intentType = getIntent();
        type = intentType.getStringExtra("type");

        String UserIDTemp = (String) SPUtils.get(context, Contans.USERID, "");
        username = RSAUtils.decryptBASE64StrLocal(UserIDTemp);
        showLog("---------->");
        showLog(username);

        str.add("巡检任务");
        imageId.add(R.mipmap.icon_xs1);
        colors.add(R.drawable.radius_b1);

        str.add("巡检工作");
        imageId.add(R.mipmap.icon6);
        colors.add(R.drawable.radius_a4);

        str.add("巡检统计");
        imageId.add(R.mipmap.icon13);
        colors.add(R.drawable.radius_b1);

        if(type.equals("YX")){
            setTitle("运行巡检");
//            str.add("缺陷工单");
//            imageId.add(R.mipmap.icon9);
//            colors.add(R.drawable.radius_a2);
        }else if(type.equals("RL")){
            setTitle("燃料巡检");
//            str.add("缺陷工单");
//            imageId.add(R.mipmap.icon9);
//            colors.add(R.drawable.radius_a2);
        }else if(type.equals("BA")){
            setTitle("保安巡检");
        }

        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        StatusBarUtil.transparencyBar(XscbglActivity.this);
        mToolbar.setBackgroundColor(Color.parseColor("#00000000"));
        setBack();

        adapter = new GridViewAdapter(this, getGridViewData(), new ArrayList<Integer>(), true);
        gv.setSelector(new ColorDrawable(Color.TRANSPARENT));
        gv.setAdapter(adapter);
        gv.setOnItemClickListener((adapterView, view, i, l) -> {
            Intent intent = null;
            switch (i) {
                case 0:
                    intent = new Intent(XscbglActivity.this, XjMainActivity.class);
                    intent.putExtra("type",type);
                    break;
                case 1:
                    intent = new Intent(XscbglActivity.this, SxgzActivity.class);
                    intent.putExtra("type",type);
                    break;
                case 2:
                    intent = new Intent(XscbglActivity.this, XJStatisticsActivity.class);//XJStatisticsMyUploadActivity //XJStatisticsActivity
                    intent.putExtra("type",type);
                    break;
            }
            if (intent != null) {
                startActivity(intent);
            }
        });
        IntentFilter filter = new IntentFilter();
        filter.addAction(Contans.ACTION_REFRESHDOWNLOADPLAN);
        //registerReceiver(myReceiver, filter);
        LocalBroadcastManager.getInstance(this).registerReceiver(myReceiver, filter);

        requestDatas();
        if(type.equals("YX")){
            getProfessionData();
        }
    }

    private List<GridViewBean> getGridViewData() {

        List<GridViewBean> datas = new ArrayList<>();
        for (int i = 0; i < str.size(); i++) {
            GridViewBean bean = new GridViewBean();
            bean.setTitle(str.get(i));
            bean.setBackgroup(colors.get(i));
            bean.setImageid(imageId.get(i));
            bean.setShow(false);
            datas.add(bean);
        }
        return datas;
    }

    private void requestDatas() {    //下载巡检数据

        Request<String> requestxs;
        if(type.equals("BA")){Log.i("app",Contans.IP + Contans.BAXJ);
            requestxs = NoHttp.createStringRequest(Contans.IP + Contans.BAXJ, RequestMethod.POST);
        }else{
            requestxs = NoHttp.createStringRequest(Contans.IP + Contans.XSCB, RequestMethod.POST);
        }

        if(type.equals("BA")){
            requestxs.setDefineRequestBodyForJson(createJsonBA());
        }else{
            requestxs.setDefineRequestBodyForJson(createJson());
        }

        NoProgresshttpUtils.getInstance().add(this, 0, requestxs, new HttpListener<String>() {

            @Override
            public void onSucceed(int what, Response<String> response) {

                String result = response.get();
                showLog("----------------");
                showLog(result);
                XjjhList list = GsonToBean(result, XjjhList.class);

                if (list != null) {
//                    for(int i=0;i<list.getData().size();i++){
//                        Xjjh xjjh = list.getData().get(i);
//                        showLog(new Gson().toJson(xjjh));
//                    }

                    if (list.getState().equals("1")) {

                        List<Xjjh> xjjhs = list.getData();//服务器数据
                        DataSupport.deleteAll(Xjjh.class, "download = 0 and username = ?",username);

                        for (Xjjh xjjh : xjjhs) {
                            showLog(new Gson().toJson(xjjh));
                            List<Xjjh> dbxjjh = DataSupport.where("zxid = ? and download = ? and username = ?", xjjh.getZxid(), "1",username).find(Xjjh.class);

                            if (dbxjjh.size() == 0) {
                                xjjh.setUsername(username);
                                xjjh.save();
                            }
                        }
                        //刷新计划下载界面
                        Intent intent = new Intent(Contans.ACTION_REFRESHPLANDOWNLOAD);
                        //发送广播,刷新任务下载页面
                        //sendBroadcast(intent);
                        LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
                    } else {
                        DataSupport.deleteAll(Xjjh.class, "download = 0 and username = ?",username);
                    }
                }
            }

            @Override
            public void onFailed(int what, Response<String> response) {

            }
        });
    }

    //获取运行专业数据
    private void getProfessionData() {

        Log.i("app",Contans.IP + Contans.XSCB);
        final Request<String> requestxs = NoHttp.createStringRequest(Contans.IP + Contans.XSCB, RequestMethod.POST);

        requestxs.setDefineRequestBodyForJson(createJsonZY());

        NoProgresshttpUtils.getInstance().add(this, 0, requestxs, new HttpListener<String>() {

            @Override
            public void onSucceed(int what, Response<String> response) {

                String result = response.get();
                showLog("----------------");
                showLog(result);
                ProfessionList list = GsonToBean(result, ProfessionList.class);

                if (list != null) {
                    //获取数据成功
                    if (list.getState().equals("1")) {
                        //服务器数据
                        List<Profession> professions = list.getData();
                        DataSupport.deleteAll(Profession.class);
                        for (Profession profession : professions) {
                            profession.save();
                        }
                    }
                }
            }

            @Override
            public void onFailed(int what, Response<String> response) {

            }
        });
    }

    private String createJsonBA() {
        XsRequestInfo info = new XsRequestInfo();
        info.setAction("BA_XJGL_RWLB_GET");
        String json = GsonUtils.GsonString(info);
        showLog(json);
        return json;
    }
    private String createJson() {
        XsRequestInfo info = new XsRequestInfo();
        info.setAction("YX_XJGL_RWLB_GET");
//        info.setZymc(Contans.YXCB_ZY_ID);
//        info.setZc((String) SPUtils.get(context, Contans.BZBH, ""));
        if(type!=null&&type.equals("YX")){
            info.setMk("YX");
        }
        if(type!=null&&type.equals("RL")){
            info.setMk("RL");
        }
        String json = GsonUtils.GsonString(info);
        showLog(json);
        return json;
    }

    private String createJsonZY() {
        XsRequestInfo info = new XsRequestInfo();
        info.setAction("YX_XJGL_ZY_GET");
        String jsonZY = GsonUtils.GsonString(info);
        showLog(jsonZY);
        return jsonZY;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //unregisterReceiver(myReceiver);
        // 注销广播接收器
        LocalBroadcastManager.getInstance(this).unregisterReceiver(myReceiver);
    }
}
