package com.cooleshow.student.ui.web;

import static com.cooleshow.base.common.WebConstants.WEB_URL;

import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;

import androidx.annotation.Nullable;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.cooleshow.base.router.RouterPath;
import com.cooleshow.base.service.PlayMusicService;
import com.cooleshow.base.ui.activity.BaseMVPActivity;
import com.cooleshow.base.utils.ToastUtil;
import com.cooleshow.base.utils.ToastUtils;
import com.cooleshow.base.utils.helper.WebParamsHelper;
import com.cooleshow.base.utils.helper.upload.UploadHelper;
import com.cooleshow.student.R;
import com.cooleshow.student.databinding.ActivityAccompanyBinding;
import com.cooleshow.student.presenter.web.AccompanyPresenter;
import com.cooleshow.student.widgets.FileUtils;
import com.cooleshow.usercenter.helper.UserHelper;
import com.gyf.immersionbar.ImmersionBar;
import com.wonderkiln.camerakit.CameraKit;
import com.wonderkiln.camerakit.CameraView;
import com.wonderkiln.camerakit.events.CameraKitError;
import com.wonderkiln.camerakit.events.CameraKitEvent;
import com.wonderkiln.camerakit.events.CameraKitEventListener;
import com.wonderkiln.camerakit.events.CameraKitImage;
import com.wonderkiln.camerakit.events.CameraKitVideo;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import io.rong.imkit.utils.StatusBarUtil;

/**
 * 创建日期：2022/6/8 14:19
 *
 * @author Ryan
 * 类说明：
 */
@Route(path = RouterPath.WebCenter.ACTIVITY_ACCOMPANY_HTML)
public class AccompanyActivity extends BaseMVPActivity<ActivityAccompanyBinding, AccompanyPresenter> {
    FrameLayout camera;
    FrameLayout fl_webview;

    private final int PORTRAIT_REQUEST_CODE = 1002;
    private final int ADD_ACCOMPANIMENT_CODE = 1003;
    private String authorization;
    private String webViewUrl;

    CameraView cameraView;
    private String filePath;
    private String videoDerectoryName = "/guanyuemiTaskVideo";
    private View cameraGroupView;
    private String recordVideFilePath; //评测视频
    private AccompanyFragment accompanyFragment;
    private JSONObject baseJsonObject;
    private Intent intentOne;

    @Override
    protected void initView() {
        camera = viewBinding.camera;
        fl_webview = viewBinding.flWebview;
        Intent intent = getIntent();
        String url = intent.getStringExtra(WEB_URL);

        int orientation = intent.getIntExtra("orientation", -1);
        boolean isOpenLight = intent.getBooleanExtra("isOpenLight", false);

        if (isOpenLight) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        }
        if (orientation >= 0) {
            setRequestedOrientation(orientation);
        }

        setStatusBarTextColor(intent.getBooleanExtra("statusBarTextColor", true));
        String userToken = UserHelper.getUserToken();
        String Authorization = TextUtils.isEmpty(userToken) ? null : userToken;
        if (!TextUtils.isEmpty(Authorization)) {
            try {
                authorization = URLEncoder.encode(Authorization, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            boolean status = url.contains("?");
            if (status) {
                webViewUrl = (url + "&Authorization=" + authorization);
            } else {
                webViewUrl = (url + "?Authorization=" + authorization);
            }
        }

        accompanyFragment = AccompanyFragment.newInstance(webViewUrl);
        accompanyFragment.setOnAccompanyListener(new AccompanyFragment.onListener() {


            @Override
            public void setStatusBarTextColor(boolean statusBarTextColor) {
//                setStatusBarTextColor(statusBarTextColor);
            }

            /**
             * 打开相机
             */
            @Override
            public void openCamera() {
                if (cameraView == null) {
                    cameraGroupView = LayoutInflater.from(AccompanyActivity.this).inflate(R.layout.record_video_layout, camera, false);
                    camera.addView(cameraGroupView);
                    cameraView = cameraGroupView.findViewById(R.id.camera);
                    cameraView.setVideoQuality(CameraKit.Constants.VIDEO_QUALITY_HIGHEST);
                    cameraView.start();
                    cameraView.addCameraKitListener(new CameraKitEventListener() {

                        @Override
                        public void onEvent(CameraKitEvent cameraKitEvent) {

                        }

                        @Override
                        public void onError(CameraKitError cameraKitError) {

                        }

                        @Override
                        public void onImage(CameraKitImage cameraKitImage) {

                        }

                        @Override
                        public void onVideo(CameraKitVideo cameraKitVideo) {
                            try {
                                File file = cameraKitVideo.getVideoFile();
                                filePath = file.getPath();
                                sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(filePath))));
                                hideLoading();
                                ToastUtil.getInstance().showShort("保存成功");
                            } catch (Exception e) {
                            }

                        }
                    });
                }
            }

            /**
             * 关闭相机
             */
            @Override
            public void closeCamera() {
                if (cameraView != null) {
                    cameraView.stop();
                    cameraView.destroyDrawingCache();
                    camera.removeView(cameraGroupView);
                    cameraGroupView = null;
                    cameraView = null;
                }
            }

            /**
             * 录视频
             */
            @Override
            public void startCapture() {
                if (cameraView != null) {
                    recordVideFilePath = FileUtils.getPublicDirectory(videoDerectoryName) + File.separator
                            + "VID_" + new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.CHINA).format(new Date()) + ".mp4";
                    cameraView.captureVideo(new File(recordVideFilePath));//开始录像
                }

            }

            @Override
            public void videoUpdate(JSONObject jsonObject) {
                baseJsonObject = jsonObject;
                File file = new File(recordVideFilePath);

                if (!file.exists()) {
                    ToastUtil.getInstance().showShort("未找到该视频，请重试");
                    FileUtils.deleteFile(recordVideFilePath);
                }
                String bucket = WebParamsHelper.getParams(jsonObject, "bucket");
                UploadHelper uploadHelper = new UploadHelper(AccompanyActivity.this,bucket);
                uploadHelper.uploadFile(file);
                uploadHelper.setUpLoadCallBack(new UploadHelper.UpLoadCallBack() {
                    @Override
                    public void onSuccess(String url) {
                        try {
                            JSONObject contentObj = baseJsonObject.getJSONObject("content");
                            String uuid = contentObj.getString("uuid");
                            contentObj.put("type", "success");
                            contentObj.put("filePath", url);
                            contentObj.put("uuid", uuid);
                            contentObj.put("message", "上传成功");
                            accompanyFragment.onSendMessage(baseJsonObject.toString());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure() {
                        upLoadFileFaile();
                        ToastUtil.getInstance().showShort("上传失败，请重新选择");
                    }
                });

            }

            /**
             * 停止录视频
             */
            @Override
            public void endCapture() {
                if (cameraView != null && cameraView.getVisibility() == View.VISIBLE) {
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            cameraView.stopVideo();//结束录像

                        }
                    }, 1000);
                }
            }
        });

        getSupportFragmentManager().beginTransaction()
                .add(R.id.fl_webview, accompanyFragment)
                .commitAllowingStateLoss();


        intentOne = new Intent(this, PlayMusicService.class);
        startService(intentOne);
    }

    public void setStatusBarTextColor(boolean statusBarTextColor) {
        if (statusBarTextColor) {
            setStatusBarColor();
        } else {
            setStatusBlackBarColor();
        }
    }

    public void setStatusBarColor() {
        ImmersionBar.with(this)
                .keyboardEnable(true)
                .transparentStatusBar()
                .statusBarDarkFont(false, 0.2f) //原理：如果当前设备支持状态栏字体变色，会设置状态栏字体为黑色，如果当前设备不支持状态栏字体变色，会使当前状态栏加上透明度，否则不执行透明度
                .autoDarkModeEnable(false)
                .flymeOSStatusBarFontColor(R.color.white)  //修改flyme OS状态栏字体颜色
                .init();  //必须调用方可沉浸

    }

    public void setStatusBlackBarColor() {
        ImmersionBar.with(this)
                .keyboardEnable(true)
                .transparentStatusBar()
                .statusBarDarkFont(true, 0.2f) //原理：如果当前设备支持状态栏字体变色，会设置状态栏字体为黑色，如果当前设备不支持状态栏字体变色，会使当前状态栏加上透明度，否则不执行透明度
                .autoDarkModeEnable(false)
                .flymeOSStatusBarFontColor(com.cooleshow.base.R.color.common_black)  //修改flyme OS状态栏字体颜色
                .init();  //必须调用方可沉浸
    }

    @Override
    protected ActivityAccompanyBinding getLayoutView() {
        return ActivityAccompanyBinding.inflate(getLayoutInflater());
    }

    @Override
    protected AccompanyPresenter createPresenter() {
        return new AccompanyPresenter();
    }


    @Override
    protected void onResume() {
        super.onResume();

        if (cameraView != null) {
            cameraView.setVisibility(View.VISIBLE);
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (cameraView != null) {
                        cameraView.start();
                    }
                }
            }, 1000);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (intentOne != null) {
            stopService(intentOne);
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ADD_ACCOMPANIMENT_CODE) {
            try {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("api", "reload");
//                onSendMessage(jsonObject.toString());
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else if (requestCode == 1000) {
            if (data != null) {
                try {
                    String filePath = data.getStringExtra("filePath");
                    JSONObject jsonObject = new JSONObject();

                    jsonObject.put("api", "uploadVideo");

                    jsonObject.put("url", filePath);
//                    webView.evaluateJavascript("sendMessage('" + jsonObject.toString() + "')", new ValueCallback<String>() {
//                        @Override
//                        public void onReceiveValue(String s) {
//                        }
//                    });

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        } else if (requestCode == 1011) {
            String selectAddress = data.getStringExtra("selectAddress");
            if (null!=accompanyFragment){
                accompanyFragment.selectAddress(selectAddress);
            }
        }
    }

    @Override
    protected void onStop() {
        if (cameraView != null) {
            cameraView.stop();
            cameraView.destroyDrawingCache();
        }

        super.onStop();

    }

    private void upLoadFileFaile() {
        try {
            JSONObject contentObj = baseJsonObject.getJSONObject("content");
            String uuid = contentObj.getString("uuid");
            contentObj.put("type", "error");
            contentObj.put("uuid", uuid);
            contentObj.put("message", "上传失败");
            accompanyFragment.onSendMessage(baseJsonObject.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
