package com.sipai.jspatrol.Fault;

import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hitomi.tilibrary.transfer.TransferConfig;
import com.hitomi.tilibrary.transfer.Transferee;
import com.sipai.jspatrol.Bean.Fault;
import com.sipai.jspatrol.Bean.Picture;
import com.sipai.jspatrol.Bean.User;
import com.sipai.jspatrol.Fault.adapter.PicAdapter;
import com.sipai.jspatrol.R;
import com.sipai.jspatrol.URL.MethodURL;
import com.sipai.jspatrol.utils.OKHttpUtils;
import com.vansz.glideimageloader.GlideImageLoader;

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

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import cn.pedant.SweetAlert.SweetAlertDialog;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class NewFaultDetailActivity extends AppCompatActivity implements View.OnClickListener{
    private TextView tv_company,tv_processsection,tv_abnormitydescription,tv_remark,tv_equs,tv_sub_man,tv_sub_time;
    private LinearLayout ll_equ;
    private LinearLayout ll_todo;//生成缺陷
    private TextView tv_receiver,tv_fault_type;
    private Spinner sp_dispose_type;
    private String st_dispose_type;
    private String is_make_todo = "";
    private String st_sel_receiver_id = "";
    private EditText edt_complete_date;
    private Fault mfault;
    private List<User> receivers = new ArrayList<>();
    private List<User> sel_receivers = new ArrayList<>();
    private static final int SEND_RECEIVERS = 131;
    private Calendar cal;
    private int year,month,day,hour,minute;
    private String mseriverip;
    private RecyclerView rc_pic;
    private List<Picture> pics = new ArrayList<>();
    private PicAdapter picAdapter;
    private LinearLayoutManager stmanager;
    private Button btn_sub;
    private SweetAlertDialog pDialog;
    private ImageView iv;
    private Transferee transferee;
    private EditText edt_planMoney;
    private String planMoney = "";


    public static void actionStart(Context context, Fault fault, String todo){
        Intent intent = new Intent(context, NewFaultDetailActivity.class);
        intent.putExtra("fault",fault);
        intent.putExtra("todo",todo);
        context.startActivity(intent);
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_fault_detail);
        init();
        getNowData();
        initView();
        initData();
        getPic();
        if (is_make_todo.equals("yes")){
            ll_todo.setVisibility(View.VISIBLE);
            getReceiver();
        }else {
            ll_todo.setVisibility(View.GONE);
        }
    }

    private void getPic() {
        HashMap<String,String> map = new HashMap<>();
        map.put("masterId",mfault.getId());
        map.put("tbName","tb_maintenance_problem_fille");
        OKHttpUtils.getClient().newCall(OKHttpUtils.OKHttpRequest(map, mServer, MethodURL.GetFaultPics_Method)).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                loadPicFail(e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                pics = getPicData(res);
                updatePic();
            }
        });
    }

    private void loadPicFail(IOException e) {
        if (!NewFaultDetailActivity.this.isFinishing()) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(NewFaultDetailActivity.this, "图片获取失败：" + e.toString(), Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    private void updatePic() {
        if (!NewFaultDetailActivity.this.isFinishing()){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (pics.size()>0) {
                        List<String> ivUrls = new ArrayList<>();
                        for (int i=0;i<pics.size();i++){
                            ivUrls.add(pics.get(i).getAbspath());
                        }
                        TransferConfig config = TransferConfig.build()
                                .setSourceUrlList(ivUrls)
                                .setDuration(350)
                                .setImageLoader(GlideImageLoader.with(getApplicationContext()))
                                .bindRecyclerView(rc_pic, R.id.moudle_new_fault_detail_rc_pic);
                        rc_pic.setVisibility(View.VISIBLE);
                        picAdapter = new PicAdapter(pics, NewFaultDetailActivity.this, new PicAdapter.PicAdapterOnClickListener() {
                            @Override
                            public void onItemClick(View v, int position) {
                                config.setNowThumbnailIndex(position);
                                transferee.apply(config).show();
                            }
                        });
                        rc_pic.setAdapter(picAdapter);
                        stmanager = new LinearLayoutManager(NewFaultDetailActivity.this);
                        stmanager.setOrientation(LinearLayoutManager.HORIZONTAL);
                        rc_pic.setLayoutManager(stmanager);
                    }else {
                        rc_pic.setVisibility(View.GONE);
                    }
                }
            });
        }
    }

    private List<Picture> getPicData(String response) {
        List<Picture> list = new ArrayList<>();
        try {
            JSONArray aNews = new JSONArray(response);
            for (int i=0;i<aNews.length();i++){
                Picture item = new Picture();
                item.setId(aNews.getJSONObject(i).get("id").toString());
                String abs = aNews.getJSONObject(i).get("abspath").toString();
                String url = "http://"+mseriverip.substring(0,mseriverip.length())+"////UploadFile////MaintenanceProblem////"+abs.substring(abs.lastIndexOf("\\")+1,abs.length());
                item.setAbspath(url);
                list.add(item);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return list;
    }

    private void getNowData() {
        cal=Calendar.getInstance();
        year=cal.get(Calendar.YEAR);       //获取年月日时分秒
        month=cal.get(Calendar.MONTH);   //获取到的月份是从0开始计数
        day=cal.get(Calendar.DAY_OF_MONTH);
        hour = cal.get(Calendar.HOUR_OF_DAY);
        minute = cal.get(Calendar.MONTH);
    }

    private void getReceiver() {
        HashMap<String,String> map = new HashMap<>();
        map.put("search_pid",mBizid);
        OKHttpUtils.getClient().newCall(OKHttpUtils.OKHttpRequest(map, mServer, MethodURL.GETUSERLISt_Method)).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                String a = e.toString();
                if (!NewFaultDetailActivity.this.isFinishing()){
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            new SweetAlertDialog(NewFaultDetailActivity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("提示")
                                    .setContentText("人员列表获取失败，请重试！")
                                    .setConfirmText("重试")
                                    .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                        @Override
                                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                                            sweetAlertDialog.dismissWithAnimation();
                                            getReceiver();
                                        }
                                    }).show();
                        }
                    });
                }
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                receivers = parseReceiver(res);
            }
        });
//        PersistentCookieStore myCookieStore = new PersistentCookieStore(this);
//        RequestParams params = new RequestParams();
//        params.put("search_pid",mBizid);
//        params.put("rows","1000");
//        AsyncHttpClient client = new AsyncHttpClient();
//        client.setCookieStore(myCookieStore);
//        client.post(mServer+"user/getUsers.do?", params, new AsyncHttpResponseHandler() {
//            @Override
//            public void onSuccess(String response) {
//                receivers = parseReceiver(response);
//            }
//
//            @Override
//            public void onStart() {
//                super.onStart();
//            }
//
//            @Override
//            public void onFinish() {
//                super.onFinish();
//            }
//
//            @Override
//            public void onFailure(final Throwable error) {
//                super.onFailure(error);
//
//            }
//        });
    }

    private List<User> parseReceiver(String response) {
        List<User> list = new ArrayList<>();
        try {
            JSONObject jsonObject = new JSONObject(response);
            JSONArray aNews = new JSONArray(jsonObject.getString("rows"));
            for (int i=0;i<aNews.length();i++){
                User item = new User();
                item.setId(aNews.getJSONObject(i).get("id").toString());
                item.setCaption(aNews.getJSONObject(i).get("caption").toString());
                item.setName(aNews.getJSONObject(i).get("name").toString());
                list.add(item);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return list;
    }

    private void initData() {

        if (mfault.getBiz()!=null&&mfault.getBiz().getName().length()>0){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    tv_company.setText(mfault.getBiz().getName());
                    tv_processsection.setText(mfault.getProcessSection().getName());
                    tv_abnormitydescription.setText(mfault.getAbnormityDescription());
                    tv_remark.setText(mfault.getRemark());
                    tv_equs.setText(mfault.getEquipmentNames());
                    tv_sub_man.setText(mfault.getInsuser());
                    tv_sub_time.setText(mfault.getInsdt().substring(5, 16));
                }
            });
        }
    }

    private void initView(){
        TextView tv_title = findViewById(R.id.moudle_back_title_tv_title);
        tv_title.setText("异常详情");
        ImageView btn_back = findViewById(R.id.moudle_back_title_iv_back);
        btn_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        pDialog = new SweetAlertDialog(this, SweetAlertDialog.PROGRESS_TYPE);
        pDialog.getProgressHelper().setBarColor(Color.parseColor("#419DE4"));
        pDialog.setTitleText("数据上传中...");
        pDialog.setCancelable(true);
        pDialog.setCanceledOnTouchOutside(true);
        tv_company = findViewById(R.id.moudle_new_fault_detail_tv_company);
        tv_processsection = findViewById(R.id.moudle_new_fault_detail_tv_processsection);
        tv_abnormitydescription = findViewById(R.id.moudle_new_fault_detail_tv_abnormitydescription);
        tv_remark = findViewById(R.id.moudle_new_fault_detail_tv_remark);
        ll_equ = findViewById(R.id.moudle_new_fault_detail_ll_equ);
        tv_equs = findViewById(R.id.moudle_new_fault_detail_tv_equs);
        tv_sub_man = findViewById(R.id.moudle_new_fault_detail_tv_sub_man);
        tv_sub_time = findViewById(R.id.moudle_new_fault_detail_tv_sub_time);
        ll_todo = findViewById(R.id.moudle_new_fault_detail_ll_todo);
        sp_dispose_type = findViewById(R.id.moudle_new_fault_detail_sp);
        final String[] repairtypes = getResources().getStringArray(R.array.dispose_type);
        ArrayAdapter repairtypeAdapter = new ArrayAdapter(this, R.layout.item_normal_little_spin, R.id.moudle_normal_little_spin_tv_title, repairtypes);
        sp_dispose_type.setAdapter(repairtypeAdapter);
        sp_dispose_type.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                st_dispose_type = String.valueOf(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                st_dispose_type = "0";
            }
        });
        edt_complete_date = findViewById(R.id.moudle_new_fault_detail_edt_complete_date);
        edt_complete_date.setOnClickListener(this);
        //在TextView上显示日期
        String smonth = "";
        String sday = "";
        String shour = "";
        String smin = "00";
        //在TextView上显示日期
        if (month<9){
            smonth = "0"+String.valueOf(month+1);
        }else {
            smonth = String.valueOf(month+1);
        }
        if (day<10){
            sday = "0"+String.valueOf(day);
        }else {
            sday = String.valueOf(day);
        }
        if (hour<10){
            shour = "0"+String.valueOf(hour);
        }else {
            shour = String.valueOf(hour);
        }
        transferee = Transferee.getDefault(this);
        edt_complete_date.setText(year+"-"+smonth+"-"+sday+" "+shour+":"+"00:00");
        edt_complete_date.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                //创建DatePickerDialog对象
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    DatePickerDialog dpd = new DatePickerDialog(NewFaultDetailActivity.this, Datelistener, year, month, day);
                    dpd.show();//显示DatePickerDialog组件
                }
                return false;
            }
        });
        edt_planMoney = findViewById(R.id.moudle_new_fault_detail_edt_planMoney);
        tv_receiver = findViewById(R.id.moudle_new_fault_detail_tv_receiver);
        tv_receiver.setOnClickListener(this);
        tv_fault_type = findViewById(R.id.moudle_new_fault_detail_tv_fault_type);
        tv_fault_type.setOnClickListener(this);
        btn_sub = findViewById(R.id.moudle_new_fault_detail_btn_sub);
        btn_sub.setOnClickListener(this);
        rc_pic = findViewById(R.id.moudle_new_fault_detail_rc_pic);
//        picAdapter = new PicAdapter(pics,NewFaultDetailActivity.this);
//        rc_pic.setAdapter(picAdapter);
        stmanager = new LinearLayoutManager(NewFaultDetailActivity.this);
        stmanager.setOrientation(LinearLayoutManager.HORIZONTAL);
        rc_pic.setLayoutManager(stmanager);
    }

    private DatePickerDialog.OnDateSetListener Datelistener=new DatePickerDialog.OnDateSetListener()
    {
        @Override
        public void onDateSet(DatePicker view, int myyear, int monthOfYear, int dayOfMonth) {
            //修改year、month、day的变量值，以便以后单击按钮时，DatePickerDialog上显示上一次修改后的值
            year=myyear;
            month=monthOfYear;
            day=dayOfMonth;
            //更新日期
            updateDate();
        }
        //当DatePickerDialog关闭时，更新日期显示
        private void updateDate()
        {
            //在TextView上显示日期
            TimePickerDialog dpd=new TimePickerDialog(NewFaultDetailActivity.this,Timelistener,hour,minute,true);
            dpd.show();//显示DatePickerDialog组件
        }
    };
    private TimePickerDialog.OnTimeSetListener Timelistener=new TimePickerDialog.OnTimeSetListener()
    {
        @Override
        public void onTimeSet(TimePicker view, int hours, int minutes) {
            //修改year、month、day的变量值，以便以后单击按钮时，DatePickerDialog上显示上一次修改后的值
            hour=hours;
            minute=minutes;
            //更新日期
            updateDate();
        }
        //当DatePickerDialog关闭时，更新日期显示
        private void updateDate()
        {
            //在TextView上显示日期
            String smonth = "";
            String sday = "";
            String shour = "";
            String smin = "00";
            //在TextView上显示日期
            if (month<9){
                smonth = "0"+String.valueOf(month+1);
            }else {
                smonth = String.valueOf(month+1);
            }
            if (day<10){
                sday = "0"+String.valueOf(day);
            }else {
                sday = String.valueOf(day);
            }
            if (hour<10){
                shour = "0"+String.valueOf(hour);
            }else {
                shour = String.valueOf(hour);
            }
            //在TextView上显示日期
            if(edt_complete_date.isFocused()){
                edt_complete_date.setText(year+"-"+smonth+"-"+sday+" "+shour+":"+"00:00");
            }
        }
    };


    /**
     * 初始化
     */
    private String mServer;
    private String mUsername;
    private String mPassword;
    private String mUserid;
    private String mCaption;
    private String mBizid;
    private String mGroup;
    private String role;
    public void init(){
        SharedPreferences sharedPre=getSharedPreferences("config", MODE_PRIVATE);
        role = sharedPre.getString("role","");
        mServer=sharedPre.getString("server", "");
        mseriverip=sharedPre.getString("serverip", "");
        mUsername=sharedPre.getString("username", "");
        mPassword=sharedPre.getString("password", "");
        mUserid=sharedPre.getString("userid", "");
        mCaption=sharedPre.getString("caption", "");
        mBizid=sharedPre.getString("bizid", "");
        mGroup=sharedPre.getString("group", "");
        mfault = (Fault) getIntent().getSerializableExtra("fault");
        is_make_todo = getIntent().getStringExtra("todo");
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.moudle_new_fault_detail_edt_complete_date:
                break;
            case R.id.moudle_new_fault_detail_tv_receiver:
                if (receivers.size()>0) {
                    Intent intent = new Intent(NewFaultDetailActivity.this, PersonSelectorActivity.class);
                    intent.putExtra("users", (Serializable) receivers);
                    startActivityForResult(intent,SEND_RECEIVERS);
                }else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            new SweetAlertDialog(NewFaultDetailActivity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("提示")
                                    .setContentText("暂未配置接收人")
                                    .show();
                        }
                    });
                }
                break;
            case R.id.moudle_new_fault_detail_tv_fault_type:
                break;
            case R.id.moudle_new_fault_detail_btn_sub:
                sub();
                break;
        }
    }

    private void pDialogHide() {
        if (!NewFaultDetailActivity.this.isFinishing()) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    pDialog.hide();
                }
            });
        }
    }

    private void pDialogshow() {
        if (!NewFaultDetailActivity.this.isFinishing()) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    pDialog.show();
                }
            });
        }
    }

    /*
    生成缺陷
     */
    private void sub() {
        pDialogshow();
        if (edt_planMoney.getText()!=null&&!edt_planMoney.getText().toString().isEmpty()){
            planMoney = edt_planMoney.getText().toString();
        }
        HashMap<String,String> map = new HashMap<>();
        map.put("maintenanceWay",st_dispose_type);
        map.put("plannedenddt",edt_complete_date.getText().toString());
        map.put("solver",st_sel_receiver_id);
        map.put("planMoney",planMoney);
        map.put("problemtypeid","");
        map.put("ids",mfault.getId());
        OKHttpUtils.getClient().newCall(OKHttpUtils.OKHttpRequest(map, mServer, MethodURL.IssuedFault_Method)).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                String a = e.toString();
                pDialogHide();
                if (!NewFaultDetailActivity.this.isFinishing()) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(NewFaultDetailActivity.this, "生成缺陷失败：" + e.toString(), Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                pDialogHide();
                if (res.equals("1")||res.equals("2")){
                    SubSuccess();
                }else {
                    SubFail();
                }
            }
        });
    }

    private void SubFail() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                new SweetAlertDialog(NewFaultDetailActivity.this, SweetAlertDialog.ERROR_TYPE)
                        .setTitleText("上传失败，请重试")
                        .setConfirmText("确认")
                        .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                            @Override
                            public void onClick(SweetAlertDialog sweetAlertDialog) {
                                sweetAlertDialog.dismissWithAnimation();
                            }
                        }).show();
            }
        });
    }

    private void SubSuccess() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                new SweetAlertDialog(NewFaultDetailActivity.this, SweetAlertDialog.SUCCESS_TYPE)
                        .setTitleText("上传成功")
                        .setConfirmText("确认")
                        .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                            @Override
                            public void onClick(SweetAlertDialog sweetAlertDialog) {
                                sweetAlertDialog.dismissWithAnimation();
                                finish();
                            }
                        }).show();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case SEND_RECEIVERS:
                if (resultCode == RESULT_OK) {
                    sel_receivers = (List<User>) data.getSerializableExtra("sel");
                    String suser = "";
                    st_sel_receiver_id = "";
                    if (sel_receivers.size() > 0) {
                        for (int i = 0; i < sel_receivers.size(); i++) {
                            if (i == 0) {
                                suser = sel_receivers.get(i).getCaption();
                                st_sel_receiver_id = sel_receivers.get(i).getId();
                            } else if (0<i &&i < sel_receivers.size()) {
                                suser = suser + "," + sel_receivers.get(i).getCaption();
                                st_sel_receiver_id = st_sel_receiver_id + "," + sel_receivers.get(i).getId();
                            }
                        }
                    }
                    final String st = suser;
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (sel_receivers.size() > 0) {
                                tv_receiver.setText(st);
                            }
                        }
                    });
                    break;
                }
        }
    }
}
