package com.fxy.main.fragment;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.elvishew.xlog.XLog;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.fxy.baselibrary.base.BaseFragment;
import com.fxy.baselibrary.language.other.CommSharedUtil;
import com.fxy.baselibrary.tddialog.TDialog;
import com.fxy.baselibrary.tddialog.base.BindViewHolder;
import com.fxy.baselibrary.tddialog.base.TBaseAdapter;
import com.fxy.baselibrary.tddialog.list.TListDialog;
import com.fxy.baselibrary.tddialog.listener.OnBindViewListener;
import com.fxy.baselibrary.util.DataCleanManager;
import com.fxy.baselibrary.util.JsonUtil;
import com.fxy.baselibrary.util.RxTimeTool;
import com.fxy.baselibrary.util.StringUtils;
import com.fxy.baselibrary.views.dialog.RxDialogZoomImageView;
import com.fxy.BuildConfig;
import com.fxy.R;
import com.fxy.base.SetLanguageActivity;
import com.fxy.bean.ActionBean;
import com.fxy.common.FiledUpload;
import com.fxy.constant.BaseConfig;
import com.fxy.constant.SPCache;
import com.fxy.login.LoginActivity;
import com.fxy.mine.BlueSettingActivity;
import com.fxy.mine.ElectronicScaleActivity;
import com.fxy.mine.FeedbackActivity;
import com.fxy.mine.PictureSelectorActivity;
import com.fxy.mine.ScanSettingActivity;
import com.fxy.mine.VersionContentActivity;
import com.fxy.net.MyDialogCallback;
import com.fxy.net.Urls;
import com.fxy.utils.DeviceIdUtils;

import org.json.JSONObject;

import java.io.File;
import java.util.Arrays;
import java.util.Collections;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * 首页个人中心页
 * @author James.Jiang
 * @date 2020-03-02
 */
public class MineFragment extends BaseFragment {

    Unbinder bind;

    /**
     * 用户头像
     */
    @BindView(R.id.iv_avatar)
    ImageView ivAvatar;

    /**
     * 用户名称
     */
    @BindView(R.id.tv_name)
    TextView tvName;

    /**
     * 系统缓存
     */
    @BindView(R.id.tv_cachesize)
    TextView tvCachesize;

    @BindView(R.id.rl_picture_selector)
    LinearLayout rlPictureSelector;



    /**
     * 系统版本
     */
    @BindView(R.id.tv_version)
    TextView tvVersion;

    private String filesDir = "";

    private String strName = "";

    @Override
    protected int getLayoutRes() {
        return R.layout.fragment_homemine;
    }

    @Override
    protected void initView(View rootView) {
        bind = ButterKnife.bind(this, rootView);
    }

    @Override
    public void onResume() {
        super.onResume();
        try {
            tvCachesize.setText(DataCleanManager.getTotalCacheSize(getApplicationContext()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        //从缓存获取
        SPCache sp = SPCache.getInstance(getActivity());
        strName = sp.getWareHouseName();
        // 登陆获取用户信息是异步的会导致取不到，这里重新取一次
        if (!strName.isEmpty()){
            tvName.setText(sp.getUserName()+"("+sp.getAccountName()+")\n" + strName);
        }

        getUserInfo();
        //GlideUtil.getInstance().loadCircleImage(getActivity(), ivAvatar, sp.getAvatarUrl());
        //tvVersion.setText(getVersionName(getActivity()));不显示正式本版号
        tvVersion.setText("");

        filesDir = "/sdcard/cargo-pda/pda-log/"+BuildConfig.BUILD_TYPE+"/";


        CommSharedUtil commSharedUtil = CommSharedUtil.getInstance(getActivity());

        String service_type  = commSharedUtil.getString(BaseConfig.SERVICE_TYPE,"PROD");

        if (!service_type.toUpperCase().equals("DEV")){
            rlPictureSelector.setVisibility(View.GONE);
        }
    }
    private String getVersionName(Context context) {
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            return info.versionName;
        } catch (Exception e) {
            e.printStackTrace();
            return getString(R.string.str_unkonw_version);
        }
    }
    /**
     * 获取用户详细信息
     */
    private void getUserInfo(){
        String serviceAddress = CommSharedUtil.getInstance(getActivity()).getString(BaseConfig.SERVICE_ADDRESS);
        OkGo.<String>post(serviceAddress + Urls.GET_USER_INFO)
                .execute(new MyDialogCallback(getApplicationContext(), true, false) {
                    @Override
                    public void onSuccess(com.lzy.okgo.model.Response<String> response) {
                        super.onSuccess(response);
                        try {
                            ActionBean bean = JsonUtil.getObject(response.body(), ActionBean.class);
                            if (bean.code == 1 && StringUtils.isNotEmpty(bean.data)) {
                                JSONObject data = new JSONObject(bean.data);
                                String user_account = data.getString("user_account");
                                String user_name = data.getString("user_name");
                                String company_name = data.getString("company_name");

                                SPCache spCache = SPCache.getInstance(getActivity());
                                spCache.setUserName(user_name);
                                spCache.setAccountName(user_account);
                                spCache.setUserPhone(data.getString("mobile"));
                                spCache.setCompanyName(company_name);
                                String strName = company_name;

                                if (data.has("resource_type") && data.has("resource_domain")&& data.has("resource_prefix")){
                                    spCache.setResourceHost(data.getString("resource_domain"));
                                    spCache.setResourceType(data.getString("resource_type"));
                                    spCache.setResourcePrefix(data.getString("resource_prefix"));
                                    spCache.setResourceRegion(data.getString("resource_region"));
                                    spCache.setResourceBucket(data.getString("resource_bucket"));
                                }

                                tvName.setText(user_name+"("+user_account+")\n" + strName);
                            }else{
                                XLog.e("获取用户信息失败:" + bean.msg);
                            }
                        } catch (Exception e) {
                            XLog.e("获取用户信息失败:" + e.getMessage());
                        }
                    }
                });
    }

    @Override
    protected void getBundleExtras(Bundle bundle) {

    }

    @Override
    protected void initLogic() {
    }

    @OnClick({R.id.iv_avatar,R.id.rl_account_feedback,R.id.rl_blue_setting,R.id.rl_scan_setting,R.id.rl_account_wipeCache,
            R.id.rl_account_versionUpdate,R.id.rl_language_change, R.id.tv_exit,R.id.rl_electronic_scale,R.id.rl_upload_files,
            R.id.rl_picture_selector})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_avatar:
                if(!TextUtils.isEmpty(SPCache.getInstance(getActivity()).getAvatarUrl()) && SPCache.getInstance(getActivity()).getAvatarUrl().startsWith("http")){
                    RxDialogZoomImageView rxDialogZoomImageView = new RxDialogZoomImageView(getActivity());
                    rxDialogZoomImageView.setImagePath(SPCache.getInstance(getActivity()).getAvatarUrl());
                    rxDialogZoomImageView.show();
                }
                break;
            case R.id.rl_blue_setting:
                intent2Page(BlueSettingActivity.class, false);
                break;
            case R.id.rl_scan_setting:
                intent2Page(ScanSettingActivity.class, false);
                break;

            case R.id.rl_account_feedback:
                intent2Page(FeedbackActivity.class, false);
                break;
             case R.id.rl_language_change:
                 intent2Page(SetLanguageActivity.class, false);
                break;
            case R.id.rl_account_wipeCache:
                new AlertDialog.Builder(getActivity())
                        .setTitle(R.string.str_wipe_cache)
                        .setMessage(R.string.str_submit_wipe_cache)
                        .setNegativeButton(R.string.str_cancel, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                dialogInterface.dismiss();
                            }
                        }).setPositiveButton(R.string.str_submit, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                        tvCachesize.setText("");
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                DataCleanManager.clearAllCache(getApplicationContext());
                                deleteLogFiles();
                            }
                        }).start();
                    }
                }).show();

                break;
            case R.id.rl_account_versionUpdate:
                intent2Page(VersionContentActivity.class, false);
                break;
            case R.id.tv_exit:
                new AlertDialog.Builder(getActivity())
                        .setTitle(R.string.str_login_out)
                        .setMessage(R.string.str_submit_login_out)
                        .setNegativeButton(R.string.str_cancel, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                dialogInterface.dismiss();
                            }
                        }).setPositiveButton(R.string.str_submit, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                logout();
                            }
                        }).show();

                break;
            case R.id.rl_electronic_scale:

                intent2Page(ElectronicScaleActivity.class, false);
                break;
            case R.id.rl_upload_files:
                showLogDialog();

                break;
            case R.id.rl_picture_selector:
                intent2Page(PictureSelectorActivity.class, false);
                break;
        }
    }

    //删除文件日志
    private void deleteLogFiles() {
        String fileName = RxTimeTool.simpleDateFormat("yyyy-MM-dd",RxTimeTool.getCurTimeDate());
        String yesterday= RxTimeTool.getYestoryDate("yyyy-MM-dd");
        File files[] =  new File(filesDir).listFiles();
        if (files != null)
            for (File f : files) {
                if (f.exists()) { // 判断是否存在
                    try {
                        //不删除当天日志
                        if (!f.getName().equals(fileName)&& !f.getName().equals(yesterday)){
                            f.delete();
                        }
                    } catch (Exception e) {
                    }
                }
            }
    }

    /**
     * 容器列表弹窗
     * @param
     */
    private void showLogDialog() {

        File files[] =  new File(filesDir).listFiles();

        if (files != null){
            //倒序的数组
            Collections.reverse(Arrays.asList(files));

            TListDialog cTListDialog = (TListDialog) new TListDialog.Builder(getActivity().getSupportFragmentManager())
                    .setListLayoutRes(R.layout.dialog_recyclerview_batch_number, LinearLayoutManager.VERTICAL)
                    .setDimAmount(0.6f)     //设置弹窗背景透明度(0-1f)
                    .setCancelOutside(true)//弹窗在界面外是否可以点击取消
//                    .setScreenHeightAspect(this,0.8f)
                    .setScreenWidthAspect(getActivity(), 0.8f)
                    .setGravity(Gravity.CENTER)
                    .setOnBindViewListener(new OnBindViewListener() {
                        @Override
                        public void bindView(BindViewHolder viewHolder) {
                            ((TextView) viewHolder.getView(R.id.txt_title)).setText(R.string.msg_title_select_log);
                        }
                    })
                    .setAdapter(new TBaseAdapter<File>(R.layout.item_dialog_list_one, Arrays.asList(files)) {
                        @Override
                        protected void onBind(BindViewHolder holder, int position, File file) {
                            holder.setText(R.id.tv_dialog_list, file.getName());
                        }
                    })

                    .setOnAdapterItemClickListener(new TBaseAdapter.OnAdapterItemClickListener<File>() {
                        @Override
                        public void onItemClick(BindViewHolder holder, int position, File file, TDialog tDialog) {
                            saveToInternet(file.getName());//选中上传日志
                            tDialog.dismiss();
                        }
                    })
                    .create()
                    .show();
        }else{
            showErrorToast("日志文件不存在");
            return;
        }


    }
    // 接受蓝牙数据处理
    @SuppressLint("HandlerLeak")
    private Handler uploadHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            try {
                XLog.e(msg);
                //String data = (String) msg.obj;
                JSONObject jsonObject = (JSONObject) msg.obj;

            } catch (Exception e) {
                XLog.e(e.getMessage());
                e.printStackTrace();
            }
        }

    };
    //保存日志

    public void saveToInternet(String fileName){
        try {
            //.params("file", new File("/sdcard/a.jpg"),"caoqijia.jpg")
            //上传单个文件
            File file = new File(filesDir+fileName);
            if (!file.exists()){
                showErrorToast(getString(R.string.error_no_log));
                return;
            }
            String imei = DeviceIdUtils.getIMEI(getContext());
            SPCache sp = SPCache.getInstance(getActivity());
            String newsFileName = fileName+"-"+sp.getUserName() +"-"+ imei;
            FiledUpload filedUpload = new FiledUpload(getActivity(),"log");
            filedUpload.filedUpload(file.toString(),newsFileName);

        }catch (Exception e){
            XLog.e("上传文件失败"+e.getMessage());
        }
    }


    /**
     * 请求服务端退出登陆
     */
    public void logout() {

        XLog.d("用户主动退出登陆，token："+SPCache.getInstance(getActivity()).getToken());
        //只请求不等结果

        String service_address = CommSharedUtil.getInstance(getActivity()).getString("service_address");
        OkGo.<String>post(service_address + Urls.LOGIN_OUT)
                .execute(new MyDialogCallback(getActivity(), true, false) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        //super.onSuccess(response);
                        ActionBean bean = JsonUtil.getObject(response.body(), ActionBean.class);

                    }
                });

        getActivity().finish();
        SPCache.getInstance(getActivity()).clearCache();
        startActivity(new Intent(getActivity(), LoginActivity.class));

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        bind.unbind();
        OkGo.getInstance().cancelTag(this);
    }
}
