package com.rehome.sgbaxj.activity.regular;


import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.rehome.sgbaxj.DBModel.Dqgz;
import com.rehome.sgbaxj.R;
import com.rehome.sgbaxj.adapter.DqgzDownloadAdapter;
import com.rehome.sgbaxj.base.BaseFragment;
import com.rehome.sgbaxj.bean.XsRequestInfo;
import com.rehome.sgbaxj.contans.Contans;
import com.rehome.sgbaxj.utils.GsonUtils;
import com.rehome.sgbaxj.utils.SPUtils;
import com.rehome.sgbaxj.weight.WaitDialog;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.rest.RequestQueue;

import org.litepal.crud.DataSupport;

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

import androidx.appcompat.app.AlertDialog;

import static org.litepal.crud.DataSupport.where;

/**
 * Created by huang on 2021/12/09
 * 定期工作-任务下载
 */

public class DqgzDownFragment extends BaseFragment {

    ListView lv;
    TextView tvNodata;
    FrameLayout FL;
    Button btnXz;
    Button btnDelete;
    LinearLayout LL;


    private WaitDialog dialog;
    private DqgzUpAndDownActivity mActivity;
    private View headView;
    private View head;
    private DqgzDownloadAdapter adapter;
    private CheckBox cb;
    private List<Dqgz> xjjhs;
//    private int selectCount = 0;
//    private int requestCount = 0;
    private List<String> zxids = new ArrayList<>();
    private List<String> jhmcs = new ArrayList<>();
    private RequestQueue queue;
    private String type = null;
    private String professionId = null;
    private  String username;

    private BroadcastReceiver myReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (Contans.ACTION_REFRESHPLANDOWNLOAD.equals(action)) {
                //刷新页面
                initData();
            }
            if(Contans.ACTION_PROFESSIONCHANGE.equals(action)){
                professionId=intent.getStringExtra("professionId");
                Log.i("app",professionId);
                Log.i("app","initData");
                //刷新页面
                initData();
            }
        }
    };

    public DqgzDownFragment() {

    }
    public DqgzDownFragment(String type) {
        this.type=type;
    }

    public static DqgzDownFragment newInstance(String type) {
        DqgzDownFragment fragment = new DqgzDownFragment(type);
        return fragment;
    }


    @Override
    public int getContentViewId() {
        return R.layout.fragment_xzxsjh;
    }

    @Override
    protected void initView() {
        lv = view.findViewById(R.id.lv);
        tvNodata = view.findViewById(R.id.tv_nodata);
        FL = view.findViewById(R.id.FL);
        btnXz = view.findViewById(R.id.btn_xz);
        btnDelete = view.findViewById(R.id.btn_delete);
        LL = view.findViewById(R.id.LL);


        username = (String) SPUtils.get(context, Contans.USERID, "");
        lv.setEmptyView(tvNodata);
        mActivity = (DqgzUpAndDownActivity) getActivity();
        headView = View.inflate(context, R.layout.xzxsjh_item, null);
        head = headView.findViewById(R.id.head);
        head.setVisibility(View.VISIBLE);

        btnXz.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (xjjhs.size() != 0) {
                    zxids.clear();
                    jhmcs.clear();
                    for (int i = 0; i < xjjhs.size(); i++) {
                        if (xjjhs.get(i).isChecked()) {
                            if (!dialog.isShowing()) {
                                dialog.setMessage("下载计划中...");
                                dialog.show();
                            }
                            //运行，燃料定时任务下载
                            downData(xjjhs.get(i).getRWID());
                            zxids.add(xjjhs.get(i).getRWID());
                        }
                    }
                    if (dialog != null && dialog.isShowing()) {
                        dialog.dismiss();
                    }

                    tvNodata.setText("暂无数据");
                    List<Dqgz> xjjhListall = new ArrayList<>();
                    if(professionId!=null){
                        xjjhListall = where("download = ? and mkbs = ? and zx_zy = ? and username = ?", "0",type,professionId,username).find(Dqgz.class);
                    }else{
                        xjjhListall = where("download = ? and mkbs = ? and username = ?", "0",type,username).find(Dqgz.class);
                    }

                    xjjhs.clear();
                    xjjhs.addAll(xjjhListall);
                    if (adapter != null) {
                        cb.setChecked(false);
                        adapter.notifyDataSetChanged();
                    }
                    showToast("下载成功");

                    Intent intent = new Intent(Contans.ACTION_REFRESHPLANUPLOAD);
                    //发送广播,刷新任务上传页面
                    requireActivity().sendBroadcast(intent);
                } else {
                    showToast("没有可下载计划");
                }
            }
        });

        btnDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (xjjhs.size() != 0) {

                    AlertDialog.Builder builder = new AlertDialog.Builder(context);
                    builder.setTitle("提示");
                    builder.setTitle("你确定要删除？");
                    builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
                    builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            List<Dqgz> delete = new ArrayList<>();
                            for (int i = 0; i < xjjhs.size(); i++) {
                                if (xjjhs.get(i).isChecked()) {
                                    delete.add(xjjhs.get(i));
                                    DataSupport.deleteAll(Dqgz.class, "rwid = ? and username = ?", xjjhs.get(i).getRWID(),username);
                                }
                            }
                            xjjhs.removeAll(delete);
                            adapter.notifyDataSetChanged();
                        }
                    });
                    builder.show();

                } else {
                    showToast("没有可删除计划");
                }
            }
        });


        cb = headView.findViewById(R.id.cb);
        cb.setOnClickListener(view -> {

            if (cb.isChecked()) {
                for (int i = 0; i < xjjhs.size(); i++) {
                    xjjhs.get(i).setChecked(true);
                    adapter.notifyDataSetChanged();
                }
            } else {
                for (int i = 0; i < xjjhs.size(); i++) {
                    xjjhs.get(i).setChecked(false);
                    adapter.notifyDataSetChanged();
                }
            }
        });
        lv.addHeaderView(headView, null, false);
        TextView tv_taskName=headView.findViewById(R.id.tv_gwmc);
        tv_taskName.setText("任务名称");
        TextView tv_isCheck=headView.findViewById(R.id.tv_gwds);
        tv_isCheck.setText("状态");
        IntentFilter filter = new IntentFilter();
        filter.addAction(Contans.ACTION_REFRESHPLANDOWNLOAD);
        filter.addAction(Contans.ACTION_PROFESSIONCHANGE);
        DqgzDownFragment.this.requireActivity().registerReceiver(myReceiver, filter);
    }

    public void initData() {

        queue = NoHttp.newRequestQueue(1);
        dialog = new WaitDialog(getActivity(), "加载中...");
        dialog.setCancelable(false);
        cb.setChecked(false);
        xjjhs = new ArrayList<>();
        //如果数据库中有数据
        if (DataSupport.count("Dqgz") != 0) {
            List<Dqgz> xjjhListall = new ArrayList<>();
            if(professionId!=null){
                xjjhListall = where("download = ? and mkbs = ? and zx_zy = ? and username = ?", "0",type,professionId,username).find(Dqgz.class);
            }else{
                xjjhListall = where("download = ? and mkbs = ? and username = ?", "0",type,username).find(Dqgz.class);
            }

            xjjhs.clear();
            xjjhs.addAll(xjjhListall);
            Log.i("app","-------");
            Log.i("app",String.valueOf(xjjhs.size()));
            setListData();
        } else {
            tvNodata.setText("暂无数据");
            LL.setVisibility(View.GONE);
        }
    }

    //运行，燃料计划下载
    private void downData(String rwid) {
        //++requestCount;
        ContentValues values = new ContentValues();
        values.put("download", 1);
        DataSupport.updateAll(Dqgz.class, values, "rwid = ?", rwid);
    }

    private String createZyJson(String zxid, String jhmc) {
        XsRequestInfo info = new XsRequestInfo();
        info.setAction("YX_XJGL_RWXZ_GET");
        info.setZxid(zxid);
        //info.setJhmc(jhmc);
        String json = GsonUtils.GsonString(info);
        Log.i("app",json);
        return json;
    }

    private void setListData() {

        adapter = new DqgzDownloadAdapter(context, xjjhs, new DqgzDownloadAdapter.CallBack() {
            @Override
            public void Click(View view) {

                CheckBox checkBox = (CheckBox) view;
                int index = (int) checkBox.getTag();
                xjjhs.get(index).setChecked(checkBox.isChecked());
                int count = 0;
                for (int a = 0; a < xjjhs.size(); a++) {
                    if (xjjhs.get(a).isChecked()) {
                        count++;
                    }
                }
                cb.setChecked(count == xjjhs.size());
                adapter.notifyDataSetChanged();
            }
        });


        lv.setAdapter(adapter);

        lv.setOnItemClickListener((adapterView, view, i, l) -> {

            xjjhs.get(i - 1).setChecked(!xjjhs.get(i - 1).isChecked());
            int count = 0;
            for (int a = 0; a < xjjhs.size(); a++) {
                if (xjjhs.get(a).isChecked()) {
                    count++;
                }
            }
            cb.setChecked(count == xjjhs.size());
            adapter.notifyDataSetChanged();
        });
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        DqgzDownFragment.this.requireActivity().unregisterReceiver(myReceiver);
    }
}
