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

import android.app.Dialog;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.graphics.Point;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.android.material.bottomsheet.BottomSheetDialogFragment;
import com.rs.macall.androidx.basemodel.callback.BaseRecycleBtnClickListener;
import com.rs.macall.androidx.basemodel.decoration.MyDividerItemDecoration;
import com.rs.macall.androidx.basemodel.utils.DimensionConvert;
import com.rs.macall.androidx.basemodel.utils.LogUtils;
import com.rs.macall.androidx.basemodel.utils.SmartRefreshLayoutHelp;
import com.rs.macall.androidx.basemodel.utils.ToastUtil;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.ycgis.macall.personalcenter.R;
import com.ycgis.macall.personalcenter.databinding.FragmentWorkbenchAddBinding;
import com.ycgis.macall.personalcenter.m.adapterbean.AppInfoBean;
import com.ycgis.macall.personalcenter.m.adapterbean.WorkAppBean;
import com.ycgis.macall.personalcenter.m.provider.NativeAppProvider;
import com.ycgis.macall.personalcenter.m.requestbean.AppInfoModel;
import com.ycgis.macall.personalcenter.m.requestbean.BaseRequestModel;
import com.ycgis.macall.personalcenter.p.callback.BaseRequestCallback;
import com.ycgis.macall.personalcenter.p.callback.OnFragmentOnClickListener;
import com.ycgis.macall.personalcenter.p.callback.WorkManageCallback;
import com.ycgis.macall.personalcenter.p.request.ApiModel;
import com.ycgis.macall.personalcenter.p.request.CommonCompositeManage;
import com.ycgis.macall.personalcenter.p.request.RetrofitService;
import com.ycgis.macall.personalcenter.v.adapter.WorkCustomAppAdapter;

import org.jetbrains.annotations.NotNull;

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

/**
 * created by:   Macall
 * create time:  2023/11/2 14:14
 * copyright:    @ruansee.com
 * Describe:
 */
public class WorkbenchManageFragment extends BottomSheetDialogFragment {
    private FragmentWorkbenchAddBinding binding;
    private WorkCustomAppAdapter appAdapter;
    private WorkManageCallback clickListener;
    private List<String> selectPackageNames;
    private List<AppInfoBean> serverData;
    private List<WorkAppBean> addressData;

    public WorkbenchManageFragment() {
    }

    public void setClickListener(WorkManageCallback clickListener) {
        this.clickListener = clickListener;
    }

    public void setSelectPackageNames(List<String> selectPackageNames) {
        this.selectPackageNames = selectPackageNames;
    }

    @Override
    public void onCreate(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(STYLE_NORMAL, R.style.BottomSheetDialog);
    }

    @Nullable
    @org.jetbrains.annotations.Nullable
    @Override
    public View onCreateView(@NonNull @NotNull LayoutInflater inflater, @Nullable @org.jetbrains.annotations.Nullable ViewGroup container, @Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        binding = FragmentWorkbenchAddBinding.inflate(getLayoutInflater());
        init();
        return binding.getRoot();
    }

    private void init() {
        SmartRefreshLayoutHelp.setPullDownToRefresh(getContext(), binding.workSrlAppList);
        binding.workSrlAppList.setOnRefreshListener(refreshLayout -> getAppList());
        binding.workRvAppListAll.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
        MyDividerItemDecoration myDividerItemDecoration = new MyDividerItemDecoration(getContext(), LinearLayoutManager.VERTICAL, 5);
        myDividerItemDecoration.setBackground(R.color.colorGrey2);
        binding.workRvAppListAll.addItemDecoration(myDividerItemDecoration);
        getAppCenterData();
    }

    private void getAppList() {
        List<WorkAppBean> dataList = new ArrayList<>();
        WorkAppBean bean = new WorkAppBean();
        bean.setBaseType(0);
        bean.setBaseMessage("");
        dataList.add(bean);
        initData(dataList);
        NativeAppProvider nativeAppProvider = new NativeAppProvider(getContext(), selectPackageNames);
        nativeAppProvider.asyncCheckInstallApps(new BaseRequestCallback<List<WorkAppBean>>() {
            @Override
            public void onRequestFailure(String msg) {

            }

            @Override
            public void onRequestSuccess(List<WorkAppBean> result) {
                addressData = result;
                hanData();
            }
        });
    }

    private void hanData() {
        if (addressData == null) return;
        if (serverData == null) return;
        List<WorkAppBean> result = new ArrayList<>();
        for (int i = 0; i < addressData.size(); i++) {
            WorkAppBean bean = addressData.get(i);
            for (AppInfoBean b : serverData) {
                //bean.getAppName().equals(b.getName()) &&
                if ( bean.getPackageName().equals(b.getPackageName())) {
                    result.add(bean);
                    break;
                }
            }
        }
        initData(result);
        binding.workSrlAppList.finishRefresh();
    }

    private void initData(List<WorkAppBean> dataList) {
        if (appAdapter == null) {
            appAdapter = new WorkCustomAppAdapter(getContext(), dataList);
            binding.workRvAppListAll.setAdapter(appAdapter);
            appAdapter.setBtnClickListener(new BaseRecycleBtnClickListener() {
                @Override
                public void onSingleClick(View v, int position, int what, Object msg) {
                    WorkAppBean dataItem = appAdapter.getDataItem(position);
                    if (what == 1) {
                        clickListener.onAdd(dataItem);
                        dataItem.setAdd(true);
                    } else {
                        clickListener.onRemove(dataItem);
                        dataItem.setAdd(false);
                    }
                    appAdapter.notifyItemChanged(position, 5);
                }
            });
        } else {
            appAdapter.upData(dataList);
        }
    }

    /**
     * 获取应用中心应用
     */
    private void getAppCenterData() {
        ApiModel.request("getApplicationCenterData",
                RetrofitService.getBaseInstance().applicationList(null, null, 1),
                new BaseRequestCallback<BaseRequestModel<List<AppInfoBean>>>() {
                    @Override
                    public void onRequestFailure(String msg) {
//                        LogUtils.e("获取应用", msg);
                        ToastUtil.centered(getContext(),msg);
                        List<WorkAppBean> dataList = new ArrayList<>();
                        WorkAppBean bean = new WorkAppBean();
                        bean.setBaseType(-1);
                        bean.setBaseMessage(msg);
                        dataList.add(bean);
                        initData(dataList);
                        binding.workSrlAppList.finishRefresh();
                    }

                    @Override
                    public void onRequestSuccess(BaseRequestModel<List<AppInfoBean>> result) {
//                        LogUtils.e("获取应用", result.toString());
                        if (result.getCode() == 20041) {
                            serverData = result.getData();
                            hanData();
                        }else {
                            ToastUtil.centered(getContext(),result.getMsg());
                            List<WorkAppBean> dataList = new ArrayList<>();
                            WorkAppBean bean = new WorkAppBean();
                            bean.setBaseType(-1);
                            bean.setBaseMessage(result.getMsg());
                            dataList.add(bean);
                            initData(dataList);
                            binding.workSrlAppList.finishRefresh();
                        }
                    }
                });
    }

    @Override
    public void onStart() {
        super.onStart();
        // 设置软键盘不自动弹出
        getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        BottomSheetDialog dialog = (BottomSheetDialog) getDialog();
        FrameLayout bottomSheet = dialog.getDelegate().findViewById(R.id.design_bottom_sheet);
        if (bottomSheet != null) {
            CoordinatorLayout.LayoutParams layoutParams = (CoordinatorLayout.LayoutParams) bottomSheet.getLayoutParams();
            layoutParams.height = getHeight();
            BottomSheetBehavior<FrameLayout> from = BottomSheetBehavior.from(bottomSheet);
//            behavior = BottomSheetBehavior.from(bottomSheet);
            // 初始为展开状态
            from.setState(BottomSheetBehavior.STATE_EXPANDED);
        }
        binding.workSrlAppList.autoRefresh();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        CommonCompositeManage.getInstance().unDisposable("getApplicationCenterData");

    }

    /**
     * 获取屏幕高度
     *
     * @return height
     */
    private int getHeight() {
        int height = 1920;
        if (getContext() != null) {
            WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
            Point point = new Point();
            if (wm != null) {
                // 使用Point已经减去了状态栏高度
                wm.getDefaultDisplay().getSize(point);
                height = point.y - DimensionConvert.dip2px(getContext(), 68);
            }
        }
        return height;
    }


}
