package com.efounder.chat.zxing.qrcode;

import android.app.Activity;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.efounder.chat.R;
import com.efounder.chat.activity.BaseActivity;
import com.efounder.chat.utils.CommonThreadPoolUtils;
import com.efounder.chat.zxing.camera.CameraManager;
import com.efounder.chat.zxing.decoding.CaptureActivityHandler;
import com.efounder.chat.zxing.decoding.DecodeFormatManager;
import com.efounder.chat.zxing.decoding.InactivityTimer;
import com.efounder.chat.zxing.view.ViewfinderView;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.utils.Constants;
import com.efounder.util.AppContext;
import com.efounder.utils.EasyPermissionUtils;
import com.efounder.utils.ResStringUtil;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.ChecksumException;
import com.google.zxing.DecodeHintType;
import com.google.zxing.FormatException;
import com.google.zxing.NotFoundException;
import com.google.zxing.PlanarYUVLuminanceSource;
import com.google.zxing.Reader;
import com.google.zxing.Result;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeReader;

import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.Hashtable;
import java.util.Vector;

import pub.devrel.easypermissions.AfterPermissionGranted;

/**
 * 扫一扫界面
 *
 * @author Ryan.Tang
 */
public class MipcaActivityCapture extends BaseActivity implements Callback {

    private CaptureActivityHandler handler;
    private ViewfinderView viewfinderView;
    private boolean hasSurface;
    private Vector<BarcodeFormat> decodeFormats;
    private String characterSet;
    private InactivityTimer inactivityTimer;
    private MediaPlayer mediaPlayer;
    private boolean playBeep;
    private static final float BEEP_VOLUME = 0.10f;
    private boolean vibrate;
    private String photo_path = "";
    private static final int REQUEST_CODE = 100;
    private static final int PARSE_BARCODE_SUC = 300;
    private static final int PARSE_BARCODE_FAIL = 303;
    private Bitmap scanBitmap;


    private QrHandler mHandler = new QrHandler(this);

    private static class QrHandler extends Handler {
        private WeakReference<MipcaActivityCapture> weakReference;

        public QrHandler(MipcaActivityCapture activity) {
            weakReference = new WeakReference<MipcaActivityCapture>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            MipcaActivityCapture activityCapture = weakReference.get();
            if (activityCapture == null) {
                return;
            }
            activityCapture.dismissLoading();
            switch (msg.what) {
                case PARSE_BARCODE_SUC:
                    activityCapture.onResultHandler((String) msg.obj, activityCapture.scanBitmap);
                    break;
                case PARSE_BARCODE_FAIL:
                    Toast.makeText(AppContext.getInstance(), (String) msg.obj, Toast.LENGTH_LONG).show();
                    break;
            }
        }

    }


    //是否返回扫描结果自己处理
    public static final String NEED_RESULT = "needResult";

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK && null != data) {
            Cursor cursor = getContentResolver().query(data.getData(), null, null, null, null);
            if (cursor.moveToFirst()) {
                photo_path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();

            showLoading(ResStringUtil.getString(R.string.wrchatview_resolving));

            CommonThreadPoolUtils.execute(new Runnable() {
                @Override
                public void run() {
                    Result result = scanningImage(photo_path);
                    if (result != null) {
                        Message m = mHandler.obtainMessage();
                        m.what = PARSE_BARCODE_SUC;
                        m.obj = result.getText();
                        mHandler.sendMessage(m);
                    } else {
                        Message m = mHandler.obtainMessage();
                        m.what = PARSE_BARCODE_FAIL;
                        m.obj = ResStringUtil.getString(R.string.wrchatview_identification_failure);
                        mHandler.sendMessage(m);
                    }
                }
            });
        }
    }


    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.erweima_capture);

        setScanWidthHeight();
        initView();
        hasSurface = false;
        inactivityTimer = new InactivityTimer(this);
        CameraManager.init(getApplication());
        checkPermission();

    }

    @AfterPermissionGranted(EasyPermissionUtils.PERMISSION_REQUEST_CODE_CAMERA)
    private void checkPermission() {
        if (EasyPermissionUtils.checkCameraPermission()) {
            CameraManager.init(getApplication());
        } else {
            EasyPermissionUtils.requestCameraPermission(this);
        }
    }


    private void initView() {
        viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);
        ImageView mButtonBack = (ImageView) findViewById(R.id.iv_back);
        mButtonBack.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                MipcaActivityCapture.this.finish();

            }
        });
        Button mButtonAlbum = (Button) findViewById(R.id.button_album);
//        if (!EnvironmentVariable.getProperty(Constants.KEY_SETTING_APPID).equals("ZSYGXOSPMobile")) {
        if (!(EnvironmentVariable.getProperty(Constants.KEY_SETTING_APPID).equals("ZSYGXOSPMobile") || EnvironmentVariable.getProperty(Constants.KEY_SETTING_APPID).equals("ZSYGXOSPMobileYS"))) {
            mButtonAlbum.setVisibility(View.VISIBLE);
            mButtonAlbum.setText(R.string.wrchatview_album);
        } else {
            mButtonAlbum.setVisibility(View.VISIBLE);
        }
        mButtonAlbum.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent innerIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                Intent wrapperIntent = Intent.createChooser(innerIntent, ResStringUtil.getString(R.string.wrchatview_select_qr));
                MipcaActivityCapture.this.startActivityForResult(wrapperIntent, REQUEST_CODE);
            }
        });
        LinearLayout llButtonView = (LinearLayout) findViewById(R.id.ll_bottom_button);

//		if(!EnvironmentVariable.getProperty(Constants.KEY_SETTING_APPID).equals("ZSYGXOSPMobile")) {
//			llButtonView.setVisibility(View.GONE);
//		}
//		if ((getIntent().getExtras()!=null)&&getIntent().getExtras().getBoolean("fromScan",false)){
//			llButtonView.setVisibility(View.VISIBLE);
//		}else {
//			llButtonView.setVisibility(View.INVISIBLE);
//		}
        ImageView ivScanCode = (ImageView) findViewById(R.id.iv_scan_code);
        ImageView ivScanInvoice = (ImageView) findViewById(R.id.iv_scan_invoice);
        //财务共享，不显示扫描
      //  if (EnvSupportManager.isSupportCWGXPage()) {
            LinearLayout saomiao = (LinearLayout) findViewById(R.id.ll_saomiao);
            saomiao.setVisibility(View.GONE);
       // }

        ivScanInvoice.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
//					Intent intent = new Intent();
//					intent.putExtra("invoiceWidth", 856);
//					intent.putExtra("invoiceHeight", 1210);
////					intent.putExtra("invoiceWidth", 856);
////					intent.putExtra("invoiceHeight", 1210);
////					intent.putExtra("invoiceWidth", 834);
////					intent.putExtra("invoiceHeight", 1180);
//					intent.setClass(MipcaActivityCapture.this, Class.forName("io.card.payment.CardIOActivity"));
//					intent.putExtra("io.card.payment.suppressManual", true)//// TODO: 17-8-1
//							.putExtra("io.card.payment.hideLogo", false)//// TODO: 17-8-1
//							.putExtra("io.card.payment.languageOrLocale", "zh-Hans")
//							.putExtra("io.card.payment.keepApplicationTheme", true)
//							.putExtra("io.card.payment.guideColor", Color.GREEN)
//							.putExtra("io.card.payment.suppressScan", true)
//							.putExtra("io.card.payment.returnCardImage", true);
//					intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//					startActivity(intent);
//					invoiceWidth = (int) (675);
//					invoiceHeight = (int) (954);

                    Intent intent = new Intent()
                            .putExtra("io.card.payment.noCamera", false)
                            .putExtra("io.card.payment.requireExpiry", false)
                            .putExtra("io.card.payment.scanExpiry", false)
                            .putExtra("io.card.payment.requireCVV", false)
                            .putExtra("io.card.payment.requirePostalCode", false)
                            .putExtra("io.card.payment.restrictPostalCodeToNumericOnly", false)
                            .putExtra("io.card.payment.requireCardholderName", false)
                            .putExtra("io.card.payment.suppressManual", true)//// TODO: 17-8-1
                            .putExtra("io.card.payment.useCardIOLogo", false)
                            .putExtra("io.card.payment.hideLogo", true)//// TODO: 17-8-1
                            .putExtra("io.card.payment.languageOrLocale", "zh-Hans")
                            .putExtra("io.card.payment.intentSenderIsPayPal", false)
                            .putExtra("io.card.payment.keepApplicationTheme", false)
                            .putExtra("io.card.payment.guideColor", Color.GREEN)
                            .putExtra("io.card.payment.suppressConfirmation", false)
                            .putExtra("io.card.payment.suppressScan", true)
                            .putExtra("invoiceWidth", 210)////ios :948 1400 //android:8-31: 675,954
                            .putExtra("invoiceHeight", 297)
                            .putExtra("intentType", "SCAN")
                            .putExtra("io.card.payment.returnCardImage", true);

                    try {
//            int unblurDigits = Integer.parseInt(mUnblurEdit.getText().toString());
                        intent.putExtra("io.card.payment.unblurDigits", 4);
                        intent.setClass(MipcaActivityCapture.this, Class.forName("io.card.payment.CardIOActivity"));
                        startActivity(intent);
                    } catch (NumberFormatException ignored) {
                    }

                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
        SurfaceHolder surfaceHolder = surfaceView.getHolder();
        if (hasSurface) {
            initCamera(surfaceHolder);
        } else {
            surfaceHolder.addCallback(this);
            surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        }
        decodeFormats = null;
        characterSet = null;

        playBeep = true;
        AudioManager audioService = (AudioManager) getSystemService(AUDIO_SERVICE);
        if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
            playBeep = false;
        }
        initBeepSound();
        vibrate = true;

    }

    @Override
    protected void onPause() {
        super.onPause();
        if (handler != null) {
            handler.quitSynchronously();
            handler = null;
        }
        CameraManager.get().closeDriver();
    }

    @Override
    protected void onDestroy() {
        inactivityTimer.shutdown();
        super.onDestroy();
        releasePlayer();
    }

    /**
     * 释放播放器资源
     */
    private void releasePlayer() {
        try {
            if (mediaPlayer != null) {
                mediaPlayer.reset();
                mediaPlayer.release();
                mediaPlayer = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 处理扫描结果
     * classisclassis
     *
     * @param result
     * @param barcode
     */
    public void handleDecode(Result result, Bitmap barcode) {
        inactivityTimer.onActivity();
        playBeepSoundAndVibrate();
        String resultString = result.getText();
        onResultHandler(resultString, barcode);
    }

    /**
     * 跳转到处理界面
     *
     * @param resultString
     * @param bitmap
     */
    private void onResultHandler(String resultString, Bitmap bitmap) {
        if (TextUtils.isEmpty(resultString)) {
            Toast.makeText(MipcaActivityCapture.this, ResStringUtil.getString(R.string.wrchatview_identification_failure), Toast.LENGTH_SHORT).show();
            return;
        }
        if (getIntent().hasExtra(NEED_RESULT)) {
            //返回扫描结果不处理
            Intent intent = new Intent();
            intent.putExtra("scanResult", resultString);
            setResult(Activity.RESULT_OK, intent);
            finish();
            return;
        }
        QRManager.handleresult(this, resultString);
        //MipcaActivityCapture.this.finish();
    }

    private void initCamera(SurfaceHolder surfaceHolder) {
        try {
            CameraManager.get().openDriver(surfaceHolder);
        } catch (IOException ioe) {
            return;
        } catch (RuntimeException e) {
            return;
        }
        if (handler == null) {
            handler = new CaptureActivityHandler(this, decodeFormats, characterSet);
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
                               int height) {

    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (!hasSurface) {
            hasSurface = true;
            initCamera(holder);
        }

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        hasSurface = false;

    }

    public ViewfinderView getViewfinderView() {
        return viewfinderView;
    }

    public Handler getHandler() {
        return handler;
    }

    public void drawViewfinder() {
        viewfinderView.drawViewfinder();

    }

    private void initBeepSound() {
        if (playBeep && mediaPlayer == null) {
            // The volume on STREAM_SYSTEM is not adjustable, and users found it
            // too loud,
            // so we now play on the music stream.
            setVolumeControlStream(AudioManager.STREAM_MUSIC);
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.setOnCompletionListener(beepListener);

            AssetFileDescriptor file = getResources().openRawResourceFd(
                    R.raw.beep);
            try {
                mediaPlayer.setDataSource(file.getFileDescriptor(),
                        file.getStartOffset(), file.getLength());
                file.close();
                mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
                mediaPlayer.prepare();
            } catch (IOException e) {
                mediaPlayer = null;
            }
        }
    }

    private static final long VIBRATE_DURATION = 200L;

    private void playBeepSoundAndVibrate() {
        if (playBeep && mediaPlayer != null) {
            mediaPlayer.start();
        }
        if (vibrate) {
            Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
            vibrator.vibrate(VIBRATE_DURATION);
        }
    }

    /**
     * When the beep has finished playing, rewind to queue up another one.
     */
    private final OnCompletionListener beepListener = new OnCompletionListener() {
        public void onCompletion(MediaPlayer mediaPlayer) {
            mediaPlayer.seekTo(0);
        }
    };

    /**
     * 扫描二维码图片的方法
     *
     * @param path
     * @return
     */
    public Result scanningImage(String path) {
        if (TextUtils.isEmpty(path)) {
            return null;
        }
        Hashtable<DecodeHintType, Object> hints = new Hashtable<DecodeHintType, Object>();
        hints.put(DecodeHintType.CHARACTER_SET, "UTF8"); //设置二维码内容的编码
        // 可以解析的编码类型
        Vector<BarcodeFormat> decodeFormats = new Vector<BarcodeFormat>();
        // 这里设置可扫描的类型
        decodeFormats.addAll(DecodeFormatManager.QR_CODE_FORMATS);
        decodeFormats.addAll(DecodeFormatManager.DATA_MATRIX_FORMATS);
        hints.put(DecodeHintType.POSSIBLE_FORMATS, decodeFormats);

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = false; // 获取新的大小
        for (int i = 1; i < 10; i++) {
            options.inSampleSize = i;

            scanBitmap = BitmapFactory.decodeFile(path, options);
//                //方法1
//            RGBLuminanceSource source = new RGBLuminanceSource(scanBitmap);
//            BinaryBitmap bitmap1 = new BinaryBitmap(new HybridBinarizer(source));
//            try {
//                QRCodeReader reader = new QRCodeReader();
//                return reader.decode(bitmap1, hints);
//            } catch (NotFoundException e) {
//                e.printStackTrace();
//            } catch (ChecksumException e) {
//                e.printStackTrace();
//            } catch (FormatException e) {
//                e.printStackTrace();
//            }
            //方法2 比方法一有效 参考 http://www.imooc.com/article/22919
            // 1.将bitmap的RGB数据转化成YUV420sp数据
            byte[] bmpYUVBytes = Bmp2YUVUtil.getBitmapYUVBytes(scanBitmap);
            // 2.塞给zxing进行decode
            try {
                return decodeYUVByZxing(bmpYUVBytes, scanBitmap.getWidth(), scanBitmap.getHeight());
            } catch (FormatException e) {
                e.printStackTrace();
            } catch (ChecksumException e) {
                e.printStackTrace();
            } catch (NotFoundException e) {
                e.printStackTrace();
            }


        }
        return null;
    }

    private static Result decodeYUVByZxing(byte[] bmpYUVBytes, int bmpWidth, int bmpHeight) throws FormatException, ChecksumException, NotFoundException {
        String zxingResult = "";
        // Both dimensions must be greater than 0
        if (null != bmpYUVBytes && bmpWidth > 0 && bmpHeight > 0) {

            PlanarYUVLuminanceSource source = new PlanarYUVLuminanceSource(bmpYUVBytes, bmpWidth,
                    bmpHeight, 0, 0, bmpWidth, bmpHeight, true);
            BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(source));
            Reader reader = new QRCodeReader();
            Result result = reader.decode(binaryBitmap);
            return result;
        }
        return null;
    }


    private void setScanWidthHeight() {
        //设置扫描的大小
        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        int widthPixels = metrics.widthPixels;
        int heightPixels = metrics.heightPixels;
        int width = widthPixels < heightPixels ? widthPixels : heightPixels;
        if (width <= 0)
            width = 320;
        CameraManager.MIN_FRAME_WIDTH = (int) (width * 3 / 5);
        CameraManager.MIN_FRAME_HEIGHT = (int) (width * 3 / 5);
        CameraManager.MAX_FRAME_WIDTH = (int) (width * 3 / 5);
        CameraManager.MAX_FRAME_HEIGHT = (int) (width * 3 / 5);
//		Log.e("distance","CameraManager.MAX_FRAME_WIDTH="+CameraManager.MAX_FRAME_WIDTH+" CameraManager.MAX_FRAME_HEIGHT="+CameraManager.MAX_FRAME_HEIGHT);
//		CameraManager.MIN_FRAME_WIDTH = 240;
//		CameraManager.MIN_FRAME_HEIGHT =240;
//		CameraManager.MAX_FRAME_WIDTH = 1200;//(int)(width*2/3);
//		CameraManager.MAX_FRAME_HEIGHT = 675;
//		CameraManager.MIN_FRAME_WIDTH = width;
//		CameraManager.MIN_FRAME_HEIGHT =width;
//		CameraManager.MAX_FRAME_WIDTH = width;//(int)(width*2/3);
//		CameraManager.MAX_FRAME_HEIGHT = width;
    }

    public void restartDecode() {
        if (handler == null) {
            handler = new CaptureActivityHandler(this, decodeFormats, characterSet);
        }

        handler.sendEmptyMessage(R.id.decode_failed);
    }
}