package com.sipai.jspatrol.Patrol;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.gigamole.navigationtabstrip.NavigationTabStrip;
import com.sipai.jspatrol.Bean.Biz;
import com.sipai.jspatrol.Bean.Patrol;
import com.sipai.jspatrol.Bean.PatrolLocation;
import com.sipai.jspatrol.Bean.PatrolModel;
import com.sipai.jspatrol.R;
import com.sipai.jspatrol.URL.GuideMenuUrl;
import com.sipai.jspatrol.URL.MethodURL;
import com.sipai.jspatrol.Webv.GuideMenuLandscapeActivity;
import com.sipai.jspatrol.utils.OKHttpUtils;
import com.sipai.ui.EmptyLayout;
import com.sipai.ui.bizPopWindow.CustomListPopupWindow;

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

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;
import q.rorbin.badgeview.QBadgeView;

public class ProPatrolTaskListActivity extends AppCompatActivity implements View.OnClickListener, CustomListPopupWindow.ItemClickCallBack {
    private TextView tv_daily,tv_tem,tv_area;
    private NavigationTabStrip tab_task;
    private SwipeRefreshLayout refresh_layout;
    private RecyclerView rc_view;
    private List<Patrol> daily_patrols = new ArrayList<>();
    private List<Patrol> daily_temp = new ArrayList<>();
    private List<Patrol> daily_temp_undo = new ArrayList<>();
    private ProPatrolTaskAdapter adapter;
    private LinearLayoutManager manager;
    private String model="0";//0为日常，1为临时
    private QBadgeView bv_task;
    private EmptyLayout emptyLayout;
    private String mCheckedUId="";
    private Context mContext;
    private List<Biz> areas = new ArrayList<>();
    CustomListPopupWindow mPopupWindow;
    private CustomListPopupWindow.ItemClickCallBack mCallBack;
    //巡检类型
    private String patrolType;//Product("P","生产巡检"), Equipment( "E","设备巡检"), Administrator("A","管理组"),Maintenance("M","运维组");
    private static final int GPS_REQUEST_CODE = 101;
    private String[] permissions = { Manifest.permission.ACCESS_COARSE_LOCATION};
    List<String> mPermissionList = new ArrayList<>();
    private final int mRequestCode = 100;//权限请求码

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pro_patrol_task_list);
        mCallBack=this;
        mContext=this;
        init();
        initView();
        checkLocPs();
        if (!isOpenGPS()){
            openGPS();
        }
    }

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

    private void checkLocPs() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            for (int i = 0; i < permissions.length; i++) {
                if (ContextCompat.checkSelfPermission(this, permissions[i]) != PackageManager.PERMISSION_GRANTED) {
                    mPermissionList.add(permissions[i]);//添加还未授予的权限
                }
            }
            // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
            if (mPermissionList.size() > 0) {
                // 如果没有授予该权限，就去提示用户请求
                ActivityCompat.requestPermissions(this, permissions, mRequestCode);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        boolean hasPermissionDismiss = false;//有权限没有通过
        if (mRequestCode == requestCode) {
            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults[i] == -1) {
                    hasPermissionDismiss = true;
                }
            }
            if (hasPermissionDismiss) {
                // 用户还是想用我的 APP 的
                // 提示用户去应用设置界面手动开启权限
                showDialogTipUserGoToAppSettting();
            }
        }
    }

    // 提示用户去应用设置界面手动开启权限

    private void showDialogTipUserGoToAppSettting() {
        new SweetAlertDialog(ProPatrolTaskListActivity.this, SweetAlertDialog.WARNING_TYPE)
                .setTitleText("位置信息权限不可用")
                .setContentText("请在-应用设置-权限中，点击允许")
                .setConfirmText("确定")
                .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                        sweetAlertDialog.dismissWithAnimation();
                        goToAppSetting();
                    }
                }).show();
    }

    // 跳转到当前应用的设置界面
    private void goToAppSetting() {
        Intent intent = new Intent();

        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", getPackageName(), null);
        intent.setData(uri);

        startActivityForResult(intent, 123);
    }

    private void openGPS() {
        new SweetAlertDialog(ProPatrolTaskListActivity.this,SweetAlertDialog.WARNING_TYPE)
                .setTitleText("提示")
                .setContentText("检测到未开启GPS定位功能，请开启，否则将无法进行巡检操作！")
                .setConfirmText("开启")
                .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                        sweetAlertDialog.dismissWithAnimation();
                        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        startActivityForResult(intent,GPS_REQUEST_CODE);
                    }
                }).setCancelText("取消")
                .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                        sweetAlertDialog.dismissWithAnimation();
                        finish();
                    }
                }).show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
//        if (requestCode == GPS_REQUEST_CODE){
        checkLocPs();
        if (!isOpenGPS()){
            openGPS();
        }
//        }
    }

    private Boolean isOpenGPS() {
        LocationManager locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
        boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        boolean net = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (gps||net){
            return true;
        }
        return false;
    }


    /**
     * 初始化
     */
    private String mServer;
    private String mUserid;
    private String mBizid;
    private String mUsername;
    private String mPassword;
    private String mCaption;
    private String mGroup;
    private String role;
    private String mGroup_com;
    private String mGroup_equ;
    private String mGroup_sludge;
    private String mAreaId = "";
    private String mAreaName = "";
    private String st_area;
    private String token;
    public void init(){
//        List<PatrolLocation> locations = LitePal.findAll(PatrolLocation.class);
        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", "");
        mAreaId = sharedPre.getString("areaid","");
        mAreaName = sharedPre.getString("areaname","");
        st_area = sharedPre.getString("arealist","");
        patrolType = sharedPre.getString("patrolTypeId","");
        token = sharedPre.getString("token","");
        areas = parseAreas(st_area);
    }

    private List<Biz> parseAreas(String response) {
        List<Biz> listres = new ArrayList<Biz>();
        try{
            JSONObject jsonObject = new JSONObject(response);
            JSONArray  aNews =  new JSONArray(jsonObject.optString("rows"));
            if(aNews!=null && aNews.length()>0){
                for(int i=0;i<aNews.length();i++){
                    Biz item=new Biz();
                    item.setId(aNews.getJSONObject(i).get("id").toString());
                    item.setName(aNews.getJSONObject(i).get("name").toString());
                    item.setBizid(aNews.getJSONObject(i).get("id").toString());
                    listres.add(item);
                }
            }
        }catch(JSONException ex){
            Log.e("JSON Error: ", ex.toString());
        }

        return listres;
    }

    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();
            }
        });
        tv_area = findViewById(R.id.moudle_back_title_tv_save);
        tv_area.setText("巡检记录");
        tv_area.setOnClickListener(this);
//        if (mAreaName!=null&&!mAreaName.isEmpty()){
//            tv_area.setText(mAreaName);
//        }
        tv_daily = findViewById(R.id.moudle_pro_patrol_task_tv_daily);
        tv_daily.setOnClickListener(this);
        tv_tem = findViewById(R.id.moudle_pro_patrol_task_tv_tem);
        tv_tem.setOnClickListener(this);
        tab_task = findViewById(R.id.moudle_pro_patrol_task_tab);
        tab_task.setTitles("日常","无","临时");
        tab_task.setTabIndex(0);
        tab_task.setSelected(false);
        rc_view = findViewById(R.id.moudle_pro_patrol_task_rc);
        adapter = new ProPatrolTaskAdapter(daily_patrols,ProPatrolTaskListActivity.this);
        rc_view.setAdapter(adapter);
        manager = new LinearLayoutManager(ProPatrolTaskListActivity.this);
        rc_view.setLayoutManager(manager);
        refresh_layout = findViewById(R.id.moudle_pro_patrol_task_refresh);
        refresh_layout.setColorSchemeResources(R.color.blue);
        refresh_layout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getPatrolTask();
            }
        });
        emptyLayout = findViewById(R.id.moudle_pro_patrol_task_list_ui_empty);
        bv_task = new QBadgeView(ProPatrolTaskListActivity.this);
        bv_task.setBadgeGravity(Gravity.END | Gravity.TOP).setBadgeTextColor(Color.WHITE);//文字透明色
        bv_task.setGravityOffset(25,1,true);
        bv_task.bindTarget(tv_tem);
        changeColor(tv_daily,0);
//        getPatrolTask();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.moudle_pro_patrol_task_tv_daily:
                changeColor(tv_daily,0);
                model = "0";
                getPatrolTask();
                break;
            case R.id.moudle_pro_patrol_task_tv_tem:
                changeColor(tv_tem,1);
                model = "1";
                getPatrolTask();
                break;
            case R.id.moudle_back_title_tv_save:
                GuideMenuLandscapeActivity.actionStart(ProPatrolTaskListActivity.this, GuideMenuUrl.url_patrol_record+"?unitId="+mBizid, GuideMenuUrl.name_patrol_record);
//                mPopupWindow=new CustomListPopupWindow(mContext, areas,mCheckedUId, mCallBack);
//                mPopupWindow.showAsDropDown(tv_area);
                break;
        }
    }

    private void getPatrolTask() {
        HashMap<String,String> map = new HashMap<>();
        map.put("unitId",mBizid);
        map.put("userIds",mUserid);
        map.put("bizid",mBizid);
        map.put("type","P");
        OKHttpUtils.OKCallGet(map, mServer, MethodURL.GetPatrolList_Method).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                hideRefresh();
                showToast("失败：" + e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                if (!res.contains("fail")) {
                    daily_patrols = getDailyPatrols(res);
                    updateList();
                }else {
                    ErrorDialog();
                }
            }
        });
    }

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

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

    private void ErrorDialog() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                refresh_layout.setRefreshing(false);
                rc_view.setVisibility(View.GONE);
                emptyLayout.setVisibility(View.VISIBLE);
            }
        });
    }

    private void updateList() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                refresh_layout.setRefreshing(false);
                bv_task.setBadgeNumber(daily_temp_undo.size());
                if (model.equals("0")) {
                    adapter = new ProPatrolTaskAdapter(daily_patrols, ProPatrolTaskListActivity.this);
                    if (daily_patrols.size()==0){
                        emptyLayout.setVisibility(View.VISIBLE);
                        rc_view.setVisibility(View.GONE);
                    }else {
                        emptyLayout.setVisibility(View.GONE);
                        rc_view.setVisibility(View.VISIBLE);
                    }
                }else if (model.equals("1")){
                    adapter = new ProPatrolTaskAdapter(daily_temp, ProPatrolTaskListActivity.this);
                    if (daily_temp.size()==0){
                        emptyLayout.setVisibility(View.VISIBLE);
                        rc_view.setVisibility(View.GONE);
                    }else {
                        emptyLayout.setVisibility(View.GONE);
                        rc_view.setVisibility(View.VISIBLE);
                    }
                }
                rc_view.setAdapter(adapter);
//                manager = new LinearLayoutManager(ProPatrolTaskListActivity.this);
//                rc_view.setLayoutManager(manager);
            }
        });
    }

    private List<Patrol> getDailyPatrols(String response) {
        daily_temp = new ArrayList<>();
        daily_temp_undo = new ArrayList<>();
        List<Patrol> list = new ArrayList<>();
        List<Patrol> list_done = new ArrayList<>();
        List<Patrol> list_undo = new ArrayList<>();
        try {
            JSONObject jsonObject = new JSONObject(response);
            JSONArray arry = new JSONArray(jsonObject.optString("content1"));
            for (int i=0;i<arry.length();i++){
                Patrol patrol = new Patrol();
                patrol.setActFinishTime(arry.getJSONObject(i).optString("actFinishTime"));
                patrol.setBizid(arry.getJSONObject(i).optString("bizId").toString());
                patrol.setContent(arry.getJSONObject(i).optString("content").toString());
                patrol.setEndTime(arry.getJSONObject(i).optString("endTime").toString());
                patrol.setSid(arry.getJSONObject(i).optString("id").toString());
                patrol.setName(arry.getJSONObject(i).optString("name").toString());
                patrol.setPatrolArea(arry.getJSONObject(i).optString("patrolArea").toString());
                patrol.setPatrolAreaId(arry.getJSONObject(i).optString("patrolAreaId").toString());
                patrol.setPatrolModelId(arry.getJSONObject(i).optString("patrolModelId").toString());
                patrol.setPatrolPlanId(arry.getJSONObject(i).optString("patrolPlanId").toString());
                patrol.setStartTime(arry.getJSONObject(i).optString("startTime").toString());
                patrol.setStatus(arry.getJSONObject(i).optString("status").toString());
                patrol.setType(arry.getJSONObject(i).optString("type").toString());
                patrol.setWorkResult(arry.getJSONObject(i).optString("workResult").toString());
                if (!arry.getJSONObject(i).optString("worker").equals("null")&&!arry.getJSONObject(i).optString("worker").isEmpty()){
                    JSONObject js = arry.getJSONObject(i).getJSONObject("worker");
                    patrol.setWorker(js.optString("caption"));
                }
                patrol.setWorkerId(arry.getJSONObject(i).optString("workerId").toString());
                patrol.setPatrolType(arry.getJSONObject(i).optString("type").toString());
                PatrolModel patrolModel = new PatrolModel();
                if (arry.getJSONObject(i).optString("patrolModel")!=null&&!arry.getJSONObject(i).optString("patrolModel").toString().equals("null")) {
                    JSONObject js = new JSONObject(arry.getJSONObject(i).optString("patrolModel").toString());
                    patrolModel.setSid(js.optString("id").toString());
                    patrolModel.setActive(js.optString("active").toString());
                    patrolModel.setBizId(js.optString("bizId").toString());
                    patrolModel.setDefaultFlag(js.optString("defaultFlag").toString());
                    patrolModel.setName(js.optString("name").toString());
                    patrolModel.setType(js.optString("type").toString());
                    patrolModel.setWhere(js.optString("where").toString());
                    patrol.setPatrolModel(patrolModel);
                }else {
                    patrolModel.setSid("");
                    patrolModel.setActive("");
                    patrolModel.setBizId("");
                    patrolModel.setDefaultFlag("");
                    patrolModel.setName("");
                    patrolModel.setType("");
                    patrolModel.setWhere("");
                    patrol.setPatrolModel(patrolModel);
                }
                if (mAreaId.equals(patrol.getPatrolAreaId())||mAreaId==null||mAreaId.equals("")) {
                    if (patrol.getPatrolModelId().equals("temp")) {
                        if (!patrol.getStatus().equals("3")) {
                            daily_temp_undo.add(patrol);
                        }
                        daily_temp.add(patrol);

                    } else {
                        if (!patrol.getStatus().equals("3")) {
                            list_undo.add(patrol);
                        }else {
                            list_done.add(patrol);
                        }
                    }
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        list.addAll(list_undo);
        list.addAll(list_done);
        return list;
    }

    private void changeColor(TextView tv, int i) {
        tv_daily.setTextColor(getResources().getColor(R.color.pro_task_tab_unsel));
        tv_tem.setTextColor(getResources().getColor(R.color.pro_task_tab_unsel));
        tv.setTextColor(getResources().getColor(R.color.pro_task_tab_sel));
        if (i==0) {
            tab_task.setTabIndex(i);
        }else {
            tab_task.setTabIndex(2);
        }
    }

    @Override
    public void callBack(Biz biz) {
        mCheckedUId=biz.getId();
        final String name = biz.getName();
        saveArea(ProPatrolTaskListActivity.this,mCheckedUId,name);
        getPatrolTask();
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                tv_area.setText(name);
                mPopupWindow.dismiss();
            }
        });
    }

    private void saveArea(ProPatrolTaskListActivity context, String mCheckedUId, String name) {
        SharedPreferences sharedPre=context.getSharedPreferences("config", MODE_PRIVATE);
        SharedPreferences.Editor editor=sharedPre.edit();
        editor.putString("areaid", mCheckedUId);
        editor.putString("areaname",name);
        editor.commit();
        init();
    }
}
