package com.zhilin.patrol.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.cjj.MaterialRefreshLayout;
import com.cjj.MaterialRefreshListener;
import com.zhilin.patrol.R;
import com.zhilin.patrol.bean.HomeEntity;
import com.zhilin.patrol.bean.LoginEntity;
import com.zhilin.patrol.http.HttpUrl;
import com.zhilin.patrol.tool.DialogUtil;
import com.zhilin.patrol.tool.IpUtils;
import com.zhilin.patrol.tool.JsonUtils;
import com.zhilin.patrol.tool.SPUtil;
import com.zhilin.patrol.views.AlertDialog;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.builder.PostFormBuilder;
import com.zhy.http.okhttp.callback.Callback;
import com.zhy.http.okhttp.request.RequestCall;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

/**
 * 主页面
 */
public class MainActivity extends BaseActivity {

    @BindView(R.id.tv_user)
    TextView mUserTv;//用户
    @BindView(R.id.tv_sex)
    TextView mSexTv;//性别
    @BindView(R.id.tv_logout)
    TextView mLogoutTv;//注销

    @BindView(R.id.tv_un_complete)
    TextView mUnCompleteTv;//未完成
    @BindView(R.id.tv_examine)
    TextView mExamineTv;//审核中
    @BindView(R.id.tv_complete)
    TextView mCompleteTv;//完成
    @BindView(R.id.tv_un_pass)
    TextView mUnpassTv;//不通过
    @BindView(R.id.tv_address)
    TextView mAddressTv;//地址
    @BindView(R.id.tv_map)
    TextView mMapTv;//地图
    @BindView(R.id.tv_msg_time)
    TextView mEndTimeTv;//最后时间消息
    @BindView(R.id.rl_layout_task)
    RelativeLayout mTaskLayout;//指派任务

    @BindView(R.id.swipe_refresh_layout)
    MaterialRefreshLayout mRefreshLayout;//下拉刷新

    @BindView(R.id.tv_tip)
    TextView mTipTv;//消息提示
    @BindView(R.id.tv_sample_num)
    TextView mSampleNumTv;//抽样消息提示
    @BindView(R.id.tv_rectify_num)
    TextView mRectifyNumTv;//整改不通过消息提示
    @BindView(R.id.tv_overdue_num)
    TextView mOverdueNumTv;//逾期消息提示
    @BindView(R.id.tv_myTask_num)
    TextView mMyTaskNum;

    /** 用户信息 */
    LoginEntity.InfoListBean mInfoListBean;
    private LoginEntity.InfoListBean.UserInfoBean mUserInfo;
    /** 是否是第一次加载 */
    private boolean mIsFirst;
    private HomeEntity.InfoListBean infoList;
    private HomeEntity.InfoListBean.ExtTaskBean extTasklist;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        isContainNavi(false);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        mInfoListBean = (LoginEntity.InfoListBean) getIntent().getSerializableExtra("infoList");
        mUserInfo = mInfoListBean.getUserInfo();
        init();
        showLoadingView();
        mIsFirst = true;
        request();
    }


    @Override
    public void request() {
        String ipAddress = IpUtils.getIpAddress(this);
        PostFormBuilder formBuilder = OkHttpUtils.post();
        formBuilder.url(HttpUrl.MAIN_URL);
        formBuilder.addParams("userCode", mUserInfo.getUserCode());
        formBuilder.addParams("userRole", mUserInfo.getUserRole() + "");
        formBuilder.addParams("userIP", ipAddress);
        RequestCall call = formBuilder.build();
        call.execute(new Callback<HomeEntity>() {
            @Override
            public HomeEntity parseNetworkResponse(Response response, int id) throws Exception {
                String jsonStr = response.body().string();
                return (HomeEntity) JsonUtils.parseJson2Obj(jsonStr, HomeEntity.class);
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                if (mIsFirst) {
                    showFailView();
                } else {
                    mRefreshLayout.finishRefresh();
                }
                DialogUtil.showNetFailDialog(MainActivity.this);
            }

            @Override
            public void onResponse(HomeEntity entity, int id) {
                if (mIsFirst) {
                    showContentView();
                } else {
                    mRefreshLayout.finishRefresh();
                }
                mIsFirst = false;
                if (entity == null) {
                    DialogUtil.showErrDialog(MainActivity.this, "返回信息为空");
                    return;
                }
                infoList = entity.getInfoList();
                if (!"1000".endsWith(entity.getReturnCode())) {
                    DialogUtil.showErrDialog(MainActivity.this, entity.getReturnMsg());
                    return;
                }
                mUnCompleteTv.setText(infoList.getUnfinishNum() + "");
                mCompleteTv.setText(infoList.getFinishNum() + "");
                mExamineTv.setText(infoList.getReviewNum() + "");
                mUnpassTv.setText(infoList.getUnpassNum()+"");
                final HomeEntity.InfoListBean.ExtTaskBean extTask = infoList.getExtTask();
                if (extTask != null) {
                    mTaskLayout.setVisibility(View.VISIBLE);
                    mAddressTv.setText(extTask.getAddress()+"(需巡" + extTask.getCheckNum() + "次|" + "已巡" +extTask.getPostNum() + "次)");
                    mEndTimeTv.setText(extTask.getEndTime() + " 前需要完成巡查上报");
                    mMapTv.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            MapActivity.toMap(MainActivity.this, Double.parseDouble(extTask.getLatitude()), Double.parseDouble(extTask.getLongitude()), extTask.getAddress());
                        }
                    });
                    extTasklist=infoList.getExtTask();
                    Log.i("code指派=",extTasklist.getPCdoe());
                } else {
                    mTaskLayout.setVisibility(View.GONE);
                }
                if (infoList.getHasEndingPlan() == 1) {
                    mTipTv.setVisibility(View.VISIBLE);
                    mTipTv.setText(infoList.getNoticeMsg());
                } else {
                    mTipTv.setVisibility(View.GONE);
                }
                setTipNum(mSampleNumTv, infoList.getSmartPlanCode());
                setTipNum(mRectifyNumTv, infoList.getUnReChangePlanCode());
                setTipNum(mOverdueNumTv, infoList.getExpirePlanCode());
                setTipNum(mMyTaskNum,infoList.getDefaultPlanCode());
            }
        });
    }

    private void setTipNum(TextView tv, String num) {
        if (!TextUtils.isEmpty(num)) {
//            String textTNum = num + "";
//            if (num > 99) {
//                textTNum = "99+";
//            }
//            tv.setText(textTNum);
            tv.setVisibility(View.VISIBLE);
        } else {
            tv.setVisibility(View.GONE);
        }
    }

    private void init() {
        if (mUserInfo != null) {
            mUserTv.setText(mUserInfo.getUserName());
            mSexTv.setText(mUserInfo.getUserSex());
        }
        mRefreshLayout.setLoadMore(false);
        mRefreshLayout.setMaterialRefreshListener(new MaterialRefreshListener() {
            @Override
            public void onRefresh(final MaterialRefreshLayout materialRefreshLayout) {
                //refreshing...
                request();
            }

            @Override
            public void onRefreshLoadMore(MaterialRefreshLayout materialRefreshLayout) {
                //load more refreshing...
            }
        });
    }

    @OnClick({ R.id.rl_record, R.id.rl_my_task, R.id.tv_logout,R.id.rl_rectify_task,//,R.id.rl_upload
            R.id.ll_un_complete, R.id.ll_examine, R.id.ll_complete, R.id.rl_task_upload,R.id.ll_un_pass,
            R.id.rl_sample_task, R.id.rl_overdue_task, R.id.tv_tip,R.id.rl_upload_info})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_task_upload://巡查上报
                Intent intent = new Intent(this, PatrolUploadActivity.class);
                intent.putExtra("userInfo", mUserInfo);
                intent.putExtra("isAssign", 1);
                intent.putExtra("pCode",extTasklist.getPCdoe());
                intent.putExtra("pbCode","null");
                intent.putExtra("address",extTasklist.getAddress());
                startActivity(intent);
                break;
            case R.id.ll_un_complete://未完成
                MyTaskTypeActivity.toMyTask(this, mUserInfo, 0);
                break;
            case R.id.ll_examine://审核中
                toActivityNum(PatrolRecordActivity.class, mUserInfo,1);
                break;
            case R.id.ll_complete://已完成
                toActivityNum(PatrolRecordActivity.class, mUserInfo,3);
                break;
            case R.id.ll_un_pass://不通过
                toActivityNum(PatrolRecordActivity.class, mUserInfo,2);
                break;
            case R.id.rl_record://巡查记录
                toActivityNum(PatrolRecordActivity.class, mUserInfo,123);
                break;
//            case R.id.rl_upload://巡查上报
//                toActivity(PatrolUploadActivity.class, mUserInfo,"fir","fir");
//                break;
            case R.id.rl_my_task://普通任务
                MyTaskTypeActivity.toMyTask(this, mUserInfo, 1);
                break;
            case R.id.rl_sample_task://抽样任务
                toTaskTypeActivity(infoList.getSmartPlanCode(), 4);
                break;
            case R.id.rl_overdue_task://逾期任务
                toTaskTypeActivity(infoList.getExpirePlanCode(), 5);
                break;
            case R.id.tv_tip://首页提示
                toTaskTypeActivity(infoList.getEndingPlanCode(), 6);
                break;
            case R.id.rl_rectify_task://整改不通过任务
                toTaskTypeActivity(infoList.getUnReChangePlanCode(), 7);
                break;
            case R.id.rl_upload_info:
                toActivityNum(InfoUploadActivity.class,mUserInfo,111);
                break;
            case R.id.tv_logout://注销
                new AlertDialog(this).builder()
                        .setTitle(getString(R.string.tv_tishi))
                        .setMsg("确定要注销?")
                        .setPositiveButton("注销", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                SPUtil.savaToShared(MainActivity.this, SPUtil.SP_COMMON_CONFIG, "infoList", "");
                                finish();
                                Intent intent=new Intent(MainActivity.this,LoginActivity.class);
                                startActivity(intent);
                            }
                        }).setNegativeButton("取消", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                    }
                }).show();
                break;
            default:
                break;
        }
    }

    private void toTaskTypeActivity(String paramPlanCode, int taskType) {
        String planCode = "";
        if (infoList != null && !TextUtils.isEmpty(paramPlanCode)) {
            planCode = paramPlanCode;
        }
        TaskTypeActivity.toTypeTask(this, mUserInfo, planCode, taskType);
    }

}
