package com.zxhl.main.page.activity

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.drawable.Drawable
import android.os.Build
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.View
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.load.resource.bitmap.CircleCrop
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.SimpleTarget
import com.bumptech.glide.request.transition.Transition
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.zxhl.cms.AppContext
import com.zxhl.cms.common.Const
import com.zxhl.cms.common.Constant
import com.zxhl.cms.common.base.BaseActivity
import com.zxhl.cms.router.RounterApi
import com.zxhl.cms.router.RounterBus
import com.zxhl.cms.runtimepermission.NicePermission
import com.zxhl.cms.runtimepermission.NicePermissionListener
import com.zxhl.cms.utils.ImageUtils
import com.zxhl.cms.utils.JumpUtils
import com.zxhl.cms.utils.Utils
import com.zxhl.cms.widget.ChatDialogUtils
import com.zxhl.cms.widget.LoadingDialog
import com.zxhl.main.R
import com.zxhl.main.page.`interface`.ChooseDateCallBack
import com.zxhl.main.page.contract.SettingInfoContract
import com.zxhl.main.page.presenter.SettingInfoPresenter
import com.zxhl.main.page.view.DialogUtils
import kotlinx.android.synthetic.main.activity_layout_setting_info.*
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.io.File

class SettingInfoActivity : BaseActivity(), ChooseDateCallBack, SettingInfoContract.View {
    private var mLoading: LoadingDialog? = null
    private var mPresenter: SettingInfoPresenter? = null
    var gender: String = ""
    var selectList:List<LocalMedia>?=ArrayList()
    companion object {
        val PERMISSIONS = arrayOf(
            Constant.Permission.PERMISSION_READ_STORAGE,
            Constant.Permission.PERMISSION_STORAGE, Constant.Permission.PERMISSION_CAMERA
        )
    }

    override fun onClick(v: View?) {

    }

    override fun before() {
        super.before()
        setStatusBarBackground(AppContext.get().resources.getColor(R.color.transparent))
    }

    override fun layoutID(): Int {
        return R.layout.activity_layout_setting_info
    }

    //检查用的权限
    fun checkPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//            //获取权限（如果没有开启权限，会弹出对话框，询问是否开启权限）
            NicePermission(this, object : NicePermissionListener {
                override fun onGranted() {
                    showDialog()
                }

                override fun onRefused() {
                    ChatDialogUtils.showPermissionDialog(mActivity as Activity, "请开启相机和存储权限")
                }
            }).requestPermission(
                *arrayOf(
                    Manifest.permission.CAMERA,
                    Manifest.permission.READ_EXTERNAL_STORAGE
                )
            )
        }


    }

    fun showDialog() {
        PictureSelector.create(this)
            .openGallery(PictureMimeType.ofImage())
            .imageSpanCount(4)// 每行显示个数 int
            .maxSelectNum(1)
            .selectionMode(PictureConfig.SINGLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
            .isSingleDirectReturn(true)//PictureConfig.SINGLE模式下是否直接返回
            .previewImage(true)// 是否可预览图片 true or false
            .isCamera(true)// 是否显示拍照按钮 true or false
            .imageFormat(PictureMimeType.JPEG)// 拍照保存图片格式后缀,默认jpeg
            .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
            .setOutputCameraPath(Const.getImgPath())// 自定义拍照保存路径,可不填
            .enableCrop(true)// 是否裁剪 true or false
            .compress(true)// 是否压缩 true or false
            .compressSavePath(Const.getImgPath())//压缩图片保存地址
            .circleDimmedLayer(true)// 是否圆形裁剪 true or false
            .showCropFrame(false)// 是否显示裁剪矩形边框 圆形裁剪时建议设为 false   true or false
            .showCropGrid(false)// 是否显示裁剪矩形网格 圆形裁剪时建议设为 false    true or false
            .rotateEnabled(false) // 裁剪是否可旋转图片 true or false
            .freeStyleCropEnabled(false)// 裁剪框是否可拖拽 true or false
            .showCropGrid(false)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false    true or false
            .forResult(PictureConfig.CHOOSE_REQUEST)//结果回调onActivityResult code

//        DialogUtils.showPictureOrPhoto(this@SettingInfoActivity, View.OnClickListener {
//            //拍照
//        }, View.OnClickListener {
//            //相册
//
//        })
    }


    override fun init() {
        mLoading = LoadingDialog.getLoadingDialog(
            this,
            getString(com.zxhl.cms.R.string.wait_ing),
            false,
            false
        )
        mPresenter = SettingInfoPresenter(this)
        id_img_photo?.setOnClickListener {
            checkPermission()
        }
        id_edit_nickname.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                wiriteFinish()
            }

            override fun afterTextChanged(p0: Editable?) {
                wiriteFinish()
            }

        })
        id_ll_nan?.setOnClickListener {
            gender = "1"
            id_ll_nan?.setBackgroundResource(R.drawable.shape_83baff_r20)
            id_tv_boy?.setTextColor(getResources().getColor(R.color.white))
            id_tv_girl?.setTextColor(getResources().getColor(R.color.color_333333))
            id_ll_nv?.setBackgroundResource(R.drawable.shape_f4f4f4_r20)
            id_img_nan?.setImageResource(R.drawable.icon_nan_click)
            id_img_nv?.setImageResource(R.drawable.icon_nv_default)
            wiriteFinish()
        }
        id_ll_nv?.setOnClickListener {
            gender = "2"
            id_ll_nan?.setBackgroundResource(R.drawable.shape_f4f4f4_r20)
            id_tv_boy?.setTextColor(getResources().getColor(R.color.color_333333))
            id_tv_girl?.setTextColor(getResources().getColor(R.color.white))
            id_ll_nv?.setBackgroundResource(R.drawable.shape_ffaeae_r20)
            id_img_nan?.setImageResource(R.drawable.icon_nan_default)
            id_img_nv?.setImageResource(R.drawable.icon_nv_click)
            wiriteFinish()
        }
        id_rl_birth?.setOnClickListener {
            DialogUtils.showchooseDate(this, this)
        }
        id_tv_regeist?.setOnClickListener {
            if (TextUtils.isEmpty(id_edit_nickname.text.toString())) {
                showToast("请填写昵称")
                return@setOnClickListener
            }
            if (TextUtils.isEmpty(gender)) {
                showToast("请选择性别")
                return@setOnClickListener
            }

            if (TextUtils.isEmpty(id_tv_birth.text.toString())) {
                showToast("请选择生日")
                return@setOnClickListener
            }
            mLoading?.setLoading("请稍后")
            mLoading?.show()
            if(!selectList.isNullOrEmpty()){
                val f = File(selectList!![0].compressPath)
                val requestFile = RequestBody.create("multipart/form-data".toMediaTypeOrNull(), f)
                val fileBody = MultipartBody.Part.createFormData("headImage", f.name, requestFile)
                mPresenter?.addUserInfo(id_tv_birth.text.toString(),id_edit_invite_code.text.toString(),id_edit_nickname.text.toString(),gender,fileBody)
            }else{
                mPresenter?.addUserNoHeadImg(id_tv_birth.text.toString(),id_edit_invite_code.text.toString(),id_edit_nickname.text.toString(),gender)
            }

        }
    }

    override fun chooseData(date: String?) {
        if (TextUtils.isEmpty(date)) {
            // id_tv_birth?.text = "生日"
        } else {
            id_tv_birth?.text = "$date"
            wiriteFinish()
        }
    }

    fun getDestroyed(): Boolean {
        return isDestroyed
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (data != null && resultCode == -1) {
            if (requestCode == PictureConfig.CHOOSE_REQUEST) {
                 selectList = PictureSelector.obtainMultipleResult(data)
                wiriteFinish()
               // Log.e("MXL", "se" + selectList[0].compressPath)
                val photoSize = Utils.dip2px(90)
                Glide.with(this).asBitmap().load(selectList!![0].compressPath)
                    .apply(
                        RequestOptions().diskCacheStrategy(DiskCacheStrategy.ALL)
                            .placeholder(R.drawable.icon_photo)
                    )
                    .into(object : SimpleTarget<Bitmap>(photoSize, photoSize) {
                        override fun onResourceReady(
                            resource: Bitmap,
                            transition: Transition<in Bitmap>?
                        ) {
                            val b = ImageUtils.getRoundedCornerBitmap(
                                resource,
                                photoSize.toFloat(),
                                photoSize.toFloat(),
                                Utils.dip2px(90).toFloat()
                            )
                                ?: return

                            Glide.with(AppContext.get()).load(resource)
                                .apply(RequestOptions().transform(CircleCrop()))
                                .into(id_img_photo)
//                            id_fragment_user_icon?.setImageBitmap(b)
                        }

                        override fun onLoadFailed(errorDrawable: Drawable?) {
                            val b = ImageUtils.getRoundedCornerBitmap(
                                BitmapFactory.decodeResource(resources, R.drawable.icon_photo),
                                photoSize.toFloat(), photoSize.toFloat(), Utils.dip2px(90).toFloat()
                            )
                                ?: return
//                            Glide.with(AppliContext.get()).load(resource)
//                                    .apply(RequestOptions().transform(CircleCrop()).error(R.drawable.user_default_icon))
//                                    .into(id_fragment_user_icon)
                        }
                    }
                    )
                //   id_img_photo.setImageURI(Uri.parse(selectList[0].compressPath))
            }
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        when (requestCode) {
            100 -> {
                if (grantResults.size > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    showDialog()
                } else {
                    // 权限被用户拒绝了。
                    if (!ActivityCompat.shouldShowRequestPermissionRationale(
                            this,
                            Manifest.permission.CAMERA
                        )
                    ) {
                        //提示用户前往设置界面自己打开权限
                        Toast.makeText(this, "请前往设置界面打开权限", Toast.LENGTH_SHORT).show()
                        return
                    }
                }
            }
        }
    }

    override fun addInfoSuc() {
        mLoading?.setResult(true, "注册成功", 1000)
        JumpUtils.activityJump(
            RounterBus.getRounter(RounterApi::class.java).getIntentActivityMain()
        )
        finish()
    }

    override fun addInfoFail() {
        mLoading?.setResult(false, "注册失败", 1000)
    }
    fun wiriteFinish(){
        if (!TextUtils.isEmpty(id_edit_nickname.text) && !TextUtils.isEmpty(gender)&&!TextUtils.isEmpty(id_tv_birth.text.toString()))
        {
            id_tv_regeist.setBackgroundResource(R.drawable.shape_aa60ff_r25)
        } else {
            id_tv_regeist.setBackgroundResource(R.drawable.shape_cccccc_r25)
        }
    }
}