package com.hh.holyolm;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.preference.PreferenceManager;

import android.Manifest;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.util.Base64;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import com.hh.holyolm.model.AbsCheckItem;
import com.hh.holyolm.model.CheckItemModel2;
import com.hh.holyolm.model.InputModel;
import com.hh.holyolm.model.OptCardModel;
import com.hh.holyolm.model.PhotoGroupModel;
import com.hh.holyolm.model.PhotoItemModel;
import com.hh.holyolm.model.CheckItemModel;
import com.hh.holyolm.model.TaskModel;
import com.hh.holyolm.model.WorkRecordModel;
import com.hh.holyolm.util.FileUtil;
import com.hh.holyolm.util.HttpUtil;
import com.hh.holyolm.util.Utils;
import com.hh.holyolm.util.XmlUtil;
import com.hh.holyolm.util.ZipUtils;

import org.w3c.dom.Text;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.CopyOption;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

public class ExecTaskActivity extends AppCompatActivity {
    static final int REQUEST_CODE_IMAGE=1;
    static final int REQUEST_CODE_CAMERA=2;

    static final String USE_MODEL_TEMPLATE="Template";
    static final String USE_MODEL_EXEC="Exec";
    static final String USE_MODEL_READ="Read";

    private File taskDir;
    private String pkgPath;

    String useModel=null;// Template / Exec / Read

    String tempPath=null;
    String tempName=null;
    ImageView tempView=null;
    PhotoItemModel tempPhotoModel=null;
    String tempPhotoID=null;
    private TaskModel taskModel;
    private List<CheckItemModel> checkList;
    private List<CheckItemModel2> checkList2;
    private File libsDir;
    private String actionCardLibPath;
    WebView webView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_exec_task);

        if(ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA)!= PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(this,new String[]{android.Manifest.permission.CAMERA},1);
        }
        if(ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_MEDIA_IMAGES)!= PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_MEDIA_IMAGES},1);
        }
        if(ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},1);
        }
        //API24以上系统分享支持file:///开头
        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());
        builder.detectFileUriExposure();

        taskDir= Utils.initTaskDir(this);
        libsDir=Utils.initLibsDir(this);
        actionCardLibPath=libsDir.getAbsolutePath()+File.separator+"action"+File.separator+"ActionCardLib.xml";

        pkgPath=getIntent().getStringExtra("PkgPath");
        useModel=getIntent().getStringExtra("Model");
        if(pkgPath==null || pkgPath.isEmpty()){
            Toast.makeText(this,"参数PkgPath无效.",Toast.LENGTH_LONG).show();
            return;
        }
        if(useModel==null || useModel.isEmpty()){
            Toast.makeText(this,"参数Model无效.",Toast.LENGTH_LONG).show();
            return;
        }

        webView=findViewById(R.id.webView);
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setAllowFileAccess(true);
        webSettings.setAllowFileAccessFromFileURLs(true);
        webSettings.setAllowUniversalAccessFromFileURLs(true);

        taskModel= XmlUtil.ReadTaskInfo(pkgPath+ File.separator+"task.xml",pkgPath);
        checkList=taskModel.getCheckItemList();
        checkList2=taskModel.getCheckItem2List();

        ((TextView)findViewById(R.id.tv_card_num)).setText("工卡号："+taskModel.getCardNum());
        if(useModel.equals(USE_MODEL_TEMPLATE)){
            findViewById(R.id.btnInstance).setVisibility(View.VISIBLE);
            findViewById(R.id.btnSave).setVisibility(View.INVISIBLE);
            findViewById(R.id.btnChecker).setVisibility(View.INVISIBLE);
            findViewById(R.id.btnWorker).setVisibility(View.INVISIBLE);
            findViewById(R.id.btnSubmit).setVisibility(View.INVISIBLE);
        }else{
            findViewById(R.id.btnInstance).setVisibility(View.INVISIBLE);
            findViewById(R.id.btnSave).setVisibility(View.VISIBLE);
            findViewById(R.id.btnChecker).setVisibility(View.VISIBLE);
            findViewById(R.id.btnWorker).setVisibility(View.VISIBLE);
            findViewById(R.id.btnSubmit).setVisibility(View.VISIBLE);
            ((TextView)findViewById(R.id.tv_task_num)).setText("任务号："+taskModel.getTaskNum());
            ((TextView)findViewById(R.id.tv_plane_num)).setText("机号："+taskModel.getPlaneNum());
        }

        findViewById(R.id.btnBack).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ExecTaskActivity.this.finish();
            }
        });

        findViewById(R.id.btnInstance).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showCreateTask();
            }
        });

        findViewById(R.id.btnSave).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    XmlUtil.SaveTaskXML(pkgPath,taskModel,checkList);
                    Toast.makeText(ExecTaskActivity.this,"保存成功.",Toast.LENGTH_LONG).show();
                }catch (Exception ex){
                    Toast.makeText(ExecTaskActivity.this,"保存失败:"+ex.getMessage(),Toast.LENGTH_LONG).show();
                }

            }
        });

        findViewById(R.id.btnSubmit).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SubmitData();

            }
        });

        findViewById(R.id.btnWorker).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                inputWorker();
            }
        });
        findViewById(R.id.btnChecker).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                inputChecker();
            }
        });

        TableLayout tableLayout=findViewById(R.id.pdt_check_table);

        TableLayout.LayoutParams tlp=new TableLayout.LayoutParams();
        tlp.setMargins(2,2,2,2);

        TableRow.LayoutParams rlp=new TableRow.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT);
        rlp.setMargins(2,2,2,2);
        rlp.gravity=Gravity.CENTER_VERTICAL;

        RadioGroup.LayoutParams rglp=new RadioGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT);
        rglp.setMargins(16,16,16,16);

        LinearLayout.LayoutParams llp=new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT);
        llp.gravity=Gravity.CENTER;

        for (int i=0;i<checkList.size();i++){
            CheckItemModel itemModel=checkList.get(i);
            TableRow row=new TableRow(this);
            row.setGravity(Gravity.CENTER_VERTICAL);
            //row.setBackgroundColor(getResources().getColor(R.color.white));
            //row.setBackgroundColor(getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral80));

            //序号
            TextView tv0=new TextView(this);
            tv0.setText(itemModel.getSeq());
            tv0.setTextSize(14);
            tv0.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
            tv0.setLayoutParams(rlp);
            //tv0.setBackgroundColor(getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral80));
            row.addView(tv0);


            //工作内容
            TextView tv1=new TextView(this);
            tv1.setText(itemModel.getCheckContent());
            tv1.setTextSize(14);
            tv1.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
            tv1.setLayoutParams(rlp);
            tv1.setEms(8);
            //tv1.setBackgroundColor(getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral80));
            if(itemModel.getCheckContent()!=null && itemModel.getCheckContent().length()>30){
                String shortStr=itemModel.getCheckContent().substring(0,20)+"......";
                tv1.setText(shortStr);
                tv1.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Dialog dialog4 = new Dialog(ExecTaskActivity.this,R.style.NormalDialogStyle);
                        View dgView = View.inflate(ExecTaskActivity.this, R.layout.dialog_scroll_text, null);
                        dialog4.setContentView(dgView);//给dialog设置一个视图
                        TextView tv_txt=dgView.findViewById(R.id.tv_text);
                        tv_txt.setText(itemModel.getCheckContent());
                        dialog4.setCanceledOnTouchOutside(true);//在点击窗口外的地方可以退出
                        Window dialogWindow = dialog4.getWindow();//获取Dialog的窗口
                        //实例化窗口布局对象
                        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
                        lp.width =WindowManager.LayoutParams.WRAP_CONTENT;
                        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
                        lp.gravity = Gravity.CENTER;
                        dialogWindow.setAttributes(lp);
                        dialog4.show();
                    }
                });
            }

            row.addView(tv1);

            //检查项目部位
            TextView tv00=new TextView(this);
            tv00.setText(itemModel.getCheckRegion());
            tv00.setTextSize(14);
            tv00.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
            tv00.setLayoutParams(rlp);
            tv00.setEms(8);
            //tv0.setBackgroundColor(getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral80));
            row.addView(tv00);

            //操作卡
            if(itemModel.getCardList().size()>0){
                LinearLayout linearLayout=new LinearLayout(this);
                linearLayout.setOrientation(LinearLayout.VERTICAL);
                linearLayout.setLayoutParams(rlp);
                for (int j = 0; j < itemModel.getCardList().size(); j++) {
                    OptCardModel cardModel=itemModel.getCardList().get(j);
                    TextView tv4=new TextView(this);
                    tv4.setText(cardModel.getNumber());
                    tv4.setTextSize(14);
                    tv4.setEms(8);
                    tv4.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_START);
                    tv4.setLayoutParams(rlp);
                    //tv4.setBackgroundColor(getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral80));
                    tv4.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            OptCardModel libCard=XmlUtil.FindOptCard(actionCardLibPath,cardModel.getNumber());
                            if(libCard!=null){
                                String xmlPath=libCard.getPdfFile();
                                File xmlFile=new File(libsDir.getAbsolutePath()+File.separator+"action"+File.separator+xmlPath);
                                if(xmlFile.exists()){
                                    //Toast.makeText(ExecTaskActivity.this,""+xmlFile.getAbsolutePath(),Toast.LENGTH_LONG).show();
                                    Uri pdfUri=Uri.fromFile(xmlFile);
                                    //webView.loadUrl("file:///android_asset/pdfjs/web/viewer.html?file=" + pdfUri.toString());
                                    //webView.setVisibility(View.VISIBLE);
                                    showPdfDialog(pdfUri);
                                }else{
                                    Toast.makeText(ExecTaskActivity.this,"文件不存在："+xmlFile.getAbsolutePath(),Toast.LENGTH_LONG).show();
                                }
                            }else{
                                Toast.makeText(ExecTaskActivity.this,"操作卡库中不存在："+cardModel.getNumber(),Toast.LENGTH_LONG).show();
                            }
                        }
                    });
                    linearLayout.addView(tv4);
                }
                row.addView(linearLayout);
            }else{
                TextView tv4=new TextView(this);
                tv4.setTextSize(14);
                tv4.setEms(8);
                tv4.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_START);
                tv4.setLayoutParams(rlp);
                //tv4.setBackgroundColor(getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral80));
                row.addView(tv4);
            }


            //完成情况
            LinearLayout linearLayout=new LinearLayout(this);
            linearLayout.setOrientation(LinearLayout.HORIZONTAL);
            linearLayout.setLayoutParams(rlp);

            CheckBox checkBox=new CheckBox(this);
            if(itemModel.getIsComplete()!=null && !itemModel.getIsComplete().isEmpty()){
                checkBox.setChecked(true);
            }else{
                checkBox.setChecked(false);
            }
            checkBox.setTextSize(14);
            checkBox.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
            checkBox.setLayoutParams(llp);
            checkBox.setEms(4);
            checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                    if(b){
                        itemModel.setIsComplete("已完成");
                    }else{
                        itemModel.setIsComplete("");
                    }
                }
            });
            linearLayout.addView(checkBox);
            if(itemModel.getRecordList()!=null && itemModel.getRecordList().size()>0){
                checkBox.setEms(2);
                Button button=new Button(this);
                button.setText("...");
                button.setEms(2);
                button.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        inputRecords(itemModel);
                    }
                });
                linearLayout.addView(button);
                String val=getFirstInputValue(itemModel);
                TextView tv44=new TextView(this);
                tv44.setTextSize(14);
                tv44.setEms(6);
                tv44.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_START);
                tv44.setLayoutParams(rlp);
                tv44.setText(val);

                //tv4.setBackgroundColor(getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral80));
                linearLayout.addView(tv44);
            }
            row.addView(linearLayout);
            /*EditText et1=new EditText(this);
            et1.setText(itemModel.getIsComplete());
            et1.setTextSize(20);
            et1.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
            et1.setLayoutParams(rlp);
            et1.setEms(6);
            et1.setBackgroundColor(getResources().getColor(R.color.white));
            row.addView(et1);*/
            //执行者
            TextView tv5=new TextView(this);
            tv5.setText(itemModel.getWoker());
            tv5.setTextSize(14);
            tv5.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
            tv5.setLayoutParams(rlp);
            tv5.setEms(4);
            //tv5.setBackgroundColor(getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral80));
            row.addView(tv5);
            //复查者
            TextView tv6=new TextView(this);
            tv6.setText(itemModel.getChecker());
            tv6.setTextSize(14);
            tv6.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
            tv6.setLayoutParams(rlp);
            tv6.setEms(4);
            //tv6.setBackgroundColor(getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral80));
            row.addView(tv6);


            /*List<OptionModel> optionList=itemModel.getOptionList();
            if(optionList!=null && optionList.size()>0){
                RadioGroup radioGroup=new RadioGroup(this);
                radioGroup.setOrientation(RadioGroup.VERTICAL);
                for (int j = 0; j < optionList.size(); j++) {
                    OptionModel option=optionList.get(j);
                    RadioButton radioButton=new RadioButton(this);
                    radioGroup.addView(radioButton);
                    radioButton.setText(option.getText());
                    radioButton.setTextSize(20);
                    radioButton.setContentDescription(option.getId());
                    radioButton.setLinkTextColor(getResources().getColor(R.color.deepblue));
                    radioButton.setHintTextColor(getResources().getColor(R.color.deepblue));
                    radioButton.setLayoutParams(rglp);
                    radioButton.setChecked(option.isChecked());
                    radioButton.setOnCheckedChangeListener(new CisOnCheckedChangeListener(option.getId()));

                }
                radioGroup.setLayoutParams(rlp);
                radioGroup.setBackgroundColor(getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral80));
                row.addView(radioGroup);
            }*/

            //拍照项
            /*Button btnImg=new Button(this);
            if(itemModel.getPhotoGroup()!=null){
                btnImg.setText(String.valueOf(itemModel.getPhotoGroup().getPicNum()));
            }else {
                btnImg.setText("/");
                btnImg.setVisibility(View.INVISIBLE);
            }
            btnImg.setTextSize(14);
            btnImg.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
            btnImg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    //root.findViewById(R.id.scrollView2).setVisibility(View.VISIBLE);
                    webView.setVisibility(View.GONE);
                    LinearLayout container=findViewById(R.id.photoContainer);
                    container.removeAllViews();
                    LinearLayout photoView=GenPhotoView(itemModel.getPhotoGroup());
                    container.addView(photoView);
                }
            });*/
            //row.addView(btnImg);
            Button btnShowItem=new Button(this);
            btnShowItem.setTextSize(14);
            btnShowItem.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
            btnShowItem.setText("查看指令");
            btnShowItem.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    showCheckItemDialog(itemModel);
                }
            });
            row.addView(btnShowItem);

            row.setLayoutParams(tlp);

            row.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    showCheckItemDialog(itemModel);
                }
            });
            tableLayout.addView(row);
        }

        for (int i=0;i<checkList2.size();i++){
            CheckItemModel2 itemModel=checkList2.get(i);
            TableRow row=new TableRow(this);
            row.setGravity(Gravity.CENTER_VERTICAL);
            //row.setBackgroundColor(getResources().getColor(R.color.white));
            //row.setBackgroundColor(getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral80));

            //序号
            TextView tv0=new TextView(this);
            tv0.setText(itemModel.getSeq());
            tv0.setTextSize(14);
            tv0.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
            tv0.setLayoutParams(rlp);
            //tv0.setBackgroundColor(getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral80));
            row.addView(tv0);
            //工作内容
            TextView tv1=new TextView(this);
            tv1.setText(itemModel.getCheckContent());
            tv1.setTextSize(14);
            tv1.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
            tv1.setLayoutParams(rlp);
            tv1.setEms(8);
            //tv1.setBackgroundColor(getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral80));
            if(itemModel.getCheckContent()!=null && itemModel.getCheckContent().length()>30){
                String shortStr=itemModel.getCheckContent().substring(0,20)+"......";
                tv1.setText(shortStr);
                tv1.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Dialog dialog4 = new Dialog(ExecTaskActivity.this,R.style.NormalDialogStyle);
                        View dgView = View.inflate(ExecTaskActivity.this, R.layout.dialog_scroll_text, null);
                        dialog4.setContentView(dgView);//给dialog设置一个视图
                        TextView tv_txt=dgView.findViewById(R.id.tv_text);
                        tv_txt.setText(itemModel.getCheckContent());
                        dialog4.setCanceledOnTouchOutside(true);//在点击窗口外的地方可以退出
                        Window dialogWindow = dialog4.getWindow();//获取Dialog的窗口
                        //实例化窗口布局对象
                        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
                        lp.width =WindowManager.LayoutParams.WRAP_CONTENT;
                        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
                        lp.gravity = Gravity.CENTER;
                        dialogWindow.setAttributes(lp);
                        dialog4.show();
                    }
                });
            }

            row.addView(tv1);

            //检查项目部位
            TextView tv00=new TextView(this);
            tv00.setTextSize(14);
            tv00.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
            tv00.setLayoutParams(rlp);
            tv00.setEms(8);
            row.addView(tv00);

            //操作卡
            if(itemModel.getCardList().size()>0){
                LinearLayout linearLayout=new LinearLayout(this);
                linearLayout.setOrientation(LinearLayout.VERTICAL);
                linearLayout.setLayoutParams(rlp);
                for (int j = 0; j < itemModel.getCardList().size(); j++) {
                    OptCardModel cardModel=itemModel.getCardList().get(j);
                    TextView tv4=new TextView(this);
                    tv4.setText(cardModel.getNumber());
                    tv4.setTextSize(14);
                    tv4.setEms(8);
                    tv4.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_START);
                    tv4.setLayoutParams(rlp);
                    //tv4.setBackgroundColor(getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral80));
                    tv4.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            OptCardModel libCard=XmlUtil.FindOptCard(actionCardLibPath,cardModel.getNumber());
                            if(libCard!=null){
                                String xmlPath=libCard.getPdfFile();
                                File xmlFile=new File(libsDir.getAbsolutePath()+File.separator+"action"+File.separator+xmlPath);
                                if(xmlFile.exists()){
                                    //Toast.makeText(ExecTaskActivity.this,""+xmlFile.getAbsolutePath(),Toast.LENGTH_LONG).show();
                                    Uri pdfUri=Uri.fromFile(xmlFile);
                                    //webView.loadUrl("file:///android_asset/pdfjs/web/viewer.html?file=" + pdfUri.toString());
                                    //webView.setVisibility(View.VISIBLE);
                                    showPdfDialog(pdfUri);
                                }else{
                                    Toast.makeText(ExecTaskActivity.this,"文件不存在："+xmlFile.getAbsolutePath(),Toast.LENGTH_LONG).show();
                                }
                            }else{
                                Toast.makeText(ExecTaskActivity.this,"操作卡库中不存在："+cardModel.getNumber(),Toast.LENGTH_LONG).show();
                            }
                        }
                    });
                    linearLayout.addView(tv4);
                }
                row.addView(linearLayout);
            }else{
                TextView tv4=new TextView(this);
                tv4.setTextSize(14);
                tv4.setEms(8);
                tv4.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_START);
                tv4.setLayoutParams(rlp);
                //tv4.setBackgroundColor(getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral80));
                row.addView(tv4);
            }


            //完成情况
            LinearLayout linearLayout=new LinearLayout(this);
            linearLayout.setOrientation(LinearLayout.HORIZONTAL);
            linearLayout.setLayoutParams(rlp);

            CheckBox checkBox=new CheckBox(this);
            if(itemModel.getIsComplete()!=null && !itemModel.getIsComplete().isEmpty()){
                checkBox.setChecked(true);
            }else{
                checkBox.setChecked(false);
            }
            checkBox.setTextSize(14);
            checkBox.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
            checkBox.setLayoutParams(llp);
            checkBox.setEms(4);
            checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                    if(b){
                        itemModel.setIsComplete("已完成");
                    }else{
                        itemModel.setIsComplete("");
                    }
                }
            });
            linearLayout.addView(checkBox);
            if(itemModel.getRecordList()!=null && itemModel.getRecordList().size()>0){
                checkBox.setEms(2);
                Button button=new Button(this);
                button.setText("...");
                button.setEms(2);
                button.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        inputRecords(itemModel);
                    }
                });
                linearLayout.addView(button);

                String val=getFirstInputValue(itemModel);
                TextView tv44=new TextView(this);
                tv44.setTextSize(14);
                tv44.setEms(6);
                tv44.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_START);
                tv44.setLayoutParams(rlp);
                tv44.setText(val);

                //tv4.setBackgroundColor(getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral80));
                linearLayout.addView(tv44);
            }

            row.addView(linearLayout);
            /*EditText et1=new EditText(this);
            et1.setText(itemModel.getIsComplete());
            et1.setTextSize(20);
            et1.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
            et1.setLayoutParams(rlp);
            et1.setEms(6);
            et1.setBackgroundColor(getResources().getColor(R.color.white));
            row.addView(et1);*/
            //执行者
            TextView tv5=new TextView(this);
            tv5.setText(itemModel.getWoker());
            tv5.setTextSize(14);
            tv5.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
            tv5.setLayoutParams(rlp);
            tv5.setEms(4);
            //tv5.setBackgroundColor(getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral80));
            row.addView(tv5);
            //复查者
            TextView tv6=new TextView(this);
            tv6.setText(itemModel.getChecker());
            tv6.setTextSize(14);
            tv6.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
            tv6.setLayoutParams(rlp);
            tv6.setEms(4);
            //tv6.setBackgroundColor(getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral80));
            row.addView(tv6);


            /*List<OptionModel> optionList=itemModel.getOptionList();
            if(optionList!=null && optionList.size()>0){
                RadioGroup radioGroup=new RadioGroup(this);
                radioGroup.setOrientation(RadioGroup.VERTICAL);
                for (int j = 0; j < optionList.size(); j++) {
                    OptionModel option=optionList.get(j);
                    RadioButton radioButton=new RadioButton(this);
                    radioGroup.addView(radioButton);
                    radioButton.setText(option.getText());
                    radioButton.setTextSize(20);
                    radioButton.setContentDescription(option.getId());
                    radioButton.setLinkTextColor(getResources().getColor(R.color.deepblue));
                    radioButton.setHintTextColor(getResources().getColor(R.color.deepblue));
                    radioButton.setLayoutParams(rglp);
                    radioButton.setChecked(option.isChecked());
                    radioButton.setOnCheckedChangeListener(new CisOnCheckedChangeListener(option.getId()));

                }
                radioGroup.setLayoutParams(rlp);
                radioGroup.setBackgroundColor(getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral80));
                row.addView(radioGroup);
            }*/

            //拍照项
            /*Button btnImg=new Button(this);
            if(itemModel.getPhotoGroup()!=null){
                btnImg.setText(String.valueOf(itemModel.getPhotoGroup().getPicNum()));
            }else {
                btnImg.setText("/");
                btnImg.setVisibility(View.INVISIBLE);
            }
            btnImg.setTextSize(14);
            btnImg.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
            btnImg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    //root.findViewById(R.id.scrollView2).setVisibility(View.VISIBLE);
                    webView.setVisibility(View.GONE);
                    LinearLayout container=findViewById(R.id.photoContainer);
                    container.removeAllViews();
                    LinearLayout photoView=GenPhotoView(itemModel.getPhotoGroup());
                    container.addView(photoView);
                }
            });*/
            //row.addView(btnImg);
            Button btnShowItem=new Button(this);
            btnShowItem.setTextSize(14);
            btnShowItem.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
            btnShowItem.setText("查看措施");
            btnShowItem.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    showCheckItemDialog(itemModel);
                }
            });
            row.addView(btnShowItem);

            row.setLayoutParams(tlp);

            row.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    showCheckItemDialog(itemModel);
                }
            });
            tableLayout.addView(row);
        }

    }

    private void showCheckItemDialog(CheckItemModel2 itemModel) {
        AlertDialog.Builder customizeDialog = new AlertDialog.Builder(this);
        final View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_show_checkitem2,null);

        ((TextView)dialogView.findViewById(R.id.et_item_type)).setText(itemModel.getItemType());
        ((TextView)dialogView.findViewById(R.id.et_item_src)).setText(itemModel.getItemSrc());
        ((TextView)dialogView.findViewById(R.id.et_release_dept)).setText(itemModel.getReleaseDept());
        ((TextView)dialogView.findViewById(R.id.et_failure_type)).setText(itemModel.getFailureType());
        ((TextView)dialogView.findViewById(R.id.et_failure_sys)).setText(itemModel.getFailureSys());
        ((TextView)dialogView.findViewById(R.id.et_failure)).setText(itemModel.getFailure());
        ((TextView)dialogView.findViewById(R.id.et_check_content)).setText(itemModel.getCheckContent());
        ((TextView)dialogView.findViewById(R.id.et_work_opp)).setText(itemModel.getWorkOpp());


        customizeDialog.setTitle("查看维修指令");
        customizeDialog.setView(dialogView).setCancelable(true);
        customizeDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });

        customizeDialog.show();
    }

    private void showCheckItemDialog(CheckItemModel itemModel) {
        AlertDialog.Builder customizeDialog = new AlertDialog.Builder(this);
        final View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_show_checkitem,null);

        ((TextView)dialogView.findViewById(R.id.et_check_opp_seq)).setText(itemModel.getCheckOppSeq());
        ((TextView)dialogView.findViewById(R.id.et_check_opp)).setText(itemModel.getCheckOpp());
        ((TextView)dialogView.findViewById(R.id.et_check_region_seq)).setText(itemModel.getCheckRegionSeq());
        ((TextView)dialogView.findViewById(R.id.et_check_region)).setText(itemModel.getCheckRegion());
        ((TextView)dialogView.findViewById(R.id.et_check_seq_seq)).setText(itemModel.getCheckSeqSeq());
        ((TextView)dialogView.findViewById(R.id.et_check_seq)).setText(itemModel.getCheckSeq());
        ((TextView)dialogView.findViewById(R.id.et_main_seq)).setText(itemModel.getMainSeq());
        ((TextView)dialogView.findViewById(R.id.et_secondary_seq)).setText(itemModel.getSecondarySeq());
        ((TextView)dialogView.findViewById(R.id.et_secondary_name)).setText(itemModel.getSecondaryName());
        ((TextView)dialogView.findViewById(R.id.et_check_method)).setText(itemModel.getCheckMethod());
        ((TextView)dialogView.findViewById(R.id.et_special_task)).setText(itemModel.getSpecialTask());
        ((TextView)dialogView.findViewById(R.id.et_special_cond)).setText(itemModel.getSpecialCond());
        ((TextView)dialogView.findViewById(R.id.et_special_method)).setText(itemModel.getSpecialMethod());
        ((TextView)dialogView.findViewById(R.id.et_attention)).setText(itemModel.getAttention());
        ((TextView)dialogView.findViewById(R.id.et_warning)).setText(itemModel.getWarning());

        customizeDialog.setTitle("查看维修指令");
        customizeDialog.setView(dialogView).setCancelable(true);
        customizeDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });

        customizeDialog.show();
    }

    private void showPdfDialog(Uri pdfUri) {
        AlertDialog.Builder customizeDialog = new AlertDialog.Builder(this);
        final View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_show_pdf,null);
        WebView webView=dialogView.findViewById(R.id.webView);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setAllowFileAccess(true);
        webView.getSettings().setAllowFileAccessFromFileURLs(true);
        webView.getSettings().setAllowUniversalAccessFromFileURLs(true);
        webView.setWebViewClient(new WebViewClient());
        webView.loadUrl("file:///android_asset/pdfjs/web/viewer.html?file=" + pdfUri.toString());

        customizeDialog.setTitle("查看执行卡");
        customizeDialog.setView(dialogView).setCancelable(true);
        /*customizeDialog.setPositiveButton("关闭",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });*/
        customizeDialog.show();


    }

    private void inputRecords(CheckItemModel itemModel) {
        LinearLayout.LayoutParams llp=new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        llp.setMargins(8,2,8,2);
        LinearLayout root=new LinearLayout(this);
        root.setOrientation(LinearLayout.VERTICAL);
        HashMap<String,InputModel> inputMap=new HashMap<String,InputModel>();
        for (int i = 0; i < itemModel.getRecordList().size(); i++) {
            WorkRecordModel recordModel=itemModel.getRecordList().get(i);
            if(recordModel.getInputEles()!=null){
                LinearLayout line=new LinearLayout(this);
                line.setLayoutParams(llp);
                for (int j = 0; j < recordModel.getInputEles().size(); j++) {
                    Object obj=recordModel.getInputEles().get(j);
                    if(obj instanceof String){
                        TextView textView=new TextView(this);
                        textView.setText((String)obj);
                        line.addView(textView);
                    }
                    if(obj instanceof InputModel){
                        InputModel inputModel=(InputModel)obj;
                        EditText editText=new EditText(this);
                        editText.setSingleLine();
                        editText.setMinEms(4);
                        editText.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
                        editText.setText(inputModel.getValue());
                        editText.setTag(inputModel.getId());
                        line.addView(editText);
                        inputMap.put(inputModel.getId(),inputModel);
                    }
                }
                root.addView(line);
            }
        }
        AlertDialog.Builder inputDialog = new AlertDialog.Builder(this);
        inputDialog.setTitle("填写执行记录").setView(root).setCancelable(false);
        inputDialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        inputDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        for (int i = 0; i < root.getChildCount(); i++) {
                            LinearLayout linearLayout=(LinearLayout) root.getChildAt(i);
                            for (int j = 0; j < linearLayout.getChildCount(); j++) {
                                View field=linearLayout.getChildAt(j);
                                if(field instanceof EditText){
                                    EditText et=(EditText) field;
                                    if(et.getTag()!=null){
                                        InputModel inputModel=inputMap.get(et.getTag().toString());
                                        if(inputModel!=null){
                                            inputModel.setValue(et.getText().toString());
                                        }
                                    }
                                }
                            }
                        }
                    }
                }).show();
        //
    }

    private String getFirstInputValue(AbsCheckItem itemModel) {
        String res=null;
        for (int i = 0; i < itemModel.getRecordList().size(); i++) {
            WorkRecordModel recordModel=itemModel.getRecordList().get(i);
            for (int j = 0; j < recordModel.getInputEles().size(); j++) {
                Object obj=recordModel.getInputEles().get(j);
                if(obj instanceof InputModel){
                    InputModel inputModel=(InputModel)obj;
                    res=inputModel.getValue();
                    return res;
                }
            }
        }
        return  res;
    }

    private void inputRecords(CheckItemModel2 itemModel) {
        LinearLayout.LayoutParams llp=new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        llp.setMargins(8,2,8,2);
        LinearLayout root=new LinearLayout(this);
        root.setOrientation(LinearLayout.VERTICAL);
        HashMap<String,InputModel> inputMap=new HashMap<String,InputModel>();
        for (int i = 0; i < itemModel.getRecordList().size(); i++) {
            WorkRecordModel recordModel=itemModel.getRecordList().get(i);
            if(recordModel.getInputEles()!=null){
                LinearLayout line=new LinearLayout(this);
                line.setLayoutParams(llp);
                for (int j = 0; j < recordModel.getInputEles().size(); j++) {
                    Object obj=recordModel.getInputEles().get(j);
                    if(obj instanceof String){
                        TextView textView=new TextView(this);
                        textView.setText((String)obj);
                        line.addView(textView);
                    }
                    if(obj instanceof InputModel){
                        InputModel inputModel=(InputModel)obj;
                        EditText editText=new EditText(this);
                        editText.setSingleLine();
                        editText.setMinEms(4);
                        editText.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
                        editText.setText(inputModel.getValue());
                        editText.setTag(inputModel.getId());
                        line.addView(editText);
                        inputMap.put(inputModel.getId(),inputModel);
                    }
                }
                root.addView(line);
            }
        }
        AlertDialog.Builder inputDialog = new AlertDialog.Builder(this);
        inputDialog.setTitle("填写执行记录").setView(root).setCancelable(false);
        inputDialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        inputDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        for (int i = 0; i < root.getChildCount(); i++) {
                            LinearLayout linearLayout=(LinearLayout) root.getChildAt(i);
                            for (int j = 0; j < linearLayout.getChildCount(); j++) {
                                View field=linearLayout.getChildAt(j);
                                if(field instanceof EditText){
                                    EditText et=(EditText) field;
                                    if(et.getTag()!=null){
                                        InputModel inputModel=inputMap.get(et.getTag().toString());
                                        if(inputModel!=null){
                                            inputModel.setValue(et.getText().toString());
                                        }
                                    }
                                }
                            }
                        }
                    }
                }).show();
        //
    }

    private void inputWorker() {
        final EditText editText = new EditText(this);
        editText.setSingleLine();
        AlertDialog.Builder inputDialog = new AlertDialog.Builder(this);
        inputDialog.setTitle("工作者签字").setView(editText).setCancelable(false);
        inputDialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        inputDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String s=editText.getText().toString();
                        if(s==null || s.isEmpty()){
                            return;
                        }

                        for (CheckItemModel item:ExecTaskActivity.this.checkList) {
                            item.setWoker(s);
                        }
                        for (CheckItemModel2 item:ExecTaskActivity.this.checkList2) {
                            item.setWoker(s);
                        }

                        TableLayout tableLayout=findViewById(R.id.pdt_check_table);
                        for (int i = 1; i < tableLayout.getChildCount(); i++) {
                            TableRow row=(TableRow)tableLayout.getChildAt(i);
                            View view=row.getChildAt(5);
                            if(view instanceof TextView){
                                TextView tv=(TextView) view;
                                tv.setText(s);
                            }
                            //Toast.makeText(ExecTaskActivity.this,tv.getClass().getName(),Toast.LENGTH_SHORT).show();
                        }
                    }
                }).show();
    }

    private void inputChecker() {
        final EditText editText = new EditText(this);
        editText.setSingleLine();
        AlertDialog.Builder inputDialog = new AlertDialog.Builder(this);
        inputDialog.setTitle("复查签字").setView(editText).setCancelable(false);
        inputDialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        inputDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String s=editText.getText().toString();
                        if(s==null || s.isEmpty()){
                            return;
                        }
                        for (CheckItemModel item:ExecTaskActivity.this.checkList) {
                            item.setChecker(s);
                        }
                        for (CheckItemModel2 item:ExecTaskActivity.this.checkList2) {
                            item.setChecker(s);
                        }
                        TableLayout tableLayout=findViewById(R.id.pdt_check_table);
                        for (int i = 1; i < tableLayout.getChildCount(); i++) {
                            TableRow row=(TableRow)tableLayout.getChildAt(i);
                            View view=row.getChildAt(6);
                            if(view instanceof TextView){
                                TextView tv=(TextView) view;
                                tv.setText(s);
                            }
                            //Toast.makeText(ExecTaskActivity.this,tv.getClass().getName(),Toast.LENGTH_SHORT).show();
                        }
                    }
                }).show();
    }

    private void showCreateTask(){
        AlertDialog.Builder customizeDialog = new AlertDialog.Builder(this);
        final View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_create_task,null);
        customizeDialog.setTitle("创建任务");
        customizeDialog.setView(dialogView).setCancelable(false);
        EditText etModel = (EditText) dialogView.findViewById(R.id.et_model);
        etModel.setText(taskModel.getPlaneModel());
        customizeDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 获取EditView中的输入内容
                        EditText etModel = (EditText) dialogView.findViewById(R.id.et_model);
                        EditText etPlane = (EditText) dialogView.findViewById(R.id.et_plane_num);
                        EditText etTask = (EditText) dialogView.findViewById(R.id.et_task_num);

                        if(etModel.getText().toString().trim().isEmpty() || etPlane.getText().toString().trim().isEmpty()
                        || etTask.getText().toString().trim().isEmpty()){
                            Toast.makeText(ExecTaskActivity.this, "属性值不能为空.",Toast.LENGTH_SHORT).show();
                            return;
                        }
                        doInstanceTask(etTask.getText().toString(),etModel.getText().toString(),etPlane.getText().toString());
                    }
                });
        customizeDialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        customizeDialog.show();
    }

    private void doInstanceTask(String taskNum,String model,String planeNum) {
        String targetPath=taskDir.getAbsolutePath()+File.separator+taskNum;
        File targetDir=new File(targetPath);
        if(targetDir.exists()){
            Toast.makeText(ExecTaskActivity.this, "任务号已存在，不能重复创建："+taskNum,Toast.LENGTH_LONG).show();
            return;
        }
        try {
            FileUtil.copyDirectory(pkgPath,targetPath);
            if(!targetDir.exists()){
                Toast.makeText(ExecTaskActivity.this, "复制失败："+taskNum,Toast.LENGTH_LONG).show();
                return;
            }

            File xmlFile=new File(targetPath+File.separator+"task.xml");
            if(!xmlFile.exists()){
                Toast.makeText(ExecTaskActivity.this, "文件未找到："+xmlFile.getAbsolutePath(),Toast.LENGTH_LONG).show();
            }else{
                XmlUtil.InstanceTaskXml(xmlFile,taskNum,model,planeNum);
                Toast.makeText(ExecTaskActivity.this, "任务创建成功："+taskNum,Toast.LENGTH_LONG).show();
            }
        } catch (Exception e) {
            Toast.makeText(ExecTaskActivity.this, "创建失败："+e.getMessage(),Toast.LENGTH_LONG).show();
        }

    }



    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_IMAGE && resultCode == RESULT_OK) {
            Uri uri = data.getData();
            Cursor cursor = this.getContentResolver().query(uri, null, null, null,null);
            if (cursor != null && cursor.moveToFirst()) {
                String path = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA));
                File resFile=new File(path);
                //String tarName=GenTimestemp()+".jpg";
                String tarName=tempPhotoID+"_"+ UUID.randomUUID() +".jpg";
                File tarFile=new File(pkgPath+File.separator+"result"+File.separator+tarName);
                try {
                    Files.copy(resFile.toPath(),tarFile.toPath());
                    //Toast.makeText(this.this, tarFile.getAbsolutePath(), Toast.LENGTH_LONG).show();
                    tempView.setImageURI(Uri.fromFile(tarFile));
                    tempPhotoModel.setActualPic("result"+File.separator+tarName);
                    tempPhotoModel.setActualPicSrc("相册");
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        if (requestCode == REQUEST_CODE_CAMERA && resultCode == RESULT_OK) {
            File resFile=new File(tempPath);
            File tarFile=new File(pkgPath+File.separator+"result"+File.separator+tempName);
            if(resFile.exists()){
                Uri uri = Uri.fromFile(resFile);
                try {
                    Files.copy(resFile.toPath(),tarFile.toPath());
                    //Toast.makeText(this.this, tarFile.getAbsolutePath(), Toast.LENGTH_LONG).show();
                    tempView.setImageURI(Uri.fromFile(tarFile));

                    tempPhotoModel.setActualPic("result"+File.separator+tempName);
                    tempPhotoModel.setActualPicSrc("拍摄");
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            //Uri uri = data.getData();
            //String s=data.getType();
            //Cursor cursor = getActivity().getContentResolver().query(uri, null, null, null,null);
           /* if (cursor != null && cursor.moveToFirst()) {
                String path = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA));
                Toast.makeText(this.this, path, Toast.LENGTH_LONG).show();
            }*/
        }
    }

    private LinearLayout GenPhotoView(PhotoGroupModel photoGroupModel){
        LinearLayout.LayoutParams linePatams1=new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT);
        linePatams1.setMargins(8,4,8,4);
        linePatams1.gravity=Gravity.CENTER_HORIZONTAL;

        LinearLayout.LayoutParams linePatams2=new LinearLayout.LayoutParams(200,200);
        linePatams2.setMargins(8,4,8,4);
        linePatams2.gravity=Gravity.CENTER_HORIZONTAL;

        LinearLayout.LayoutParams linePatams3=new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);
        linePatams3.setMargins(4,4,4,4);
        linePatams3.gravity=Gravity.CENTER_HORIZONTAL;

        LinearLayout.LayoutParams linePatams4=new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT);
        linePatams4.gravity=Gravity.CENTER_HORIZONTAL;

        LinearLayout view=new LinearLayout(this);
        view.setOrientation(LinearLayout.VERTICAL);

        String path=pkgPath+File.separator+"result";
        File resultDir = new File(path);
        if(!resultDir.exists()) resultDir.mkdirs();

        if (photoGroupModel!=null && photoGroupModel.getItemList()!=null){
            List<PhotoItemModel> modelList=photoGroupModel.getItemList();
            for (int i = 0; i < modelList.size(); i++) {
                PhotoItemModel model=modelList.get(i);
                TextView tv_desc=new TextView(this);
                tv_desc.setText(model.getDesc());
                tv_desc.setTextSize(14);
                tv_desc.setEms(12);
                tv_desc.setLayoutParams(linePatams1);
                //view.addView(tv_desc);
                ///////////////////////
                LinearLayout left=new LinearLayout(this);
                left.setOrientation(LinearLayout.VERTICAL);
                left.setLayoutParams(linePatams1);

                TextView tv_left=new TextView(this);
                tv_left.setText("样例照片");
                tv_left.setTextSize(14);
                tv_left.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
                tv_left.setLayoutParams(linePatams1);

                ImageView iv_left=new ImageView(this);
                iv_left.setLayoutParams(linePatams2);
                //iv_left.setImageResource(R.drawable.ic_menu_gallery);
                /*File imageFile=new File("/sdcard/Android/data/com.hh.holycis/files/packages/exec/XXX-2023-003/sample/1.png");
                Uri imageUri=Uri.fromFile(imageFile);
                iv_left.setImageURI(imageUri);*/
                String samplePic=model.getSamplePic();
                if(samplePic==null || samplePic.isEmpty()){
                    iv_left.setImageResource(R.drawable.ic_menu_gallery);
                }else{
                    File sampleFile=new File(pkgPath+File.separator+samplePic);
                    if(sampleFile.exists()){
                        iv_left.setImageURI(Uri.fromFile(sampleFile));
                    }else{
                        iv_left.setImageResource(R.drawable.ic_menu_gallery);
                    }
                }
                iv_left.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if(iv_left.getDrawable()!=null){
                            Drawable drawable=iv_left.getDrawable();
                            ShowBigImage(drawable);
                        }
                    }
                });



                left.addView(tv_left);
                left.addView(iv_left);
                //////////////
                LinearLayout right=new LinearLayout(this);
                right.setOrientation(LinearLayout.VERTICAL);
                right.setLayoutParams(linePatams1);

                TextView tv_right=new TextView(this);
                tv_right.setText("实拍照片");
                tv_right.setTextSize(14);
                tv_right.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
                tv_right.setLayoutParams(linePatams1);

                ImageView iv_right=new ImageView(this);
                iv_right.setLayoutParams(linePatams2);
                String actPic=model.getActualPic();
                if(actPic==null || actPic.isEmpty()){
                    iv_right.setImageResource(R.drawable.ic_menu_camera);
                }else{
                    File actFile=new File(pkgPath+File.separator+actPic);
                    if(actFile.exists() && actFile.getAbsolutePath().toLowerCase().endsWith(".jpg")){
                        iv_right.setImageURI(Uri.fromFile(actFile));
                    }else{
                        iv_right.setImageResource(R.drawable.ic_menu_camera);
                    }
                }

                iv_right.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if(iv_right.getDrawable()!=null){
                            Drawable drawable=iv_right.getDrawable();
                            ShowBigImage(drawable);
                        }
                    }
                });

                Button btnPhoto=new Button(this);
                btnPhoto.setText("拍摄照片");
                btnPhoto.setLayoutParams(linePatams1);
                btnPhoto.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if(ContextCompat.checkSelfPermission(ExecTaskActivity.this, android.Manifest.permission.CAMERA)!= PackageManager.PERMISSION_GRANTED){
                            Toast.makeText(ExecTaskActivity.this,"应用未获得使用相机权限。",Toast.LENGTH_LONG).show();
                        }else{
                            //String imagePath=resultDir.getAbsolutePath()+File.separator+GenTimestemp()+".jpg";
                            //File file=new File(imagePath);
                            tempView=iv_right;
                            tempPhotoModel=model;
                            tempPhotoID=photoGroupModel.getId();
                            //Toast.makeText(this, Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath()+"", Toast.LENGTH_SHORT).show();
                            tempName=tempPhotoID+"_"+UUID.randomUUID()+".jpg";
                            tempPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath()+File.separator+tempName;
                            Uri fileUri = Uri.fromFile(new File(tempPath));
                            //Uri imageUri = Uri.fromFile(file);
                            Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
                            startActivityForResult(openCameraIntent, REQUEST_CODE_CAMERA);
                        }
                    }

                });

                Button btnView=new Button(this);
                btnView.setText("从相册选取");
                btnView.setLayoutParams(linePatams1);
                btnView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        tempView=iv_right;
                        tempPhotoModel=model;
                        tempPhotoID=photoGroupModel.getId();
                        Intent intent = new Intent(Intent.ACTION_PICK);
                        intent.setType("image/*");
                        startActivityForResult(intent, REQUEST_CODE_IMAGE);
                    }
                });
                right.addView(tv_right);
                right.addView(iv_right);
                right.addView(btnPhoto);
                right.addView(btnView);
                ////////////////

                Button btnCompare=new Button(this);
                btnCompare.setText("对比查看");
                btnCompare.setLayoutParams(linePatams1);
                btnCompare.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Drawable d1=iv_left.getDrawable();
                        Drawable d2=iv_right.getDrawable();
                        ShowTwoImage(d1,d2);
                    }

                });
                left.addView(btnCompare);

                LinearLayout l2=new LinearLayout(this);
                l2.setOrientation(LinearLayout.HORIZONTAL);
                l2.addView(left);
                l2.addView(right);
                //l2.addView(btnPhoto);
                //l2.addView(btnView);
                //l2.addView(btnCompare);
                l2.setLayoutParams(linePatams1);

                LinearLayout l1=new LinearLayout(this);
                l1.setOrientation(LinearLayout.VERTICAL);
                //l1.setBackground(getResources().getDrawable(R.drawable.border));
                l1.setBackgroundColor(getResources().getColor(R.color.white));
                l1.setLayoutParams(linePatams3);
                l1.addView(tv_desc);
                l1.addView(l2);
                view.addView(l1);
            }
        }

        return view;
    }

    void ShowBigImage(Drawable drawable){
        final Dialog dialog = new Dialog(this,R.style.NormalDialogStyle);
        View dgView=View.inflate(this,R.layout.dialog_big_image,null);
        dialog.setContentView(dgView);
        ZoomImageView imageView=dgView.findViewById(R.id.zoomView);
        imageView.setImageDrawable(drawable);
        dialog.setCanceledOnTouchOutside(true);//在点击窗口外的地方可以退出
        Window dialogWindow = dialog.getWindow();//获取Dialog的窗口
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width =WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.MATCH_PARENT;
        lp.gravity = Gravity.CENTER;
        dialogWindow.setAttributes(lp);
        dialog.show();
    }


    void ShowTwoImage(Drawable drawable1, Drawable drawable2){
        final Dialog dialog = new Dialog(this,R.style.NormalDialogStyle);
        View dgView=View.inflate(this,R.layout.dialog_two_image,null);
        dialog.setContentView(dgView);
        ZoomImageView imageView1=dgView.findViewById(R.id.zoomView1);
        imageView1.setImageDrawable(drawable1);
        ZoomImageView imageView2=dgView.findViewById(R.id.zoomView2);
        imageView2.setImageDrawable(drawable2);
        dialog.setCanceledOnTouchOutside(true);//在点击窗口外的地方可以退出
        Window dialogWindow = dialog.getWindow();//获取Dialog的窗口
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width =WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.MATCH_PARENT;
        lp.gravity = Gravity.CENTER;
        dialogWindow.setAttributes(lp);
        dialog.show();
    }

    public void SubmitData() {
        XmlUtil.SaveTaskXML(pkgPath,taskModel,checkList);
        AlertDialog.Builder builder = new AlertDialog.Builder(ExecTaskActivity.this);
        builder.setTitle("确认");
        builder.setMessage("当前任务提交后无法继续修改，是否确定提交？");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                File submitDir = initSubmitDir();
                String pkgName = pkgPath.substring(pkgPath.lastIndexOf(File.separator));
                String destPath = submitDir + File.separator + pkgName + ".zip";
                ShowWaiting("正在压缩数据包，请稍等.....");
                DoZipTask doZipTask = new DoZipTask(pkgPath, destPath, false);
                doZipTask.execute();

                //AssmCheckActivity.this.finish();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
            }
        });
        builder.show();

    }

    protected File initSubmitDir(){
        String pkgPath=this.getExternalFilesDir("packages").getAbsolutePath();
        File zipsPath=new File(pkgPath+ File.separator+"submit");
        if(!zipsPath.exists()) zipsPath.mkdirs();
        return zipsPath;
    }
    ProgressDialog pd=null;
    void ShowWaiting(String message){
        pd = new ProgressDialog(this);//初始化等待条
        pd.setMessage(message);//等待显示条的信息
        pd.setCanceledOnTouchOutside(false);
        pd.show();//等待显示条
    }
    void CloseWaiting(){
        pd.dismiss();
    }

    class DoZipTask extends AsyncTask<String, Integer, String> {
        String pkgPath;
        String zipPath;
        boolean deleteSrc;

        DoZipTask(String pkgPath, String zipPath, boolean deleteSrc) {
            this.pkgPath = pkgPath;
            this.zipPath = zipPath;
            this.deleteSrc = deleteSrc;
        }

        @Override
        protected String doInBackground(String... params) {
            String result;
            try {
                File targetFile = new File(zipPath);
                File bufferDir = new File(targetFile.getParent() + File.separator + "buffer");
                if (!bufferDir.exists()) bufferDir.mkdirs();
                File bufferFile = new File(bufferDir.getAbsolutePath() + File.separator + targetFile.getName());
                if (bufferFile.exists()) bufferFile.delete();
                /*FileOutputStream fos1 = new FileOutputStream(new File(zipPath));*/
                FileOutputStream fos1 = new FileOutputStream(bufferFile);
                ZipUtils.toZip(pkgPath, fos1, true);
                if (bufferFile.exists()) bufferFile.renameTo(targetFile);
                result = zipPath;
            } catch (Exception e) {
                result = "ERROR:" + e.getMessage();
                //throw new RuntimeException(e);
            }
            //将结果返回给onPostExecute方法
            return result;
        }
        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            //CisAbsCheckActivity.this.ContinueUpload(result);
            //删除压缩前文件夹
            if(deleteSrc){
                File srcDir=new File(pkgPath);
                FileUtil.deleteFile(srcDir);
            }
            CloseWaiting();
            //ExecTaskActivity.this.finish();
            ExecTaskActivity.this.ContinueUpload(result);
        }

    }

    void ContinueUpload(String filePath){
        Log.d(ExecTaskActivity.class.getName(), "ContinueUpload: "+filePath);
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        String url=prefs.getString("uploadurl","");
        //String url="http://192.168.0.116:31101/aviationmaintenance/main/noauth/uploadinstancedata";
        DoUploadTask uploadTask=new DoUploadTask(url,filePath);
        uploadTask.execute();
    }

    class DoUploadTask extends AsyncTask<String, Integer, String> {
        String url;
        String zippath;
        String dir;
        DoUploadTask(String url,String zippath){
            this.url=url;
            this.zippath=zippath;
        }
        @Override
        protected String doInBackground(String... params) {
            //WebServiceUtil util=new WebServiceUtil();
            String result=null;
            try {
                File zipFile=new File(zippath);
                if(!zipFile.exists()) return "ERROR:Zip文件不存在,"+zippath;
                HttpUtil.okHttpUploadFile(url,zipFile);

            } catch (Exception e) {
                e.printStackTrace();
                result="ERROR:上传失败,"+e.getMessage();
            }
            result="上传成功.";
            //将结果返回给onPostExecute方法
            return result;
        }

        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            // 将WebService返回的结果显示在TextView中
            //resultView.setText(result);
            Toast.makeText(ExecTaskActivity.this,result,Toast.LENGTH_LONG).show();
            //ExecTaskActivity.this.finish();
        }
    }
}