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

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.os.Environment;
import android.provider.MediaStore;
import android.text.Html;
import android.view.View;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.king.zxing.CameraScan;
import com.rs.macall.androidx.basemodel.base.BaseViewBindFragment;
import com.rs.macall.androidx.basemodel.callback.CustomClickListener;
import com.rs.macall.androidx.basemodel.callback.SimpleListClickListener;
import com.rs.macall.androidx.basemodel.utils.DateUitls;
import com.rs.macall.androidx.basemodel.utils.ToastUtil;
import com.ycgis.macall.personalcenter.R;
import com.ycgis.macall.personalcenter.databinding.FragmentHome2Binding;
import com.ycgis.macall.personalcenter.m.adapterbean.AppBean;
import com.ycgis.macall.personalcenter.m.adapterbean.HomeMessageBean;
import com.ycgis.macall.personalcenter.m.adapterbean.MessageBean;
import com.ycgis.macall.personalcenter.m.enumbean.AppOpenType;
import com.ycgis.macall.personalcenter.m.event.MessageEvent;
import com.ycgis.macall.personalcenter.p.app.RuanseeApplication;
import com.ycgis.macall.personalcenter.p.callback.ImageCallBack;
import com.ycgis.macall.personalcenter.p.callback.OnFragmentOnClickListener;
import com.ycgis.macall.personalcenter.p.request.LoadPhotoImage;
import com.ycgis.macall.personalcenter.util.ToThirdPartyAppUtils;
import com.ycgis.macall.personalcenter.v.activity.MainActivity;
import com.ycgis.macall.personalcenter.v.activity.MyDetailsActivity;
import com.ycgis.macall.personalcenter.v.activity.ScanCodeActivity;
import com.ycgis.macall.personalcenter.v.activity.WorkbenchCenterActivity;
import com.ycgis.macall.personalcenter.v.activity.applyfo.ApplyForMainActivity;
import com.ycgis.macall.personalcenter.v.activity.travel.TravelAssistantActivity;
import com.ycgis.macall.personalcenter.v.adapter.HomeAppListAdapter;
import com.ycgis.macall.personalcenter.v.adapter.MessageAdapter;
import com.ycgis.macall.personalcenter.v.viewmodel.HomeViewModel;
import com.youth.banner.adapter.BannerImageAdapter;
import com.youth.banner.holder.BannerImageHolder;
import com.youth.banner.indicator.RectangleIndicator;
import com.youth.banner.transformer.AlphaPageTransformer;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

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

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link Home2Fragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class Home2Fragment extends BaseViewBindFragment<FragmentHome2Binding> {
    private HomeAppListAdapter appListAdapter;
    private ToThirdPartyAppUtils appUtils;
    private MessageAdapter msgAdapter;

    public static boolean isReadMsg = false;
    private HomeViewModel viewModel;
//    private OnFragmentOnClickListener clickListener;

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

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment Home2Fragment.
     */
    // TODO: Rename and change types and number of parameters
    public static Home2Fragment newInstance(String param1, String param2) {
        return new Home2Fragment();
    }

    @Override
    protected boolean isEventBus() {
        return true;
    }

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

    @Override
    protected void lazyLoad() {

    }

    @Override
    protected void readInstanceState(Bundle savedInstanceState) {

    }

    @Override
    protected void initView(View view) {
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(), 4);
        viewBinding.homeAppList.setLayoutManager(gridLayoutManager);
        LinearLayoutManager manager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
        viewBinding.homeRvMsg.setLayoutManager(manager);
        viewModel = ViewModelProviders.of(this).get(HomeViewModel.class);
//        viewBinding.mainScanCode.setOnClickListener(v -> {
//            Intent intent = new Intent(getContext(), ScanCodeActivity.class);
//            startActivityForResult(intent, 15015);
//        });
    }

    @Override
    protected void startView(View view) {
        setUserInfoUI();
        //45 *1 * 24 *20
//        viewModel.addBannerData(this, this::initBanner);
//        viewModel.getBanner();
        viewModel.addAppList(this, this::initAppData);
        viewModel.getAppList();
        viewModel.addMsgList(this, homeMessageBean -> {
            viewBinding.homeTvMsgCount.setText(Html.fromHtml(homeMessageBean.getTitle()));
            viewBinding.homeTvMsgCount.setTag(homeMessageBean.getCount());
            initMessage(homeMessageBean.getMessageBeanList());
        });
        viewModel.getMessage();
    }

    /**
     * 创建图片地址uri,用于保存拍照后的照片 Android 10以后使用这种方法
     */
    private Uri createImageUri() {
        String status = Environment.getExternalStorageState();
        // 判断是否有SD卡,优先使用SD卡存储,当没有SD卡时使用手机存储
        if (status.equals(Environment.MEDIA_MOUNTED)) {
            return getContext().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new ContentValues());
        } else {
            return getContext().getContentResolver().insert(MediaStore.Images.Media.INTERNAL_CONTENT_URI, new ContentValues());
        }
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void hanMessage(MessageEvent event) {
        if (event.getCount() <= 0) return;
        Object tag = viewBinding.homeTvMsgCount.getTag();
        if (tag != null) {
            int count = (int) tag;
            if (count == event.getCount()) return;
        }
        MessageContentFragment.isReadMsg = true;
        viewBinding.homeTvMsgCount.setTag(event.getCount());
        viewBinding.homeTvMsgCount.setText(Html.fromHtml(event.getMsg()));
        initMessage(event.getMessageBeanList());
    }


    @Override
    public void onResume() {
        super.onResume();
        if (isReadMsg) {
            viewModel.getMessage();
            isReadMsg = false;
        }
    }

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

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
        if (requestCode == 15015 && resultCode == Activity.RESULT_OK) {
            if (data == null) return;
            String stringExtra = data.getStringExtra(CameraScan.SCAN_RESULT);
            ToastUtil.centered(getContext(), stringExtra);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    public void getPhotoImage() {
        viewBinding.homeTvUserPhoto.setImageDrawable(getDrawables(RuanseeApplication.getUserData().getErrorPhotoByIdCardNum()));
        Bitmap bitmap = new LoadPhotoImage().loadPhotoImage(RuanseeApplication.getUserData().getPhoto(), viewBinding.homeTvUserPhoto, new ImageCallBack() {
            @Override
            public void imageLoad(ImageView imageView, Bitmap bitmap) {
                if (getActivity() == null)return;
//                viewBinding.homeTvUserPhoto.setImageBitmap(bitmap);
                if (getActivity().isDestroyed()) return;
                Glide.with(getContext())
                        .load(bitmap)
                        .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                        .into(viewBinding.homeTvUserPhoto);
            }

            @Override
            public void imageLoadError(ImageView imageView, String message) {
//                ToastUtil.centered(getContext(),message);
//                if (getActivity().isDestroyed())return;
//                viewBinding.homeTvUserPhoto.setImageDrawable(getDrawables(RuanseeApplication.getUserData().getErrorPhotoByIdCardNum()));
            }
        });

        if (bitmap != null) {
            if (getActivity() == null)return;
            if (getActivity().isDestroyed()) return;
            Glide.with(getContext())
                    .load(bitmap)
                    .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                    .into(viewBinding.homeTvUserPhoto);
        }
    }

    /**
     * 显示用户信息
     */
    private void setUserInfoUI() {
        viewBinding.homeTvUserName.setText(RuanseeApplication.getUserData().getUserName());
        viewBinding.homeTvUserCode.setText(RuanseeApplication.getUserData().getUserCode());
        viewBinding.homeTvUserDeptName.setText(RuanseeApplication.getUserData().getDeptName());
        viewBinding.homeBtnUser.setOnClickListener(new CustomClickListener() {
            @Override
            public void onSingleClick(View v) {
                startActivity(new Intent(getContext(), MyDetailsActivity.class));
            }
        });
        getPhotoImage();
    }

    private void initMessage(List<MessageBean> dataList) {
        if (msgAdapter == null) {
            msgAdapter = new MessageAdapter(getContext(), dataList);
            viewBinding.homeRvMsg.setAdapter(msgAdapter);
            msgAdapter.setListClickListener(new SimpleListClickListener() {
                @Override
                public void onSingleClick(View v, int pointer) {
                    if (appUtils == null) {
                        appUtils = new ToThirdPartyAppUtils(getContext());
                        getLifecycle().addObserver(appUtils);
                    }
                    baseShowDialong("正在打开应用，请稍后。。。");
                    appUtils.skipReadMsg(msgAdapter.getDataItem(pointer));
                    msgAdapter.removeItem(pointer);
                    MessageContentFragment.isReadMsg = true;
                    if (msgAdapter.getItemCount() == 0) {
                        List<MessageBean> messageBeanList = new ArrayList<>();
                        MessageBean bean = new MessageBean();
                        bean.setBaseType(0);
                        bean.setBaseMessage("暂无新消息！");
                        messageBeanList.add(bean);
                        initMessage(messageBeanList);
                        viewBinding.homeTvMsgCount.setText("全部消息");
                        viewBinding.homeTvMsgCount.setTag(0);
                    } else {
                        Object tag = viewBinding.homeTvMsgCount.getTag();
                        if (tag == null) {
                            viewBinding.homeTvMsgCount.setText("全部消息");
                            viewBinding.homeTvMsgCount.setTag(0);
                        } else {
                            int count = (int) tag;
                            count--;
                            viewBinding.homeTvMsgCount.setTag(count);
                            String title = "<font color=\"#808080\">全部消息(</font><font color=\"#FF9124\">" + count + "</font><font color=\"#808080\">）</font>";
                            viewBinding.homeTvMsgCount.setText(Html.fromHtml(title));
                        }
                    }
                }
            });
        } else {
            msgAdapter.upData(dataList);
        }
    }

    private void initAppData(List<AppBean> dataList) {
        if (appListAdapter == null) {
            appListAdapter = new HomeAppListAdapter(getContext(), dataList);
            viewBinding.homeAppList.setAdapter(appListAdapter);
            appListAdapter.setListClickListener(new SimpleListClickListener() {
                @Override
                public void onSingleClick(View v, int pointer) {
                    if (appUtils == null) {
                        appUtils = new ToThirdPartyAppUtils(getContext());
                    }
                    AppBean dataItem = appListAdapter.getDataItem(pointer);
                    appUtils.skipApp(dataItem);
                }
            });
        } else {
            appListAdapter.upData(dataList);
        }
        if (dataList.size() == 1) {
            int baseType = dataList.get(0).getBaseType();
            if (baseType == -1 || baseType == 0) {
                LinearLayoutManager gridLayoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
                viewBinding.homeAppList.setLayoutManager(gridLayoutManager);
                return;
            }
        }
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(), 4);
        viewBinding.homeAppList.setLayoutManager(gridLayoutManager);
    }

    private void initBanner(List<Object> imageViewList) {
        //添加生命周期观察者
        viewBinding.homeBanner.addBannerLifecycleObserver(this)
                .setLoopTime(4000)
                .setIndicatorSpace(5)
                .setPageTransformer(new AlphaPageTransformer())
                .setAdapter(new BannerImageAdapter(imageViewList) {
                    @Override
                    public void onBindView(Object holder, Object data, int position, int size) {
                        if (isDetached()) return;
                        if (holder instanceof BannerImageHolder) {
                            BannerImageHolder h = (BannerImageHolder) holder;
                            h.imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                            //图片加载自己实现
                            Glide.with(h.imageView)
                                    .load(data)
                                    .placeholder(R.drawable.icon_banner1)
                                    .error(R.drawable.ic_load_imag_eerror)
                                    .apply(RequestOptions.bitmapTransform(new RoundedCorners(8)))
                                    .into(h.imageView);
                        }
                    }
                })
                .setIndicator(new RectangleIndicator(getContext()));

        viewBinding.homeBanner.start();
    }

}