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

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

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

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.AppCompatSpinner;
import androidx.appcompat.widget.Toolbar;

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.adapter.SingleUserListAdapter;
import com.tofly.ghrq_route.common.ui.view.CheckBoxListView;
import com.tofly.ghrq_route.common.ui.view.MyAudioRecordButton;
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.MaintainCommonParam;
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.UserInfoTool;
import com.tofly.ghrq_route.module.user.controller.UserCallBack;
import com.tofly.ghrq_route.module.user.domain.DepartmentBean;
import com.tofly.ghrq_route.module.user.domain.DepartmentUserBean;
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.file.FileUtil;
import com.tofly.ghrq_route.common.util.image.PhotoHelper;

import org.greenrobot.eventbus.EventBus;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

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

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

public class UiCommonDeviceRepair extends BaseFileActivity {
    @BindView(R.id.main_toolbar)
    Toolbar toolbar;
    @BindView(R.id.layout_option)
    LinearLayout layoutOptions;
    @BindView(R.id.spinner_repair_depart)
    AppCompatSpinner spinnerDepart;
    @BindView(R.id.spinner_repair_user)
    AppCompatSpinner spinnerUser;
    @BindView(R.id.edit_report_note)
    EditText editReportNote;
    @BindView(R.id.btn_add_photo)
    Button btnAddPhoto;
    @BindView(R.id.layout_add_photo)
    LinearLayout layoutAddPhoto;
    @BindView(R.id.photo_gallery)
    LinearLayout photoGallery;

    private PointRepairTool repairTool;

    private PlanPointRepair mPointRepair;

    private OfflinePathBean mPlanPoint;

    private PlanBean mPlan;

    private boolean mbIsEditable = false;

    private boolean mbUseServerParams = true;

    private int mPhotoNeed = RepairSysDeviceSetting.REPAIR_PARA_OPTIONAL;

    private MenuItem menuCommit;

    private MenuItem menuSave;

    private List<MaintainCommonParam> mRepairParams;

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

    private List<DepartmentBean> mDepartmentList;

    private List<DepartmentUserBean> mUserList;

    private SingleUserListAdapter userListAdapter;

    private int indexDepartment = -1;

    private int indexUser = -1;

    private boolean isEditable = false;

    private boolean isRemoveable = false;

    private boolean isUpload = false;

    private boolean isUpdate = false;

    private boolean isSetUser = false;

    private boolean isLocal = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ui_common_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) {
        if (item.getItemId() == R.id.action_upload) {
            if (checkValid()) {
                showUploadAlertDialog();
            }
        }
        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);
            LocationUtil_xu.CoordinateClass coordinate =
                    (LocationUtil_xu.CoordinateClass) bundle.getSerializable(LocationUtil.CURRENT_LOCATION_KEY);
            if (coordinate != null)
                mLocation = new Point(coordinate.Longtitude, coordinate.Latitude);
            mPlan = (PlanBean) bundle.getSerializable(PlanBean.PLAN_BEAN_KEY);
            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;

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

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

    public void initListener() {
        super.initListener();
        editReportNote.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(){
        boolean hasPhoto = true;
        List<MaintainSelectParam> params = new ArrayList<>();
        for (MaintainCommonParam param : mRepairParams){
            MaintainSelectParam selectParam = MaintainSelectParam.getSelectParam(param);
            if (isUpdate) {
                String id = selectParam.getId();
                List<String> selectIds = mPointRepair.getContent();
                if (selectIds.contains(id)) {
                    selectParam.setSelected(true);
                }
            }
            params.add(selectParam);
        }
        if (params.size() > 0) {
            CheckBoxListView optionsView = new CheckBoxListView(this, params);
            View rootView = optionsView.getViewWithNoTitle();
            if (rootView != null) {
                layoutOptions.removeAllViews();
                layoutOptions.addView(rootView);
            }
            optionsView.setOnItemSelectListener((id, selected) -> setSelectedItem(id, selected));
        }
        if (!hasPhoto){
            mPhotoNeed = RepairSysDeviceSetting.REPAIR_PARA_NONEED;
            layoutAddPhoto.setVisibility(View.GONE);
        }
    }

    private void setSelectedItem(String id, boolean selected) {
        if (id != null && !id.isEmpty()) {
            if (selected) {
                if (!mSelectedIds.contains(id)) {
                    mSelectedIds.add(id);
                }
            }else {
                if (mSelectedIds.contains(id)) {
                    mSelectedIds.remove(id);
                }
            }
            setUpdateEnabled();
        }
    }

    private boolean isSelectUserChanged() {
        boolean isChanged = false;
        if (isUpdate) {
            String deviceUser = mPointRepair.getDeviceUser();
            DepartmentUserBean userBean = mUserList.get(indexUser);
            isChanged = !userBean.getId().equals(deviceUser);
        }
        return isChanged;
    }

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

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

    private boolean checkValid() {
        if (indexUser == -1 || mUserList.isEmpty()) {
            toast("请选择操作人员!");
            return false;
        }

        String notes = editReportNote.getText().toString();
        if (notes.isEmpty()) {
            editReportNote.requestFocus();
            toast("请输入检修备注!");
            return false;
        }

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

        return true;
    }

    private void collectData() {
        /*备注*/
        String notes = editReportNote.getText().toString();
        mPointRepair.setNotes(notes);
        /*操作部门*/
        DepartmentBean departmentBean = mDepartmentList.get(indexDepartment);
        mPointRepair.setDeviceUserDeptId(departmentBean.getId());
        /*操作人*/
        DepartmentUserBean userBean = mUserList.get(indexUser);
        mPointRepair.setDeviceUser(userBean.getId());
        /*维修内容*/
        mPointRepair.setContent(mSelectedIds);
        /*图片文件*/
        for (TroublePictureBean pictureBean : mPicturesUpload) {
            if (pictureBean != null) {
                boolean isDeleted = pictureBean.getStatus() == TroublePictureBean.PHOTO_DELETED_STATE;
                if (isDeleted) {
                    repairTool.deleteRepairPhoto(pictureBean);
                }
            }
        }
    }

    public boolean checkHasData(){
        String notes = editReportNote.getText().toString();
        if (!notes.isEmpty()) {
            return true;
        }

        return super.checkHasData();
    }

/*    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, true);
            onSaveFinished();
        }
    }*/

    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(){
        List<MaintainCommonParam> paramList = repairTool.getLocalCommonDeviceSettings();
        if (paramList == null || paramList.isEmpty()) {
            repairTool.getCommonDeviceSettingList(this, new PointRepairCallBack(){
                @Override
                public void onGetCommonDeviceSettingList(boolean isSuccess, int errorCode, String errMsg, List<MaintainCommonParam> paramList, int total) {
                    super.onGetCommonDeviceSettingList(isSuccess, errorCode, errMsg, paramList, total);
                    if (isSuccess && paramList != null && paramList.size() > 0) {
                        mRepairParams = paramList;
                        onGetParamsUpdateUI();
                    }else {
                        showAlertWithConfirmButton(getString(R.string.repair_common_get_params_failed), errMsg, false,
                                (dialog, which) -> UiCommonDeviceRepair.this.finish());
                    }
                }
            });
        }else {
            mRepairParams = paramList;
            onGetParamsUpdateUI();
        }
    }

    private void getDepartments() {
        UserInfoTool userInfoTool = UserInfoTool.getInstance();
        userInfoTool.getDepartments(this, false, new UserCallBack(){
            @Override
            public void onGetDepartmentList(boolean isSuccess, int errorCode, String errMsg, List<DepartmentBean> departmentList) {
                super.onGetDepartmentList(isSuccess, errorCode, errMsg, departmentList);
                if (isSuccess) {
                    mDepartmentList = departmentList;
                    setDepartmentAdater();
                }
            }
        });
    }

    private void setDepartmentAdater(){
        List<String> departNameList = new ArrayList<>();
        for (DepartmentBean departmentBean : mDepartmentList) {
            departNameList.add(departmentBean.getName());
        }
        ArrayAdapter<String> adapterDevType = new ArrayAdapter<String>(this,
                R.layout.my_simple_spinner_item, departNameList){
        };
        adapterDevType.setDropDownViewResource(R.layout.danger_report_spinner_item);
        //加载适配器
        spinnerDepart.setAdapter(adapterDevType);

        /*默认选择当前部门*/
        String departId = null;
        if (isUpdate) {
            departId = mPointRepair.getDeviceUserDeptId();
        }else {
            UserBean loginUser = BaseApp.getInstance().getLoginUser();
            if (loginUser != null) {
                departId = loginUser.getDepartmentId();
            }
        }
        if (departId != null && !departId.isEmpty()) {
            for (int i = 0; i < mDepartmentList.size(); i++) {
                DepartmentBean departmentBean = mDepartmentList.get(i);
                if (departmentBean.getId().equals(departId)) {
                    indexDepartment = i;
                    break;
                }
            }
            if (indexDepartment >= 0 && indexDepartment < adapterDevType.getCount()) {
                spinnerDepart.setSelection(indexDepartment);
            }
        }
    }

    private void getDepartmentUsers(String departId) {
        UserInfoTool userInfoTool = UserInfoTool.getInstance();
        userInfoTool.getDepartmentUsers(this, departId, new UserCallBack(){
            @Override
            public void onGetDepartmentUserList(boolean isSuccess, int errorCode, String errMsg,
                                                List<DepartmentUserBean> userList) {
                super.onGetDepartmentUserList(isSuccess, errorCode, errMsg, userList);
                if (isSuccess) {
                    mUserList = userList;
                    setUserAdapter();
                }
            }
        });
    }

    private void setUserAdapter(){
        //适配器
        userListAdapter = new SingleUserListAdapter(this, mUserList);
        spinnerUser.setAdapter(userListAdapter);

        if (isUpdate && !isSetUser) {
            isSetUser = true;
            String userId = mPointRepair.getDeviceUser();
            for (int i = 0; i < userListAdapter.getCount(); i++) {
                DepartmentUserBean userBean = userListAdapter.getItem(i);
                if (userBean.getId().equals(userId)) {
                    indexUser = i;
                    break;
                }
            }
            if (indexUser >= 0 && indexUser < userListAdapter.getCount()) {
                spinnerUser.setSelection(indexUser);
            }
        }
    }

    @OnItemSelected({R.id.spinner_repair_depart, R.id.spinner_repair_user})
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id){
        switch (parent.getId()){
            case R.id.spinner_repair_depart:
                indexDepartment = position;
                indexUser = -1;
                if (mDepartmentList != null) {
                    DepartmentBean departmentBean = mDepartmentList.get(position);
                    getDepartmentUsers(departmentBean.getId());
                }
                break;
            case R.id.spinner_repair_user:
                indexUser = position;
                userListAdapter.setSelection(position);
                if (isSelectUserChanged()) {
                    setUpdateEnabled();
                }
                break;
        }
    }

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

            repairTool.uploadCommonDeviceRepairRecord(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(){
        menuCommit.setEnabled(false);
        menuSave.setEnabled(false);
        mbNeedRemoveCache = false;
        EventBus.getDefault().post(new PointRepairEvent(PointRepairEvent.REPAIR_ROUTE_SAVED, 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) {
                UiPlanPointRepairFamen.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
    public Button getAddPhotoBtn() {
        return btnAddPhoto;
    }

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

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

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (isUpdate) {
            repairTool.setRepairRecordUpdating(mPointRepair, false);
        }
    }
}
