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

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.rs.macall.androidx.basemodel.base.BaseViewBindActivity;
import com.rs.macall.androidx.basemodel.callback.SimpleListClickListener;
import com.rs.macall.androidx.basemodel.utils.LogUtils;
import com.rs.macall.androidx.basemodel.utils.SmartRefreshLayoutHelp;
import com.rs.macall.androidx.basemodel.utils.StringUtil;
import com.rs.macall.androidx.basemodel.utils.ToastUtil;
import com.rs.macall.androidx.basemodel.utils.TypConversion;
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.ActivityAppGuideDetailsBinding;
import com.ycgis.macall.personalcenter.m.adapterbean.AppGuideDetailsBean;
import com.ycgis.macall.personalcenter.m.adapterbean.AppInfoBean;
import com.ycgis.macall.personalcenter.p.app.AppCache;
import com.ycgis.macall.personalcenter.p.app.RuanseeApplication;
import com.ycgis.macall.personalcenter.p.callback.BaseRequestCallback;
import com.ycgis.macall.personalcenter.p.request.ApiModel;
import com.ycgis.macall.personalcenter.p.request.DownloadUtil;
import com.ycgis.macall.personalcenter.p.request.RetrofitService;
import com.ycgis.macall.personalcenter.util.FileUtils;
import com.ycgis.macall.personalcenter.v.adapter.AppGuideDetailsAdapter;
import com.ycgis.macall.personalcenter.v.photoview.ShowPhotoDialog;

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

import java.io.File;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/**
 * 应用指南详情
 */
public class AppGuideDetailsActivity extends BaseViewBindActivity<ActivityAppGuideDetailsBinding> {
    private String appJson;
    private AppInfoBean appBean;
    private AppGuideDetailsAdapter adapter;
    private ShowPhotoDialog showPhotoDialog;
//    private LoadAppCenterImage loadAppCenterImage;

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

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

    @Override
    protected void init() {
//        setViewOnClickListener(viewBinding.baseTitle.titleleft);
        GridLayoutManager manager = new GridLayoutManager(getContext(), 3);
        viewBinding.rvAppList.setLayoutManager(manager);
    }

    @Override
    protected void readInstanceState(Bundle savedInstanceState) {
        appJson = getIntent().getStringExtra("appJson");
    }

    @Override
    protected void start() {
        viewBinding.baseTitle.leftImage.setImageDrawable(getDrawables(R.drawable.back_cliener));
        viewBinding.baseTitle.contentTitle.setText("指南详情");
        viewBinding.baseTitle.titleleft.setOnClickListener(v -> finish());
        SmartRefreshLayoutHelp.setPullDownToRefresh(getContext(), viewBinding.srlRefresh);
        viewBinding.srlRefresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull @NotNull RefreshLayout refreshLayout) {
                getDetailsList();
            }
        });
        viewBinding.srlRefresh.autoRefresh();
        LinearLayoutManager manager = new LinearLayoutManager(getContext());
        manager.setOrientation(LinearLayoutManager.HORIZONTAL);
        viewBinding.rvAppList.setLayoutManager(manager);
        appBean = new Gson().fromJson(appJson, AppInfoBean.class);
        setAppInfo();
    }

    private void setAppInfo() {
        viewBinding.tvAppName.setText(appBean.getName());
        if (StringUtil.hasContent(appBean.getRemark())) {
            viewBinding.tvAppIntroduction.setText("\t\t" + appBean.getRemark());
        }
        viewBinding.tvCompany.setText(appBean.getServiceProvider());
        viewBinding.tvOperationName.setText(String.format("运维人员：%s", appBean.getOperationPerson()));
        viewBinding.tvOperationLxdh.setText(String.format("联系电话：%s", appBean.getPhoneNumber()));
        setImg(viewBinding.ivIcon, appBean.getIconUrl());

        ApiModel.uploadOperationLog("3","3", " 查询应用："+appBean.getName() +"指南");
    }

    private void setImg(ImageView img, String url) {
        //图片加载自己实现
        Glide.with(img)
                .load(url)
                .placeholder(R.drawable.icon_error2)
                .error(R.drawable.ic_load_imag_eerror)
                .into(img);
    }

    private void getDetailsList() {
        ApiModel.request("getCZSCxq", RetrofitService.getBaseInstance().operationGuideList(String.valueOf(appBean.getId())), new BaseRequestCallback<JsonObject>() {
            @Override
            public void onRequestFailure(String msg) {
                LogUtils.e(TAG, msg);
                List<AppGuideDetailsBean> dataList = new ArrayList<>();
                AppGuideDetailsBean bean = new AppGuideDetailsBean();
                bean.setBaseType(-1);
                bean.setBaseMessage(msg);
                dataList.add(bean);
                initData(dataList);
            }

            @Override
            public void onRequestSuccess(JsonObject result) {
                LogUtils.w(TAG, result.toString());
                List<AppGuideDetailsBean> dataList = new ArrayList<>();
                try {
                    JSONObject object = new JSONObject(result.toString());
                    String code = TypConversion.getJsonStr(object, "code");
                    if (code.equals("20041")) {
                        JSONArray data = TypConversion.getJSONArray(object, "data");
                        if (data == null) {
                            AppGuideDetailsBean bean = new AppGuideDetailsBean();
                            bean.setBaseType(0);
                            bean.setBaseMessage(TypConversion.getJsonStr(object, "msg"));
                            dataList.add(bean);
                            initData(dataList);
                            return;
                        }
                        Type type = new TypeToken<List<AppGuideDetailsBean>>() {
                        }.getType();
                        List<AppGuideDetailsBean> list = new Gson().fromJson(data.toString(), type);
                        if (list == null || list.isEmpty()) {
                            AppGuideDetailsBean bean = new AppGuideDetailsBean();
                            bean.setBaseType(0);
                            bean.setBaseMessage("暂未操作手册");
                            dataList.add(bean);
                            initData(dataList);
                            return;
                        }
                        dataList.addAll(list);
                        for (AppGuideDetailsBean b : dataList) {
                            b.setBaseType(1);
                        }
                        initData(dataList);
                    } else {
                        AppGuideDetailsBean bean = new AppGuideDetailsBean();
                        bean.setBaseType(0);
                        bean.setBaseMessage(TypConversion.getJsonStr(object, "msg"));
                        dataList.add(bean);
                        initData(dataList);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    AppGuideDetailsBean bean = new AppGuideDetailsBean();
                    bean.setBaseType(-1);
                    bean.setBaseMessage(e.getMessage());
                    dataList.add(bean);
                    initData(dataList);
                }
            }
        });
    }

    private void initData(List<AppGuideDetailsBean> dataList) {
        viewBinding.srlRefresh.finishRefresh();
        if (adapter == null) {
            adapter = new AppGuideDetailsAdapter(getContext(), dataList);
            viewBinding.rvAppList.setAdapter(adapter);
            adapter.setListClickListener(new SimpleListClickListener() {
                @Override
                public void onSingleClick(View v, int pointer) {
                    AppGuideDetailsBean dataItem = adapter.getDataItem(pointer);
                    String imgUrl = AppCache.BASE_IMAGE_URL + dataItem.getFilePath();
                    if (dataItem.getType() == 1) {
                        if (showPhotoDialog == null) {
                            showPhotoDialog = new ShowPhotoDialog(getContext(), R.style.MyDialogTheme);
                        }
                        if (StringUtil.hasContent(dataItem.getFilePath())) {
                            showPhotoDialog.show(imgUrl);
                        }
                    } else if (dataItem.getType() == 2) {
                        if (dataItem.getFilePath().endsWith(".mp4")) {
                            Intent intent = new Intent(getContext(), PlayVideosActivity.class);
                            intent.putExtra("url", imgUrl);
                            startActivity(intent);
                            return;
                        }
                    } else if (dataItem.getType() == 3) {
                        String filePath = dataItem.getFilePath();
                        int i = filePath.lastIndexOf("/");
                        String substring = filePath.substring(i + 1);
                        File file = new File(FileUtils.FILE_DIR, substring);
                        if (file.exists()) {
                            //打开文件
                            FileUtils.openFileByPath(getActivity(), file.getAbsolutePath());
                        } else {
                            //下载文件
                            handlerFile(imgUrl);
                        }
                    }
                }
            });
        } else {
            adapter.upData(dataList);
        }
    }

    private void handlerFile(String url) {
        baseShowDialog("正在下载文件，请稍后...");
        DownloadUtil.get().download(url, FileUtils.FILE_DIR, "", new DownloadUtil.OnDownloadListener() {
            @Override
            public void onDownloadSuccess(File file) {
                baseDismissDialog();
                ToastUtil.centered(getContext(), "文件下载成功！");
                if (file.exists()) {
                    //打开文件
                    FileUtils.openFileByPath(getActivity(), file.getAbsolutePath());
                }
            }

            @Override
            public void onDownloading(int progress) {

            }

            @Override
            public void onDownloadFailed(String msg) {
                baseDismissDialog();
                ToastUtil.centered(getContext(), "文件下载失败！" + msg);
            }
        });
    }
}