package com.tofly.ghrq_route.common.ui.activity;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;

import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;

import com.esri.arcgisruntime.geometry.Point;
import com.gaoyuan.weixinrecord.utils.PermissionHelper;
import com.mgq.base.utils.progressdialog.ProgressManager;
import com.tofly.ghrq_route.R;
import com.tofly.ghrq_route.base.BaseApp;
import com.tofly.ghrq_route.base.ui.BaseFileActivity;
import com.tofly.ghrq_route.base.URLResponseCode;
import com.tofly.ghrq_route.common.ui.view.CheckBoxListView;
import com.tofly.ghrq_route.common.ui.view.MyAudioRecordButton;
import com.tofly.ghrq_route.common.util.file.FileUtil;
import com.tofly.ghrq_route.module.plan.domain.OfflinePathBean;
import com.tofly.ghrq_route.module.plan.domain.PlanBean;
import com.tofly.ghrq_route.module.planPointRepair.PointRepairTool;
import com.tofly.ghrq_route.module.planPointRepair.controller.PointRepairCallBack;
import com.tofly.ghrq_route.module.planPointRepair.domain.AdjustRepairContent;
import com.tofly.ghrq_route.module.planPointRepair.domain.MaintainAdjustParam;
import com.tofly.ghrq_route.module.planPointRepair.domain.MaintainSelectParam;
import com.tofly.ghrq_route.module.planPointRepair.domain.PlanPointRepair;
import com.tofly.ghrq_route.module.planPointRepair.domain.PointRepairEvent;
import com.tofly.ghrq_route.module.planPointRepair.domain.RepairSysDeviceSetting;
import com.tofly.ghrq_route.module.trouble.domain.TroubleBean;
import com.tofly.ghrq_route.module.trouble.domain.TroublePictureBean;
import com.tofly.ghrq_route.module.user.domain.UserBean;
import com.tofly.ghrq_route.common.util.Location.LocationUtil;
import com.tofly.ghrq_route.common.util.Location.LocationUtil_xu;
import com.tofly.ghrq_route.common.util.date.DateUtils;
import com.tofly.ghrq_route.common.util.image.PhotoHelper;

import org.greenrobot.eventbus.EventBus;

import java.lang.ref.WeakReference;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.hzw.graffiti.WaterMarkParams;

/**
 * Created by Amu on 2017/7/25.
 */

public class UiAdjustDeviceRepair extends BaseFileActivity {
    @BindView(R.id.layout_option)
    LinearLayout layoutOptions;
    @BindView(R.id.edit_repair_region)
    EditText editRepairRegion;
    @BindView(R.id.btn_add_photo)
    Button btnAddPhoto;
    @BindView(R.id.photo_gallery)
    LinearLayout photoGallery;

    private int mPhotoType = 0;

    private PointRepairTool repairTool;

    private OfflinePathBean mPlanPoint;

    private PlanPointRepair mPointRepair;

    private PlanBean mPlan;

    private MenuItem menuCommit;

    private MenuItem menuSave;

    private boolean mbUseServerParams = true;

    private boolean mbIsEditable = false;

    private int mPhotoNeed = RepairSysDeviceSetting.REPAIR_PARA_OPTIONAL;

    private Map<MaintainAdjustParam, List<MaintainAdjustParam>> mRepairParams;

    private List<String> mSelectedIds = new ArrayList<>();

    private List<AdjustRepairContent> mSelectContents;

    private boolean isUpload = false;

    private boolean isUpdate = false;

    private boolean isLocal = false;

    private final String DEFAULT_TIME_FORMAT = "yyyy-MM-dd HH:mm";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ui_adjust_device_repair_update);
        ButterKnife.bind(this);

        initView();
        initData();
        initListener();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_danger_report_next, menu);
        menuCommit = menu.findItem(R.id.action_upload);
        if (isUpload) {
            menuCommit.setTitle(R.string.upload);
        }else {
            menuCommit.setTitle(R.string.update);
            //menuCommit.setEnabled(false);
        }
        menuSave = menu.findItem(R.id.action_save);
        menuSave.setVisible(false);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            /*case R.id.action_save:{
                if (checkHasData()){
                    showSaveAlertDialog();
                }
            }
            break;*/
            case R.id.action_upload:{
                if (checkValid()) {
                    showUploadAlertDialog();
                }
            }
            break;
        }
        return super.onOptionsItemSelected(item);
    }

    public void initView() {
        super.initView();
    }

    public void initData() {
        super.initData();
        repairTool = PointRepairTool.getInstance();

        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        if (bundle != null) {
            mPlanPoint = (OfflinePathBean) bundle.getSerializable(OfflinePathBean.PLAN_POINT_BEAN_KEY);
            mPlan = (PlanBean) bundle.getSerializable(PlanBean.PLAN_BEAN_KEY);
            LocationUtil_xu.CoordinateClass coordinate = (LocationUtil_xu.CoordinateClass) bundle.getSerializable(LocationUtil.CURRENT_LOCATION_KEY);
            if (coordinate != null) {
                mLocation = new Point(coordinate.Longtitude, coordinate.Latitude);
            }

            boolean isNewRecord = bundle.getBoolean(PlanPointRepair.POINT_REPAIR_IS_NEW_KEY, false);
            if (isNewRecord) {
                mPointRepair = new PlanPointRepair(mPlanPoint, mLocation);
                isUpdate = false;
            } else {
                mPointRepair = (PlanPointRepair) bundle.getSerializable(PlanPointRepair.POINT_REPAIR_BEAN_KEY);
                isLocal = mPointRepair.getState() == TroubleBean.SAVED_STATE ||
                        mPointRepair.getState() == TroubleBean.SERVER_UPDATE_UNUPLOAD_STATE;
                repairTool.setRepairRecordUpdating(mPointRepair, true);

                isUpdate = true;
                bRemoveCacheFile = false;

                editRepairRegion.setText(mPointRepair.getCheckRegion());

 /*               List<String> selectContents = mPointRepair.getContent();
                if (selectContents != null) {
                    mSelectedIds = selectContents;
                }*/
            }
            isUpload = isNewRecord || isLocal;

            getRepairSysSettingList();
            if (isUpdate) {
                getPhotos();
            }
        }
    }

    public void initListener() {
        super.initListener();
        editRepairRegion.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                setUpdateEnabled();
            }
        });

        setPhotoListener((picture, photoView) -> setUpdateEnabled());

        setOnNavigationClickListener(v -> showExitAlertDialog());
    }

    private void onGetParamsUpdateUI(){
        if (mRepairParams != null && mRepairParams.size() > 0){
            mbUseServerParams = true;
            onParamsUpdateUi();
        }else {
            mbUseServerParams = false;
        }
    }

    private void onParamsUpdateUi(){
        if (mRepairParams != null) {
            AdjustParamUpdateUITask updateUITask = new AdjustParamUpdateUITask(this);
            updateUITask.execute();
        }
    }

    private List<String> getContentSelectIds(String parentId) {
        List<String> selectIds = new ArrayList<>();
        List<AdjustRepairContent> contents = mPointRepair.getContents();
        if (contents != null) {
            for (AdjustRepairContent repairContent : contents) {
                if (repairContent.getParentId().equals(parentId)) {
                    List<String> content = repairContent.getMenuIds();
                    if (content != null) {
                        selectIds = content;
                    }
                    break;
                }
            }
        }
        return  selectIds;
    }

    private String getContentNote(String parentId) {
        String note = null;
        List<AdjustRepairContent> contents = mPointRepair.getContents();
        if (contents != null) {
            for (AdjustRepairContent content : contents) {
                if (content.getParentId().equals(parentId)) {
                    note = content.getNote();
                    break;
                }
            }
        }
        return note;
    }

    private void setUpdateEnabled() {
        if (!isUpload) {
            if (menuCommit != null)
                menuCommit.setEnabled(true);
        }
    }

    @Override
    public void onBackPressed() {
        showExitAlertDialog();
    }

    public boolean checkHasData(){
        return (mPicturesUpload != null && mPicturesUpload.size() > 0);
    }

/*    private void showSaveAlertDialog() {
        String title = "保存数据";
        String content = "是否保存数据?";
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(title);
        builder.setMessage(content);
        builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                saveRouteRecordInfo();
            }
        });
        builder.setNegativeButton(android.R.string.cancel, null);
        builder.show();
    }

    private void saveRouteRecordInfo(){
        if (mPointRepair != null && mPlanPoint != null){
            repairTool.savePlanPointRepairRecord(mPointRepair, mPlanPoint, mPicturesUpload, false);
            onSaveFinished();
        }
    }*/

    private boolean checkValid() {
        String region = editRepairRegion.getText().toString();
        if (region.isEmpty()) {
            editRepairRegion.requestFocus();
            toast("请输入用气片区!");
            return false;
        }

        if (mSelectContents == null || mSelectContents.isEmpty()) {
            toast("请检查每项内容，并在对应的检查结果上打钩");
            return false;
        }

        for (AdjustRepairContent selectContent : mSelectContents) {
            List<String> menuIds = selectContent.getMenuIds();
            if (menuIds == null || menuIds.isEmpty()) {
                toast(String.format("请检查 【%s】，并在对应的检查结果上打钩", selectContent.getParentName()));
                return false;
            }
        }

        if (mPicturesUpload == null || mPicturesUpload.size() == 0){
            toast("请添加图片!");
            return false;
        }

        return true;
    }

    private void showUploadAlertDialog() {
        String title = "上传数据";
        String content = "是否上传数据?";
        showAlertWithConfirmCancelButton(title, content, true, (dialog, which) -> commitPlanPointRepair());
    }

    private void showExitAlertDialog(){
        boolean hasInput = checkHasData();
        if (hasInput){
            String title = "退出编辑";
            String content = "退出编辑，当前输入将会丢失。是否继续?";
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle(title);
            builder.setMessage(content);
            builder.setPositiveButton(android.R.string.ok, (dialog, which) -> {
                removeCacheFile();
                finish();
            });
            builder.setNegativeButton(android.R.string.cancel, null);
            builder.show();
        }else {
            removeCacheFile();
            finish();
        }
    }

    private void getPhotos() {
        if (isLocal) {
            getSavedPhotos();
        }else {
            getUploadPhotos();
        }
    }

    private void getUploadPhotos() {
        String record_id = mPointRepair.getTemp_id();
        List<TroublePictureBean> pictures = repairTool.getLocalRepairPhotos(record_id);
        mPicturesUpload  = pictures;
        for (TroublePictureBean picture : pictures){
            if (picture != null){
                getSchemeFiles(picture, photoGallery);
            }
        }
    }

    private void getSavedPhotos(){
        String record_id = mPointRepair.getTemp_id();
        List<TroublePictureBean> pictures = repairTool.getLocalRepairPhotos(record_id);
        mPicturesUpload  = pictures;
        for (TroublePictureBean picture : pictures){
            if (picture != null){
                View view = getPhotoViewFromPath(picture);
                if (view != null) {
                    photoGallery.addView(view);
                }
            }
        }
    }

    private void getRepairSysSettingList(){
        String strUploading = getResources().getString(R.string.updating_data);
        ProgressManager.getInstance().showProgress(this, null, strUploading, false);
        repairTool.getAdjustDeviceSettingList(this, new PointRepairCallBack(){
            @Override
            public void onGetAdjustDeviceSettingList(boolean isSuccess, int errorCode, String errMsg, List<MaintainAdjustParam> paramList, int total) {
                super.onGetAdjustDeviceSettingList(isSuccess, errorCode, errMsg, paramList, total);
                ProgressManager.getInstance().cancelProgress();
                if (isSuccess && paramList != null && paramList.size() > 0) {
                    mRepairParams = repairTool.getLocalPairedAdjustDeviceSettings();
                    onGetParamsUpdateUI();
                }else {
                    showAlertWithConfirmButton(getString(R.string.repair_adjust_get_params_failed), errMsg, false,
                            (dialog, which) -> UiAdjustDeviceRepair.this.finish());
                }
            }
        });
    }

    private void collectData() {
        /*操作人*/
        UserBean userBean = BaseApp.getInstance().getLoginUser();
        mPointRepair.setDeviceUser(userBean.getUserid());
        /*维修内容*/
        mPointRepair.setContents(mSelectContents);
        /*用气片区*/
        String region = editRepairRegion.getText().toString();
        mPointRepair.setCheckRegion(region);

        for (TroublePictureBean pictureBean : mPicturesUpload) {
            if (pictureBean != null) {
                boolean isDeleted = pictureBean.getStatus() == TroublePictureBean.PHOTO_DELETED_STATE;
                if (isDeleted) {
                    repairTool.deleteRepairPhoto(pictureBean);
                }
            }
        }
    }

    private void commitPlanPointRepair() {
        if (mPointRepair != null) {
            collectData();
            String strUploading = getResources().getString(R.string.uploading_data);
            ProgressManager.getInstance().showProgress(this, null, strUploading, false);

            repairTool.uploadAdjustDeviceRepairRecord(this, mPointRepair, mPicturesUpload, new PointRepairCallBack(){
                @Override
                public void onAddPointChildRepair(boolean isSuccess, int errorCode, String errMsg) {
                    super.onAddPointChildRepair(isSuccess, errorCode, errMsg);
                    ProgressManager.getInstance().cancelProgress();
                    onUploadFinish(isSuccess, errorCode);
                }
            });
        }
    }

/*    private void onSaveFinished(){
        setMenuCommitEnabled(false);
        menuSave.setEnabled(false);
        mbNeedRemoveCache = false;
        String msg = PointRepairEvent.REPAIR_ROUTE_SAVED;
        EventBus.getDefault().post(new PointRepairEvent(msg, mPlanPoint));
        showSaveFinishedDialog();
    }

    private void showSaveFinishedDialog(){
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(R.string.dangerreport_next_save_ok);
        builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                UiAdjustDeviceRepair.this.finish();
            }
        });
        builder.show();
    }*/

    private void onUploadFinish(boolean isSuccess, int error_code){
        menuCommit.setEnabled(false);
        menuSave.setEnabled(false);
        String msg = isSuccess ? PointRepairEvent.REPAIR_ROUTE_UPLOADED : PointRepairEvent.REPAIR_ROUTE_SAVED;
        EventBus.getDefault().post(new PointRepairEvent(msg, mPlanPoint));
        showUploadFinishedDialog(isSuccess, error_code);
    }

    private void showUploadFinishedDialog(boolean isSuccess, int error_code){
        String title = getTitle().toString();
        String content = isSuccess ?
                getString(R.string.upload_ok) : getString(R.string.upload_fail_saved);
        if (error_code == URLResponseCode.ErrorCode.ALREADY_EXISTS) {
            content = getString(R.string.repair_finished_no_commit);
        }
        showAlertWithConfirmButton(title, content, false,
                (dialog, which) -> this.finish());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private static class AdjustParamUpdateUITask extends AsyncTask {
        private final WeakReference<UiAdjustDeviceRepair> activityReference;
        private final Map<MaintainAdjustParam, CheckBoxListView> mChildViews;

        AdjustParamUpdateUITask(UiAdjustDeviceRepair context){
            activityReference  = new WeakReference<>(context);
            mChildViews = new HashMap<>();
        }

        @Override
        protected void onPreExecute() {
            UiAdjustDeviceRepair context = activityReference.get();
            if (context == null || context.isFinishing())
                return ;

            context.layoutOptions.removeAllViews();

            String strUploading = context.getString(R.string.updating_data);
            ProgressManager.getInstance().showProgress(context, null, strUploading, false);
        }

        @Override
        protected Object doInBackground(Object[] objects) {
            UiAdjustDeviceRepair context = activityReference.get();
            if (context == null || context.isFinishing())
                return -1;

            context.mSelectContents = new ArrayList<>();
            for (Map.Entry<MaintainAdjustParam, List<MaintainAdjustParam>> entry : context.mRepairParams.entrySet()) {
                MaintainAdjustParam parentParam = entry.getKey();
                List<MaintainAdjustParam> childParams = entry.getValue();
                String parent_id = parentParam.getId();
                String parent_name = parentParam.getName();
                String defaultValue = AdjustRepairContent.defaultMap.get(parent_name);
                List<String> selectIds = context.getContentSelectIds(parent_id);
                List<MaintainSelectParam> params = new ArrayList<>();
                boolean hasNone = false;
                MaintainSelectParam paramNone = null;
                for (MaintainAdjustParam param : childParams){
                    MaintainSelectParam selectParam = MaintainSelectParam.getSelectParam(param);
                    String id = selectParam.getId();
                    String name = selectParam.getName();
                    if (context.isUpdate) {
                        if (selectIds.contains(id)) {
                            selectParam.setSelected(true);
                        }
                    }else {
                        if (defaultValue != null && !defaultValue.isEmpty() && defaultValue.equals(name)) {
                            selectParam.setSelected(true);
                            selectIds.add(id);
                        }
                    }
                    if (param.getName().equals(context.getString(R.string.none))) {
                        hasNone = true;
                        paramNone = selectParam;
                    }
                    params.add(selectParam);
                }
                if (params.size() > 0) {
                    AdjustRepairContent repairContent = new AdjustRepairContent(parent_id, parent_name);
                    repairContent.setHasNone(hasNone);
                    repairContent.setNoneParam(paramNone);
                    if (context.isUpdate) {
                        String note = context.getContentNote(parent_id);
                        if (note != null) {
                            repairContent.setNote(note);
                        }
                    }
                    if (paramNone != null && selectIds.contains(paramNone.getId())) {
                        repairContent.setExist(0);
                    }else {
                        repairContent.setExist(1);
                    }
                    CheckBoxListView optionsView = new CheckBoxListView(context, params, repairContent);
                    optionsView.setCOLUMN(3);
                    context.mSelectContents.add(repairContent);
                    mChildViews.put(parentParam, optionsView);
                }
            }
            return 0;
        }

        @Override
        protected void onPostExecute(Object o) {
            UiAdjustDeviceRepair context = activityReference.get();
            if (context == null || context.isFinishing())
                return ;

            ProgressManager.getInstance().cancelProgress();
            if (mChildViews.size() > 0) {
                for (Map.Entry<MaintainAdjustParam, CheckBoxListView> entry : mChildViews.entrySet()) {
                    MaintainAdjustParam parentParam = entry.getKey();
                    CheckBoxListView optionsView = entry.getValue();
                    View rootView = optionsView.getViewWithParentTitle(parentParam);
                    if (rootView != null) {
                        context.layoutOptions.addView(rootView);
                    }
                    //optionsView.setOnItemSelectListener((id, selected) -> setUpdateEnabled());
                }
            }
        }
    }

    @Override
    public Button getAddPhotoBtn() {
        return btnAddPhoto;
    }

    @Override
    public LinearLayout getPhotoGallery() {
        return photoGallery;
    }

    @Override
    public MyAudioRecordButton getAudioRecordBtn() {
        return null;
    }

    @Override
    protected LocationUtil_xu.CoordinateClass getLocation() {
        return super.getLocation();
    }
}
