package com.example.audiovisualrecord.ui.main;

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

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.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

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.CORequest.COResponse;
import com.example.audiovisualrecord.utils.api.apidata.searchtype.TYPEResponse;
import com.example.audiovisualrecord.utils.api.searcheqkd.EQKDResponse;
import com.example.audiovisualrecord.utils.api.searchmntfct.MNTFCTResponse;
import com.example.audiovisualrecord.utils.api.searchpmfct.PMFCTResponse;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
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 File photoFile;
    //    Bundle bag;
    String token, imageFilePath;
    int countFile = 0;

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

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

    String sidData ="";

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

    @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);
    }

    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 void openCameraIntent() {
        Intent pictureIntent = new Intent(
                MediaStore.ACTION_IMAGE_CAPTURE);
        settingSystemCamera(pictureIntent);
        if (pictureIntent.resolveActivity(getPackageManager()) != null) {
            //Create a file to store the image
            photoFile = null;
            try {
                photoFile = createImageFile();
            } catch (IOException ex) {
                // Error occurred while creating the File

            }
            if (photoFile != null) {
                Uri photoURI = FileProvider.getUriForFile(this, "com.example.audiovisualrecord.provider", photoFile);
                pictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                        photoURI);
                startActivityForResult(pictureIntent,
                        REQUEST_CAPTURE_IMAGE);
            }
        }
    }

    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 timeStamp =
                new SimpleDateFormat("yyyyMMdd_HHmmss",
                        Locale.getDefault()).format(new Date());
        String imageFileName = "IMG_" + timeStamp + "_";
        File storageDir =
                getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
        );

        imageFilePath = image.getAbsolutePath();
        return image;
    }

    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) {
            File imgFile = new File(imageFilePath);
            //照片的檔案
            if (imgFile.exists()) {
                Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
                try {
                    FileOutputStream out = new FileOutputStream(imgFile);
                    myBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
                    out.flush();
                    out.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        if (requestCode == REQUEST_VIDEO_CAPTURE && resultCode == RESULT_OK) {
            //影片的uri
            Uri videoUri = data.getData();
        }

        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()));
                Log.e("eee", getPath(data.getData()));
            }
            //照片的uri
//             mPresenter.onGetSid();
            onUploadFile(uriList, getResourceString(R.string.on_upload_image));
//            onUploadFile1();
        }

        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));
                    mPresenter.segVideo(uriList.get(i), 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);
                mPresenter.segVideo(path, name);
                Log.e("path", path);

                // TODO here====================
//            onUploadFile(compressList, getResourceString(R.string.on_upload_vedio));
                //影片的uri
            }
        }
        if (requestCode == PICK_FILE_REQUEST_CODE && resultCode == RESULT_OK) {
            Uri selectedFile = data.getData();
            Log.e("ggggg", "" + selectedFile);
            String filePath = MagicFileChooser.getAbsolutePathFromUri(this, selectedFile);
            Log.e("filePath", filePath + "");

            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:
                openCameraIntent();
                break;

            case R.id.btnGetImageFromGallery:
                pickImageFromGallery();
//                onUploadFile1();
                break;

            case R.id.btnGetVideoFromGallery:
                pickVideoFromGallery();
                break;

            case R.id.btnRecordVideo:
                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;
        }
    }

    //如果能改成用retrofit加rxjava最好，已經嘗試過三天的，可能有缺什麼，不過緊急所以先求功能
    private void onUploadFile(final ArrayList<String> uriList, String type) {

//        ongetsid();
        showProgressDialog(type);
        new Thread(new Runnable() {
            @Override
            public void run() {
//                OkHttpClient client = new OkHttpClient().newBuilder()
//                        .build();
//                MediaType mediaType = MediaType.parse("text/plain");
//                MultipartBody.Builder buildernew = new MultipartBody.Builder()
//                        .setType(MultipartBody.FORM)
//                        .addFormDataPart("AuthorizedId", "1179cf63-9f4c-4060-a0f3-201f108b20c1")
//                        .addFormDataPart("CO", "1")
//                        .addFormDataPart("CONM", "台塑")
//                        .addFormDataPart("PMFCT", "A3")
//                        .addFormDataPart("PMFCTNM", "麥寮AN廠")
//                        .addFormDataPart("EQKD", "PU")
//                        .addFormDataPart("EQKDNM", "泵浦")
//                        .addFormDataPart("EQNO", "P-166")
//                        .addFormDataPart("EQNM", "工業用水泵浦")
//                        .addFormDataPart("RecordDate", "2020/04/06")
//                        .addFormDataPart("RecordSubject", "測試")
//                        .addFormDataPart("UploadEMP", "1")
//                        .addFormDataPart("UploadNM", "新人")
//                        .addFormDataPart("UploadDATETM", "");
//                for (String path : uriList) {
//                    File uploadFile = new File(path);
//                    buildernew.addFormDataPart("", uploadFile.getName(),
//                            RequestBody.create(MediaType.parse("application/octet-stream"),
//                                    uploadFile));
//                }
//                RequestBody body = buildernew.build();
//
//                Request request = new Request.Builder()
//                        .url("https://cloud.fpcetg.com.tw/FPC/API/MTN/API_MTN/MTN/Upload")
//                        .method("POST", body)
//                        .build();

                String apiname = "SYNO.FileStation.Upload";
                String method = "upload";
                String version = "2";
                String sid = "4CY9mdpmlP5eh8KGLob3h3bqm6VvygRIu8BPwMIOy3UlYGBJ3VkM7Dgtw-hLIdH3ipntHHmJDK7y72Tio9ybLk";
                String path1 = "/仁武氯乙烯廠製造一課/1_SOP導讀";
                Boolean a = true;
                Boolean b = false;

                OkHttpClient client = new OkHttpClient().newBuilder()
                        .connectTimeout(60, TimeUnit.SECONDS)
                        .readTimeout(60, TimeUnit.SECONDS)
                        .writeTimeout(60, TimeUnit.SECONDS)
                        .build();
//                MediaType mediaType = MediaType.parse("application/octet-stream");
//                MediaType mediaType = MediaType.parse("multiparty/form-data");
                    MediaType mediaType = MediaType.parse("image/jpg");
                MultipartBody.Builder buildernew = new MultipartBody.Builder()
                        .setType(MultipartBody.FORM)
//                        .addFormDataPart("api", apiname)
//                        .addFormDataPart("method", method)
//                        .addFormDataPart("version", version)
//                        .addFormDataPart("_sid", sid)
                        .addFormDataPart("path",path1)
                        .addFormDataPart("create_parents", a.toString())
                        .addFormDataPart("overwrite", a.toString())
                        .addFormDataPart("data", "")
                        .addFormDataPart("success", "");
                Log.e("test_path",path1);
                Log.e("test_create_parents",b.toString());
                Log.e("test_overwrite",a.toString());

//                        .addFormDataPart("file", "b525a7db0c5da640_1.jpg",
//                            RequestBody.create(mediaType,new File("/storage/emulated/0/Watashi AHD V.2/temp_images/b525a7db0c5da640_1.jpg")
//                            ));
//                Log.e("test",""+buildernew.build().parts().get(0));
                for (String path : uriList) {
                    File uploadFile = new File(path);
//                    RequestBody fileBody = RequestBody.create(mediaType,uploadFile);
                    buildernew.addFormDataPart("file", uploadFile.getName(),
                            RequestBody.create(MediaType.parse("multiparty/form-data"), path));
//                    RequestBody.create(MediaType.parse("application/octet-stream"), path));

                    Log.e("test_filename", uploadFile.getName());
                    Log.e("path", path);
                    Log.e("test_file", uploadFile.getAbsolutePath());
                }
                RequestBody body = buildernew.build();
//                buildernew.build();

                Request request = new Request.Builder()
                        .url("https://fpcrtpms.synology.me:5001/webapi/entry.cgi?api="+apiname+"&method="+method+"&version="+version+"&_sid="+sidData)
//                        .url("https://fpcrtpms.synology.me:5001/webapi/entry.cgi")
                        .method("POST", body)
//                        .header("api",apiname)
//                        .header("method",method)
//                        .header("version",version)
//                        .header("_sid",sid)
//                        .addHeader("Content-Type", "text/xml; charset=utf-8")
//                        .post(buildernew.build())
                        .build();

                Log.e("test_url", request.url().toString());
                try {
                    Response response = client.newCall(request).execute();
                    Log.e("response", response.body().string());
                    dismissProgressDialog();
//                        Log.e("isSuccess",json.get("IsSuccess").toString());
                } catch (IOException e) {
                    e.printStackTrace();
                    dismissProgressDialog();
//                    showDialogCaveatMessage("上傳失敗");
                    Log.e("error", "" + e.getMessage());
                }
            }
        }).start();
    }

    private void onUploadFile1() {

        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient client = new OkHttpClient().newBuilder()
                        .build();
                MediaType mediaType = MediaType.parse("text/plain");
                RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
                        .addFormDataPart("path", "/仁武氯乙烯廠製造一課/1_SOP導讀")
                        .addFormDataPart("create_parents", "false")
                        .addFormDataPart("overwrite", "true")
                        .addFormDataPart("file","/C:/Users/PCKing/Pictures/356154.jpg",
                                RequestBody.create(MediaType.parse("application/octet-stream"),
                                        new File("/C:/Users/PCKing/Pictures/356154.jpg")))
                        .build();
                Request request = new Request.Builder()
                        .url("https://fpcrtpms.synology.me:5001/webapi/entry.cgi?api=SYNO.FileStation.Upload&method=upload&version=2&_sid=")
                        .method("POST", body)
                        .build();
                try {
                    Response response = client.newCall(request).execute();
                } catch (IOException e) {
                    e.printStackTrace();
                }
//                Call call = client.newCall(request);
//                call.enqueue(new Callback() {
//                    @Override
//                    public void onFailure(@NotNull Call call, @NotNull IOException e) {
//                        Log.e("error", "" + e.getMessage());
//                    }
//
//                    @Override
//                    public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
//                        Log.e("response", response.body().string());
//                    }
//                });
                try {
                    Response response = client.newCall(request).execute();
                    Log.e("response", response.body().string());
                } catch (IOException e) {
                    e.printStackTrace();
                    Log.e("error", "" + e.getMessage());
                }
            }
        }).start();
    }

    private void ongetsid(){
      new Thread(new Runnable() {
          @Override
          public void run() {
              OkHttpClient client = new OkHttpClient().newBuilder()
                      .build();
              Request request = new Request.Builder()
                      .url("https://webapp.fpcitc.com.tw/SOP/api/FileUpload/GetLogin")
                      .method("GET", null)
                      .addHeader("Content-Type", "application/x-www-form-urlencoded")
                      .build();
              try {
                  Response response = client.newCall(request).execute();
                  Log.e("response", response.body().string());
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }).start();
    }
    @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<MNTFCTResponse> adapterData) {
        dialogString.clear();
        mMainData.setmMNTFCTDataList(adapterData);
        for (MNTFCTResponse mMNTFCTResponse : adapterData) {
            dialogString.add(mMNTFCTResponse.getmPZNM());
        }
        showItemDialog(dialogString, onMaintenanceDialogItemClick);
    }

    @Override
    public void setDPNMData(List<PMFCTResponse> adapterData) {
        dialogString.clear();
        mMainData.setmPMFCTDataList(adapterData);
        for (PMFCTResponse mPMFCTResponse : adapterData) {
            dialogString.add(mPMFCTResponse.getmDPNM());
        }
        showItemDialog(dialogString, onProductionDialogItemClick);
    }

    @Override
    public void setEQKDData(List<EQKDResponse> adapterData) {
        dialogString.clear();
        mMainData.setmEQKDDataList(adapterData);
        for (EQKDResponse mEQKDResponse : adapterData) {
            dialogString.add(mEQKDResponse.getmShift());
        }
        showItemDialog(dialogString, onDeviceCategoryDialogItemClick);
    }

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

    @Override
    public void setSIDData(String sid) {
        sidData = sid;

    }

    private DialogInterface.OnClickListener onCompanyDialogItemClick = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            tvCompany.setText(mMainData.getmCODataList().get(which).getcONM());
            mChooseDeviceItemData.setCompany(mMainData.getmCODataList().get(which).getcONM());
            mChooseDeviceItemData.setCompanyId(mMainData.getmCODataList().get(which).getcO());
        }
    };
    private DialogInterface.OnClickListener onMaintenanceDialogItemClick = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            tvFactory.setText(mMainData.getmMNTFCTDataList().get(which).getmPZNM());
            mChooseDeviceItemData.setFactoryAreaName(mMainData.getmMNTFCTDataList().get(which).getmPZNM());
//            mChooseDeviceItemData.setMaintenancePlantCompanyId(mMainData.getmMNTFCTDataList().get(which).getmPZ());
            mChooseDeviceItemData.setFactoryAreaId(mMainData.getmMNTFCTDataList().get(which).getmPZ());

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

    private DialogInterface.OnClickListener onDeviceCategoryDialogItemClick = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            tvClass.setText(mMainData.getmEQKDDataList().get(which).getmShift());
            mChooseDeviceItemData.setDeviceCategory(mMainData.getmEQKDDataList().get(which).getmShift());
//            mChooseDeviceItemData.setDeviceCategryId(mMainData.getmEQKDDataList().get(which).getmEQKD());
        }
    };

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


}
