package com.example.audiovisualrecord.ui.main;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.core.content.FileProvider;
import androidx.core.os.EnvironmentCompat;

import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.audiovisualrecord.FileUtil;
import com.example.audiovisualrecord.MagicFileChooser;
import com.example.audiovisualrecord.R;
import com.example.audiovisualrecord.base.BaseActivity;
import com.example.audiovisualrecord.ui.chooseitem.ChooseDeviceItemData;
import com.example.audiovisualrecord.utils.api.apidata.searchco.COResponse;
import com.example.audiovisualrecord.utils.api.apidata.searchtype.TYPEResponse;
import com.example.audiovisualrecord.utils.api.searchshift.SHIFTResponse;
import com.example.audiovisualrecord.utils.api.searchpz.PZResponse;
import com.example.audiovisualrecord.utils.api.searchdp.DPResponse;


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

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


public class MainActivity extends BaseActivity implements MainContract.View, View.OnClickListener {

    private static final int REQUEST_CAPTURE_IMAGE = 100;
    private static final int REQUEST_VIDEO_CAPTURE = 200;
    private static final int PICK_IMAGE_FROM_GALLERY_REQUEST_CODE = 300;
    private static final int PICK_VIDEO_FROM_GALLERY_REQUEST_CODE = 400;
    private static final int PICK_FILE_REQUEST_CODE = 500;

    private Button btnCapturePicture, btnRecordVideo, btnGetImageFromGallery, btnGetVideoFromGallery, btnDeviceEdit, btnCentralCloud, btnChoseDevice, btnBasicInformation;


    private String pathCompany = "";
    private String pathFactoryArea = "";
    private String pathFactoryClass = "";
    private String pathClass = "";
    private String pathShootType = "";
    private String uploadPath = "";
    /**
     * 用于保存拍照图片的uri
     */
    private Uri mCameraUri;

    /**
     * 用于保存图片的文件路径，Android 10以下使用图片路径访问图片
     */
    private String mCameraImagePath;

    /**
     * 是否是Android 10以上手机
     */
    private boolean isAndroidQ = Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q;

    Bundle bag;
    String token;
    int countFile = 0;

    private TextView tvCompany, tvFactory, tvClass, tvUnit, tvShootType;
    private TextView textCompany, textFactory, textClass, textUnit, textShootType;
    private MainPresenter mPresenter;
    private MainData mMainData;
    private ChooseDeviceItemData mChooseDeviceItemData;
    private ArrayList<String> dialogString = new ArrayList<>();

    private String changeFileName = "";

    private List<String> filepath = new ArrayList<>();
    private List<String> filename = new ArrayList<>();

    String sidData = "";

//    String imageFilePhth;
//    String videoFilePath;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        dismissProgressDialog();
        bag = getIntent().getExtras();
        token = bag.getString("token");
        init();
        mPresenter = new MainPresenter(this, token);
        mMainData = new MainData();
        mChooseDeviceItemData = new ChooseDeviceItemData();
        createSegVideoFolder();

    }

    //創建分割後影片資料夾
    private void createSegVideoFolder() {
        File folder = new File(Environment.getExternalStorageDirectory() +
                File.separator + "Seg_Video");
        boolean success = true;
        if (!folder.exists()) {
            success = folder.mkdirs();
        } else {
            Log.e("wer", "folder exists");
        }
    }

    @Override
    public void init() {
        btnCapturePicture = findViewById(R.id.btnCaptureImage);
        btnGetImageFromGallery = findViewById(R.id.btnGetImageFromGallery);
        btnGetVideoFromGallery = findViewById(R.id.btnGetVideoFromGallery);
        btnRecordVideo = findViewById(R.id.btnRecordVideo);
        btnCapturePicture.setOnClickListener(this);
        btnGetImageFromGallery.setOnClickListener(this);
        btnGetVideoFromGallery.setOnClickListener(this);
        btnRecordVideo.setOnClickListener(this);
        tvCompany = findViewById(R.id.tv_company);
        tvFactory = findViewById(R.id.tv_factory);
        tvUnit = findViewById(R.id.tv_unit);
        tvClass = findViewById(R.id.tv_class);
        tvShootType = findViewById(R.id.tv_shoottype);
        tvCompany.setOnClickListener(this);
        tvFactory.setOnClickListener(this);
        tvUnit.setOnClickListener(this);
        tvClass.setOnClickListener(this);
        tvShootType.setOnClickListener(this);
        textCompany = findViewById(R.id.text_company);
        textUnit = findViewById(R.id.text_unit);
        textShootType = findViewById(R.id.text_shoottype);
        textFactory = findViewById(R.id.text_factory);
        textClass = findViewById(R.id.text_class);


    }

    private void pickImageFromGallery() {
        //Create an Intent with action as ACTION_PICK
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        // Sets the type as image/*. This ensures only components of type image are selected
        intent.setType("image/*");

        intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
        //We pass an extra array with the accepted mime types. This will ensure only components with these MIME types as targeted.
        String[] mimeTypes = {"image/jpeg", "image/png"};
        intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
        // Launching the Intent
        startActivityForResult(intent, PICK_IMAGE_FROM_GALLERY_REQUEST_CODE);
    }

    private void pickVideoFromGallery() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("video/*");
        intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
        String[] mimeTypes = {"video/mp4", "video/mov"};
        intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
        startActivityForResult(intent, PICK_VIDEO_FROM_GALLERY_REQUEST_CODE);
    }

    private Uri createImageUri() {
        String status = Environment.getExternalStorageState();
        // 判断是否有SD卡,优先使用SD卡存储,当没有SD卡时使用手机存储
        if (status.equals(Environment.MEDIA_MOUNTED)) {
            return getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new ContentValues());
        } else {
            return getContentResolver().insert(MediaStore.Images.Media.INTERNAL_CONTENT_URI, new ContentValues());
        }
    }

    private void openCameraIntent() {
        Intent pictureIntent = new Intent(
                MediaStore.ACTION_IMAGE_CAPTURE);
        settingSystemCamera(pictureIntent);
        if (pictureIntent.resolveActivity(getPackageManager()) != null) {
            //Create a file to store the image
            File photoFile = null;
            Uri photoUri = null;
            if (isAndroidQ) {
                photoUri = createImageUri();
            } else {
                try {
                    photoFile = createImageFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (photoFile != null) {
                mCameraImagePath = photoFile.getAbsolutePath();
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    photoUri = FileProvider.getUriForFile(this, "com.example.audiovisualrecord.provider", photoFile);

                } else {
                    photoUri = Uri.fromFile(photoFile);
                }

                mCameraUri = photoUri;

                if (photoUri != null) {
                    pictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
                    pictureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                    startActivityForResult(pictureIntent, REQUEST_CAPTURE_IMAGE);
                }
            }
        }
    }

    /**
     * 保存位图到本地
     *
     * @param bitmap
     * @param path   本地路径
     * @return void
     */
    public void SavaImage(Bitmap bitmap, String path) {

        File file = new File(path);
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri uri = Uri.fromFile(file);
        intent.setData(uri);
        this.sendBroadcast(intent);
        FileOutputStream fileOutputStream = null;
        String imageFilePhth;
        String fileName;
        //文件夹不存在，则创建它
        if (!file.exists()) {
            file.mkdir();
        }
        try {
            Date c = Calendar.getInstance(Locale.TAIWAN).getTime();
            SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd_HHmmss");
            String formattedDate = df.format(c);

            fileName = "IMG_"+formattedDate + ".jpg";
            imageFilePhth = path + "/" +fileName;
//            fileName = System.currentTimeMillis() + "";
            Log.e("filepath", imageFilePhth);
            File file1 = new File(imageFilePhth);

            fileOutputStream = new FileOutputStream(file1.getPath());
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
            fileOutputStream.close();
            //图片路径
//            MediaStore.Images.Media.insertImage(context.getContentResolver(),
//                    imageFilePhth,fileName , null);
            //多存一張照片
//            MediaStore.Images.Media.insertImage(this.getContentResolver(), bitmap, "", "");
            //要改掉下面那行
//            this.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file1.getAbsolutePath())));
            changeFileNameCheckDialog(imageFilePhth,fileName);

//            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://"+ Environment.getExternalStorageDirectory())));
        } catch (Exception e) {
//            ToastUtil.showToast("保存失败");
            Log.e("error", e.getMessage());
            e.printStackTrace();
        }
    }

    private void openRecordVideoIntent() {
        Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
        PackageManager packageManager = this.getPackageManager();
        List<ResolveInfo> listCam = packageManager.queryIntentActivities(takeVideoIntent, 0);
        takeVideoIntent.setPackage(listCam.get(0).activityInfo.packageName);
//        takeVideoIntent.putExtra(MediaStore.EXTRA_SIZE_LIMIT, 10996480L);  //限制影片大小
        if (takeVideoIntent.resolveActivity(getPackageManager()) != null) {
            startActivityForResult(takeVideoIntent, REQUEST_VIDEO_CAPTURE);
        }
    }

    private File createImageFile() throws IOException {
        String imageName = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        if (!storageDir.exists()) {
            storageDir.mkdir();
        }
        File tempFile = new File(storageDir, imageName);
        if (!Environment.MEDIA_MOUNTED.equals(EnvironmentCompat.getStorageState(tempFile))) {
            return null;
        }
        return tempFile;
    }


    private void settingSystemCamera(Intent intent) {
        PackageManager packageManager = MainActivity.this.getPackageManager();
        List<ResolveInfo> listCam = packageManager.queryIntentActivities(intent, 0);
        intent.setPackage(listCam.get(0).activityInfo.packageName);
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CAPTURE_IMAGE && resultCode == RESULT_OK) {
            Bitmap myBitmap = BitmapFactory.decodeFile(mCameraImagePath);
            String path1 = Environment.getExternalStorageDirectory().toString() + "/Pictures";
            SavaImage(myBitmap, path1);
        }

        if (requestCode == REQUEST_VIDEO_CAPTURE && resultCode == RESULT_OK) {
            //影片的uri

            String videoFilePath;
            Uri videoUri = data.getData();

            videoFilePath = MagicFileChooser.getAbsolutePathFromUri(this, videoUri);
            File file = new File(videoFilePath);
            String name = (file.getName());
            changeFileNameCheckDialog(videoFilePath,name);


        }

        if (requestCode == PICK_IMAGE_FROM_GALLERY_REQUEST_CODE && resultCode == RESULT_OK) {
            ArrayList<String> uriList = new ArrayList<String>();

            if (data.getClipData() != null) {
                for (int i = 0; i < data.getClipData().getItemCount(); i++) {
                    uriList.add(getPath(data.getClipData().getItemAt(i).getUri()));
//                    Log.e("gggg", "" + uriList.get(i));
                }
            } else if (Build.VERSION.SDK_INT >= 16 && data.getClipData() == null) {
                uriList.add(getPath(data.getData()));
            }
            //照片的uri
            mPresenter.onGetSid(uriList, getResourceString(R.string.on_upload_image));
        }

        if (requestCode == PICK_VIDEO_FROM_GALLERY_REQUEST_CODE && resultCode == RESULT_OK) {
            ArrayList<String> uriList = new ArrayList<String>();

            if (data.getClipData() != null) {
                Uri selectedVideo = data.getClipData().getItemAt(0).getUri();
                int count = data.getClipData().getItemCount();
                //count 選取檔案的數量
                for (int i = 0; i < count; i++) {
                    uriList.add(getPath(data.getClipData().getItemAt(i).getUri()));
                    filename.add(FileUtil.fileName(getPath(data.getClipData().getItemAt(i).getUri())));
//                    Log.e("gggg", "" + uriList.get(i));
//                    Log.e("dddd", "" + filename.get(i));
                }
                Log.e("aaa", count + "");

            } else if (Build.VERSION.SDK_INT >= 16 && data.getClipData() == null) {
                uriList.clear();

                String path = FileUtil.getFileAbsolutePath(this, data.getData());
                String name = FileUtil.fileName(path);
                uriList.add(path);

                // 2020/07/03廠商方面說先做單檔上傳不用分割影片
                //所以segVideo Function暫時先不用

//                mPresenter.segVideo(path, getResourceString(R.string.on_upload_vedio));

                ArrayList<String> VideoList = new ArrayList<>();
                VideoList.add(path);
                Log.e("Listsize",VideoList.size()+"");
                Log.e("List",VideoList.get(0));
                mPresenter.onGetSid(VideoList, getResourceString(R.string.on_upload_vedio));
                // TODO here====================
                //影片的uri
            }
        }
        if (requestCode == PICK_FILE_REQUEST_CODE && resultCode == RESULT_OK) {
            Uri selectedFile = data.getData();
            String filePath = MagicFileChooser.getAbsolutePathFromUri(this, selectedFile);
//            Log.e("filePath", filePath + "");
//            Log.e("ggggg", "" + selectedFile);
            checkFileTypeAndOpen(filePath, selectedFile);
        }
    }

    //根據副檔名判斷用什麼應用程式開啟
    private void checkFileTypeAndOpen(String filePath, Uri selectedFile) {
        final Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        if (filePath.contains(".doc")) {
            intent.setDataAndType(selectedFile, "application/msword");
        } else if (filePath.contains(".ppt")) {
            intent.setDataAndType(selectedFile, "application/vnd.ms-powerpoint");
        } else if ((filePath.contains(".csv")) || (filePath.contains(".xls"))) {
            intent.setDataAndType(selectedFile, "application/vnd.ms-excel");
        } else if (filePath.contains(".pdf")) {
            intent.setDataAndType(selectedFile, "application/pdf");
        } else if (filePath.contains(".txt")) {
            intent.setDataAndType(selectedFile, "text/plain");
        } else {
            intent.setDataAndType(selectedFile, "application/*");
        }

        PackageManager pm = getPackageManager();
        List<ResolveInfo> list = pm.queryIntentActivities(intent, 0);
        if (list.size() > 0)
            startActivity(intent);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btnCaptureImage:
                uploadPath = mPresenter.onJudgmentPath(pathCompany, pathFactoryArea, pathFactoryClass, pathClass, pathShootType);
                if ("".equals(uploadPath)) {
                    showDialogCaveatMessage("請選擇路徑");
                } else {
                    openCameraIntent();
                }
                break;

            case R.id.btnGetImageFromGallery:
                uploadPath = mPresenter.onJudgmentPath(pathCompany, pathFactoryArea, pathFactoryClass, pathClass, pathShootType);
                if ("".equals(uploadPath)) {
                    showDialogCaveatMessage("請選擇路徑");
                } else {
                    pickImageFromGallery();
                }
                break;

            case R.id.btnGetVideoFromGallery:
                uploadPath = mPresenter.onJudgmentPath(pathCompany, pathFactoryArea, pathFactoryClass, pathClass, pathShootType);
                if ("".equals(uploadPath)) {
                    showDialogCaveatMessage("請選擇路徑");
                } else {
                    pickVideoFromGallery();
                }
                break;

            case R.id.btnRecordVideo:
                uploadPath = mPresenter.onJudgmentPath(pathCompany, pathFactoryArea, pathFactoryClass, pathClass, pathShootType);
                if ("".equals(uploadPath)) {
                    showDialogCaveatMessage("請選擇路徑");
                } else {
                    openRecordVideoIntent();
                }
                break;

            case R.id.tv_company:
                mPresenter.onGetComData();
                break;

            case R.id.tv_factory:
                mPresenter.onGetPZData();
                break;

            case R.id.tv_unit:
                if (mChooseDeviceItemData.getFactoryAreaId().equals("")) {
                    showDialogCaveatMessage(getResourceString(R.string.add_device_no_maintenance_plant_error));
                }
                if (mChooseDeviceItemData.getCompanyId().equals("")) {
                    showDialogCaveatMessage(getResourceString(R.string.add_device_no_company_error));
                }
                mPresenter.onGetDPData(mChooseDeviceItemData.getCompanyId(), mChooseDeviceItemData.getFactoryAreaId());
                break;

            case R.id.tv_class:
                if (mChooseDeviceItemData.getCompanyId().equals("")) {
                    showDialogCaveatMessage(getResourceString(R.string.add_device_no_company_error));
                }
                if (mChooseDeviceItemData.getProductionPlantId().equals("")) {
                    showDialogCaveatMessage(getResourceString(R.string.add_device_no_production_plant_error));
                }
                mPresenter.onGetSHIFTData(mChooseDeviceItemData.getCompanyId(), mChooseDeviceItemData.getProductionPlantId());
                break;

            case R.id.tv_shoottype:
                if (mChooseDeviceItemData.getCompanyId().equals("")) {
                    showDialogCaveatMessage(getResourceString(R.string.add_device_no_company_error));
                }
                if (mChooseDeviceItemData.getProductionPlantId().equals("")) {
                    showDialogCaveatMessage(getResourceString(R.string.add_device_no_production_plant_error));
                }
                mPresenter.onGetTYPEData(mChooseDeviceItemData.getCompanyId(), mChooseDeviceItemData.getProductionPlantId()
                );

                break;
        }
    }

    @Override
    public void setCOData(List<COResponse> adapterData) {
        dialogString.clear();
        mMainData.setmCODataList(adapterData);
        for (COResponse mCoResponse : adapterData) {
            dialogString.add(mCoResponse.getcONM());
        }
        showItemDialog(dialogString, onCompanyDialogItemClick);
    }

    @Override
    public void setPZData(List<PZResponse> adapterData) {
        dialogString.clear();
        mMainData.setmPZDataList(adapterData);
        for (PZResponse mPZResponse : adapterData) {
            dialogString.add(mPZResponse.getmPZNM());
        }
        showItemDialog(dialogString, onFavtoryAreaDialogItemClick);
    }

    @Override
    public void setDPNMData(List<DPResponse> adapterData) {
        dialogString.clear();
        mMainData.setmDPDataList(adapterData);
        for (DPResponse mDPResponse : adapterData) {
            dialogString.add(mDPResponse.getmDPNM());
        }
        showItemDialog(dialogString, onFactoryClassDialogItemClick);
    }

    @Override
    public void setEQKDData(List<SHIFTResponse> adapterData) {
        dialogString.clear();
        mMainData.setmSHIFTDataList(adapterData);
        for (SHIFTResponse mSHIFTResponse : adapterData) {
            dialogString.add(mSHIFTResponse.getmShift());
        }
        showItemDialog(dialogString, onClassUnitDialogItemClick);
    }

    @Override
    public void setTYPEData(List<TYPEResponse> adapterData) {
        dialogString.clear();
        mMainData.setmTYPEDataList(adapterData);
        for (TYPEResponse mTYPEResponse : adapterData) {
            dialogString.add(mTYPEResponse.getmType());
        }
        showItemDialog(dialogString, onShootTypeCategoryDialogItemClick);
    }

    @Override
    protected void onPause() {
        super.onPause();
        dismissProgressDialog();
    }

    //如果能改成用retrofit加rxjava最好，已經嘗試過，可能有缺什麼，不過緊急所以先求功能
    @Override
    public void onUploadFile(final ArrayList<String> uriList, String type, final String sid) {
        uploadPath = mPresenter.onJudgmentPath(pathCompany, pathFactoryArea, pathFactoryClass, pathClass, pathShootType);
        dismissProgressDialog();
        showProgressDialog(type);


        for (String path : uriList) {
            updateMedia(path,this);
        }

        new Thread(new Runnable() {
            @Override
            public void run() {

                String path1 = uploadPath;

                OkHttpClient client = new OkHttpClient().newBuilder()
                        .connectTimeout(60, TimeUnit.SECONDS)
                        .readTimeout(60, TimeUnit.SECONDS)
                        .writeTimeout(60, TimeUnit.SECONDS)
                        .build();

                MultipartBody.Builder buildernew = new MultipartBody.Builder()
                        .setType(MultipartBody.FORM)
                        .addFormDataPart("_sid", sid)
                        .addFormDataPart("path", path1);

                for (String path : uriList) {
                    File uploadFile = new File(path);
                    Log.e("file5555555", uploadFile.length() / 1024 / 1024 + "mb");
                    buildernew.addFormDataPart("file", uploadFile.getName(),
                            RequestBody.create(MediaType.parse("application/octet-stream"), uploadFile));

                }
                RequestBody body = buildernew.build();

                Request request = new Request.Builder()
                        .addHeader("Accept", "*/*")
                        .url("https://webapp.fpcitc.com.tw/SOP/api/FileUpload/fileUpload")
                        .method("POST", body)
                        .build();

                try {
                    Response response = client.newCall(request).execute();
                    final String responsemessage = response.message();
                    final String responsebody = response.body().string();
                    JSONObject json = null;
                    try {
                        json = new JSONObject(responsebody);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    Log.e("response", responsebody);
//                    dismissProgressDialog();
                    if (json.get("success").equals("true")) {
                        MainActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                dismissProgressDialog();
                                showDialogMessage("上傳完成");
                            }
                        });
                    } else {
                        MainActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                dismissProgressDialog();
                                showDialogMessage("上傳失敗");

                            }
                        });
                    }

//                        Log.e("isSuccess",json.get("IsSuccess").toString());
                    mPresenter.onLogoutSid(sidData);                //登出sid
                } catch (final IOException | JSONException e) {
                    MainActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            dismissProgressDialog();
                            e.printStackTrace();
                            showDialogMessage("上傳失敗");
                            Log.e("error", "" + e.getMessage());
                        }
                    });
                }
            }
        }).start();
    }

    private DialogInterface.OnClickListener onCompanyDialogItemClick = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            textCompany.setText(mMainData.getmCODataList().get(which).getcONM());
            pathCompany = mMainData.getmCODataList().get(which).getcONM();
            mChooseDeviceItemData.setCompany(mMainData.getmCODataList().get(which).getcONM());
            mChooseDeviceItemData.setCompanyId(mMainData.getmCODataList().get(which).getcO());


        }
    };
    private DialogInterface.OnClickListener onFavtoryAreaDialogItemClick = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            textFactory.setText(mMainData.getmPZDataList().get(which).getmPZNM());
            pathFactoryArea = mMainData.getmPZDataList().get(which).getmPZNM();
            mChooseDeviceItemData.setFactoryAreaName(mMainData.getmPZDataList().get(which).getmPZNM());
            mChooseDeviceItemData.setFactoryAreaId(mMainData.getmPZDataList().get(which).getmPZ());


        }
    };
    private DialogInterface.OnClickListener onFactoryClassDialogItemClick = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            textUnit.setText(mMainData.getmDPDataList().get(which).getmDPNM());
            pathFactoryClass = mMainData.getmDPDataList().get(which).getmDPNM();
            mChooseDeviceItemData.setFactoryClassCode(mMainData.getmDPDataList().get(which).getmDP());
            mChooseDeviceItemData.setFactoryClass(mMainData.getmDPDataList().get(which).getmDPNM());
            mChooseDeviceItemData.setProductionPlantId(mMainData.getmDPDataList().get(which).getmPMFCT());

        }
    };

    private DialogInterface.OnClickListener onClassUnitDialogItemClick = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            textClass.setText(mMainData.getmSHIFTDataList().get(which).getmShift());
            pathClass = mMainData.getmSHIFTDataList().get(which).getmShift();
            mChooseDeviceItemData.setDeviceCategory(mMainData.getmSHIFTDataList().get(which).getmShift());
        }
    };

    private DialogInterface.OnClickListener onShootTypeCategoryDialogItemClick = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            textShootType.setText(mMainData.getmTYPEDataList().get(which).getmType());
            pathShootType = mMainData.getmTYPEDataList().get(which).getmType();
            mChooseDeviceItemData.setShootType(mMainData.getmTYPEDataList().get(which).getmType());
        }
    };

    //廣播更新媒體庫
    private static void updateMedia(String path , Context context){
        File file = new File(path);
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        intent.setData(Uri.fromFile(file));
        context.sendBroadcast(intent);
    }


    @Override
    public void changeFileNameCheckDialog(final String path, final String name) {

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        //取得自訂版面
        LayoutInflater inflater = LayoutInflater.from(MainActivity.this);
        final View v = inflater.inflate(R.layout.dialog_changefilename,null);
        builder.setTitle("請問要將檔名修改成:");
        builder.setView(v);
        builder.setCancelable(false);
        builder.setPositiveButton("確定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                EditText editChangeName = v.findViewById(R.id.etChangeName);
                changeFileName = editChangeName.getText().toString();
//                Log.e("euu",changeFileName);
                if (changeFileName.length() <= 0){
                    Toast.makeText(MainActivity.this,"請輸入要更改的檔名",Toast.LENGTH_SHORT).show();
                    changeFileNameCheckDialog(path,name);
                }else if(changeFileName.length()>0){
                    updateChangeFileName(changeFileName,path,name);
                }
            }
        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //廣播圖片or影片
                updateMedia(path,MainActivity.this);
            }
        });
        builder.create();
        builder.show();
    }



    private void updateChangeFileName(String changeFileName, final String path, String originFileName) {
        if (originFileName.contains(".jpg")){
            Log.e("type","jpg");
            File newFile = new File(path.replace(originFileName,changeFileName)+".jpg");
            File originFile = new File(path);
            originFile.renameTo(newFile);
            updateMedia(newFile.getAbsolutePath(),this);
        }else if (originFileName.contains(".mp4")){
            Log.e("type","mp4");
            File newFile = new File(path.replace(originFileName,changeFileName)+".mp4");
            File originFile = new File(path);
            originFile.renameTo(newFile);
            updateMedia(newFile.getAbsolutePath(),this);

            //跑太快畫面來不及更新
            showProgressDialog("影片改名中");
            showProgressDialog("影片改名中");
            showProgressDialog("影片改名中");
            showProgressDialog("影片改名中");
            showProgressDialog("影片改名中");
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(3000);
                        updateMedia(new File(path).getAbsolutePath(),MainActivity.this); //把舊檔案更新掉，不然媒體庫會有一個額外且不能用的檔案
                       dismissProgressDialog();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        Log.e("error",e.getMessage());
                    }
                }
            }).start();
//            updateMedia(new File(path).getAbsolutePath(),this); //把舊檔案更新掉，不然媒體庫會有一個額外且不能用的檔案
        }
    }
}
