package com.ycgis.macall.personalcenter.v.fragment;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.util.Log;
import android.view.View;

import com.google.gson.JsonObject;
import com.rs.macall.androidx.basemodel.base.BaseViewBindFragment;
import com.rs.macall.androidx.basemodel.callback.SimpleListClickListener;
import com.rs.macall.androidx.basemodel.utils.SmartRefreshLayoutHelp;
import com.rs.macall.androidx.basemodel.utils.TypConversion;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.ycgis.macall.personalcenter.R;
import com.ycgis.macall.personalcenter.databinding.FragmentWorkbenchBinding;
import com.ycgis.macall.personalcenter.m.adapterbean.AppBean;
import com.ycgis.macall.personalcenter.m.adapterbean.WorkAppBean;
import com.ycgis.macall.personalcenter.m.enumbean.AppOpenType;
import com.ycgis.macall.personalcenter.m.provider.NativeAppProvider;
import com.ycgis.macall.personalcenter.p.callback.BaseRequestCallback;
import com.ycgis.macall.personalcenter.p.callback.WorkManageCallback;
import com.ycgis.macall.personalcenter.p.request.ApiModel;
import com.ycgis.macall.personalcenter.p.request.RetrofitService;
import com.ycgis.macall.personalcenter.util.ToThirdPartyAppUtils;
import com.ycgis.macall.personalcenter.v.adapter.HomeAppListAdapter;
import com.ycgis.macall.personalcenter.v.adapter.WorkAppListAdapter;

import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

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

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link WorkbenchFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class WorkbenchFragment extends BaseViewBindFragment<FragmentWorkbenchBinding> {
    private HomeAppListAdapter appListAdapter;
    private WorkAppListAdapter customAdapter;
    private ToThirdPartyAppUtils appUtils;
    private WorkbenchManageFragment workbenchManageFragment;
    private NativeAppProvider provider;

    public WorkbenchFragment() {
        // Required empty public constructor
    }

    /**
     * 5*3 =15 *25
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @return A new instance of fragment WorkbenchFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static WorkbenchFragment newInstance() {
        return  new WorkbenchFragment();
    }

    @Override
    protected FragmentWorkbenchBinding getViewBinding() {
        return FragmentWorkbenchBinding.inflate(getLayoutInflater());
    }

    @Override
    protected void lazyLoad() {
        viewBinding.workRefresh.autoRefresh();
    }

    @Override
    protected void readInstanceState(Bundle savedInstanceState) {

    }

    @Override
    protected void initView(View view) {
        viewBinding.workCustomList.setLayoutManager(new GridLayoutManager(getContext(), 4));
        viewBinding.workRecommendedList.setLayoutManager(new GridLayoutManager(getContext(), 4));
        SmartRefreshLayoutHelp.setPullDownToRefresh(getContext(), viewBinding.workRefresh);
    }

    @Override
    protected void startView(View view) {
        viewBinding.contentTitle.setText("工作台");
        viewBinding.workRefresh.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull @NotNull RefreshLayout refreshLayout) {

            }

            @Override
            public void onRefresh(@NonNull @NotNull RefreshLayout refreshLayout) {
                getRecommendedData();
                getCustomData();
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        if (appListAdapter == null){
            viewBinding.workRefresh.autoRefresh();
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        Log.w(TAG, "onStart");
    }

    @Override
    public void onPause() {
        super.onPause();
        baseDismissDialog();
    }


    private void hintTuiJianApp(int type, String msg) {
        List<AppBean> modelList1 = new ArrayList<>();
        AppBean bean = new AppBean();
        bean.setBaseType(type);
        bean.setBaseMessage(msg);
        modelList1.add(bean);
        initRecommendedAppData(modelList1);
    }

    private void getRecommendedData() {
        ApiModel.request(RetrofitService.getBaseInstance().recommendApplication(), new BaseRequestCallback<JsonObject>() {
            @Override
            public void onRequestFailure(String msg) {
                Log.e(TAG, msg);
                viewBinding.workRecommendedList.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
                hintTuiJianApp(-1, msg);
            }

            @Override
            public void onRequestSuccess(JsonObject result) {
                Log.w(TAG, result.toString());
                try {
                    JSONObject object = new JSONObject(result.toString());
                    String code = TypConversion.getJsonStr(object, "code");
                    if (code.equals("20041")) {
                        List<AppBean> modelList1 = new ArrayList<>();
                        JSONObject data = TypConversion.getJSONObject(object, "data");
                        if (data == null) {
                            hintTuiJianApp(0, "暂无应用");
                            return;
                        }
                        JSONArray tjyy = TypConversion.getJSONArray(data, "推荐应用");
                        JSONArray zxyy = TypConversion.getJSONArray(data, "最新应用");
                        if (zxyy != null) {
                            modelList1.addAll(hanAppData(zxyy));
                        }
                        if (tjyy != null) {
                            modelList1.addAll(hanAppData(tjyy));
                        }
                        if (modelList1.isEmpty()) {
                            viewBinding.workRecommendedList.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
                            hintTuiJianApp(0, "暂无应用");
                        } else {
                            AppBean bean = null;
                            if (modelList1.size() >= 12) {
                                bean = modelList1.get(11);
                                bean.setBaseType(1);
                                bean.setAppName("更多应用");
                                bean.setIcon(R.drawable.icon_gd2);
                                bean.setIconUrl("");
                            }
                            viewBinding.workRecommendedList.setLayoutManager(new GridLayoutManager(getContext(), 4));
                            initRecommendedAppData(modelList1);
                        }
                    } else {
                        hintTuiJianApp(-1, TypConversion.getJsonStr(object, "msg"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    viewBinding.workRecommendedList.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
                    hintTuiJianApp(-1, e.getMessage());
                }
            }
        });
    }

    private List<AppBean> hanAppData(JSONArray array) {
        List<AppBean> dataList = new ArrayList<>();
        for (int i = 0; i < array.length(); i++) {
            JSONObject jsonObject = TypConversion.getJSONObject(array, i);
            if (jsonObject == null) continue;
            AppBean bean = new AppBean();
            bean.setBaseType(1);
            bean.setAppName(TypConversion.getJsonStr(jsonObject, "name"));
            bean.setId(TypConversion.getJsonStr(jsonObject, "id"));
            bean.setAppType(TypConversion.getJsonStr(jsonObject, "level"));
            if ("3".equals(bean.getAppType())) {
                bean.setLinkUrl(TypConversion.getJsonStr(jsonObject, "packageName"));
            } else {
                bean.setLinkUrl(TypConversion.getJsonStr(jsonObject, "link"));
            }
            String type = TypConversion.getJsonStr(jsonObject, "type");
            if (type.equals("1")) {
                bean.setNetworkType("Ⅱ类应用");
            } else if (type.equals("2")) {
                bean.setNetworkType("Ⅲ类应用");
            }
            bean.setClientId(TypConversion.getJsonStr(jsonObject, "clientId"));
            bean.setClientSecret(TypConversion.getJsonStr(jsonObject, "clientSecret"));
            bean.setIconUrl(TypConversion.getJsonStr(jsonObject, "icon"));
            bean.setClassification(TypConversion.getJsonStr(jsonObject, "classification"));
            bean.setCompany(TypConversion.getJsonStr(jsonObject, "serviceProvider"));
            bean.setOperationName(TypConversion.getJsonStr(jsonObject, "operationPerson"));
            bean.setOperationPhone(TypConversion.getJsonStr(jsonObject, "phoneNumber"));
            bean.setTime(TypConversion.getJsonStr(jsonObject, "applicationTime"));
            dataList.add(bean);
        }
        return dataList;
    }

    /**
     * 获取本地应用
     */
    private void getCustomData() {
        if (customAdapter == null) {
            if (provider == null) {
                provider = new NativeAppProvider(getContext(), null);
                provider.getSelCustomAppList(new BaseRequestCallback<List<WorkAppBean>>() {
                    @Override
                    public void onRequestFailure(String msg) {
                    }

                    @Override
                    public void onRequestSuccess(List<WorkAppBean> result) {
                        WorkAppBean bean1 = new WorkAppBean();
                        bean1.setBaseType(5);
                        result.add(bean1);
                        initCustomData(result);
                        viewBinding.workRefresh.finishRefresh();
                    }
                });
            }
        } else {
            viewBinding.workRefresh.finishRefresh();
        }
    }

    private WorkManageCallback callback = new WorkManageCallback() {
        @Override
        public void onAdd(WorkAppBean appBean) {
            customAdapter.addItem(customAdapter.getItemCount() - 1, appBean);
            NativeAppProvider.cacheCustomAppList(true, appBean.getPackageName());
        }

        @Override
        public void onRemove(WorkAppBean appBean) {
            NativeAppProvider.cacheCustomAppList(false, appBean.getPackageName());
            List<WorkAppBean> data = customAdapter.getData();
            int position = -1;
            for (int i = 0; i < data.size(); i++) {
                WorkAppBean bean = data.get(i);
                if (appBean.getPackageName().equals(bean.getPackageName())) {
                    position = i;
                    break;
                }
            }
            if (position > -1) {
                data.remove(position);
                customAdapter.notifyItemRemoved(position);
            }
        }
    };

    /**
     * 自定因应用
     * @param dataList
     */
    private void initCustomData(List<WorkAppBean> dataList) {
        if (customAdapter == null) {
            customAdapter = new WorkAppListAdapter(getContext(), dataList);
            viewBinding.workCustomList.setAdapter(customAdapter);
            customAdapter.setListClickListener(new SimpleListClickListener() {
                @Override
                public void onSingleClick(View v, int pointer) {
                    int itemViewType = customAdapter.getItemViewType(pointer);
                    if (itemViewType == 5) {
                        workbenchManageFragment = new WorkbenchManageFragment();
                        workbenchManageFragment.setClickListener(callback);
                        List<WorkAppBean> data = customAdapter.getData();
                        List<String> packageNames = new ArrayList<>();
                        for (int i = 0; i < data.size(); i++) {
                            WorkAppBean bean = data.get(i);
                            if (bean.getBaseType() != 1) {
                                continue;
                            }
                            packageNames.add(bean.getPackageName());
                        }
                        workbenchManageFragment.setSelectPackageNames(packageNames);
                        workbenchManageFragment.show(getFragmentManager(), "WorkbenchManageFragment");
                        return;
                    }
                    if (appUtils == null) {
                        appUtils = new ToThirdPartyAppUtils(getContext());
                    }
                    WorkAppBean dataItem = customAdapter.getDataItem(pointer);
                    AppBean bean = new AppBean();
                    bean.setAppType("3");
                    bean.setLinkUrl(dataItem.getPackageName());
                    appUtils.skipLevel(bean, AppOpenType.LOGIN);
                }
            });
        } else {
            customAdapter.upData(dataList);
        }
    }


    /**
     * 推荐应用
     * @param dataList
     */
    private void initRecommendedAppData(List<AppBean> dataList) {
        if (appListAdapter == null) {
            appListAdapter = new HomeAppListAdapter(getContext(), dataList);
            viewBinding.workRecommendedList.setAdapter(appListAdapter);
            appListAdapter.setListClickListener(new SimpleListClickListener() {
                @Override
                public void onSingleClick(View v, int pointer) {
                    if (appUtils == null) {
                        appUtils = new ToThirdPartyAppUtils(getContext());
                        getLifecycle().addObserver(appUtils);
                    }
                    baseShowDialong("正在打开应用，请稍后...");
                    appUtils.skipApp(appListAdapter.getDataItem(pointer));

                }
            });
        } else {
            appListAdapter.upData(dataList);
        }
    }

}