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.Color
import android.graphics.drawable.Drawable
import android.net.Uri
import android.os.Build
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.util.Log
import android.view.View
import android.widget.ImageView
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.recyclerview.widget.GridLayoutManager
import byc.imagewatcher.ImageWatcher
import byc.imagewatcher.ImageWatcherHelper
import com.bigkoo.pickerview.builder.OptionsPickerBuilder
import com.bigkoo.pickerview.view.OptionsPickerView
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.google.gson.Gson
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.decoration.GridSpacingItemDecoration
import com.luck.picture.lib.entity.LocalMedia
import com.zxhl.cms.AppContext
import com.zxhl.cms.common.Const
import com.zxhl.cms.common.base.BaseActivity
import com.zxhl.cms.net.SettingPreference
import com.zxhl.cms.net.model.uc.UserInfo
import com.zxhl.cms.runtimepermission.NicePermission
import com.zxhl.cms.runtimepermission.NicePermissionListener
import com.zxhl.cms.utils.*
import com.zxhl.cms.widget.*
import com.zxhl.main.R
import com.zxhl.main.page.`interface`.*
import com.zxhl.main.page.adapter.PhotoMoveListener
import com.zxhl.main.page.adapter.PublishPhotoAdapter
import com.zxhl.main.page.contract.EditUserInfoContract
import com.zxhl.main.page.entity.JsonBean
import com.zxhl.main.page.presenter.EditUserInfoPresenter
import com.zxhl.main.page.view.DialogUtils
import kotlinx.android.synthetic.main.activity_layout_user_info.*
import kotlinx.android.synthetic.main.activity_layout_user_info.id_img_back
import kotlinx.android.synthetic.main.activity_layout_user_info.id_img_head
import kotlinx.android.synthetic.main.activity_layout_user_info.id_tv_address
import kotlinx.android.synthetic.main.activity_layout_user_info.id_tv_height
import kotlinx.android.synthetic.main.activity_layout_user_info.id_tv_zhiye
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody
import org.json.JSONArray
import java.io.File

//个人信息页面
class UserInfoActivity : BaseActivity(), EditUserInfoContract.View, ChooseDateCallBack,
    ChooseHeightCallBack, ChooseWeightCallBack, ChooseIncomeCallBack, ChossoccupationCallBack,
    ChooseGenderCallBack, OnRecycleItemClickListener<String>,
    ImageWatcher.OnPictureLongPressListener, AdCallback<String>,
    PhotoMoveListener {
    private var mPresenter: EditUserInfoPresenter? = null
    var selectList: List<LocalMedia>? = ArrayList()
    private var options1Items: ArrayList<JsonBean> = ArrayList() //省
    private val options2Items: ArrayList<ArrayList<String>> = ArrayList() //市
    private val options3Items: ArrayList<ArrayList<ArrayList<String>>> = ArrayList() //区
    private var mAdapter: PublishPhotoAdapter? = null
    private val COLUMN: Int = 3
    private var mLoading: LoadingDialog? = null
    private var mImgUrlList = ArrayList<String>()
    private var iwHelper: ImageWatcherHelper? = null
    var isTranslucentStatus = false
    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_user_info
    }

    override fun init() {
        initJsonData()
        initPhoto()
        updateView()
        mLoading = LoadingDialog.getLoadingDialog(
            this,
            getString(com.zxhl.cms.R.string.wait_ing),
            false,
            false
        )
        mPresenter = EditUserInfoPresenter(this)
        mPresenter?.getUserInfo()
        id_edit_desc?.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                if (s != null) {
                    id_tv_length?.text = (30 - s!!.length).toString()
                }

            }

            override fun afterTextChanged(s: Editable?) {

            }

        })
        id_img_back?.setOnClickListener {
            finish()
        }
        id_rl_voice?.setOnClickListener {
            JumpUtils.VoiceJump()
        }
        id_img_head?.setOnClickListener {
            checkPermission()
        }
        id_rl_birth?.setOnClickListener {
            DialogUtils.showchooseDate(this, this)
        }
        id_rl_city?.setOnClickListener {
            showPickerView()
        }
        id_rl_height?.setOnClickListener {
            DialogUtils.showchooseHeight(this, this)
        }
        id_rl_gender?.setOnClickListener {
            DialogUtils.showchooseGender(this, this)
        }

        id_rl_weight?.setOnClickListener {
            DialogUtils.showchooseWeight(this, this)
        }
        id_rl_income?.setOnClickListener {
            DialogUtils.showchooseIncome(this, this)
        }
        id_rl_zhiye?.setOnClickListener {
            DialogUtils.showchooseoccupation(this, this)
        }
        id_tv_sava_info?.setOnClickListener {
            saveInfo()
        }
        id_rl_nick_name?.setOnClickListener {
            JumpUtils.UpdateNickNameJump()
        }
        id_rl_introduction?.setOnClickListener {
            JumpUtils.UpdateIntrodutionJump(description)
        }
    }

    fun initPhoto() {
        iwHelper =
            ImageWatcherHelper.with(this, GlideSimpleLoader()) // 一般来讲， ImageWatcher 需要占据全屏的位置
                .setTranslucentStatus(if (!isTranslucentStatus) Utils.calcStatusBarHeight(AppContext.get()) else 0) // 如果不是透明状态栏，你需要给ImageWatcher标记 一个偏移值，以修正点击ImageView查看的启动动画的Y轴起点的不正确
                .setErrorImageRes(R.mipmap.error_picture) // 配置error图标 如果不介意使用lib自带的图标，并不一定要调用这个API
                .setOnPictureLongPressListener(this)
                .setOnStateChangedListener(object : ImageWatcher.OnStateChangedListener {
                    override fun onStateChangeUpdate(
                        imageWatcher: ImageWatcher,
                        clicked: ImageView,
                        position: Int,
                        uri: Uri,
                        animatedValue: Float,
                        actionTag: Int
                    ) {
                        Log.e(
                            "IW",
                            "onStateChangeUpdate [$position][$uri][$animatedValue][$actionTag]"
                        )
                    }

                    override fun onStateChanged(
                        imageWatcher: ImageWatcher,
                        position: Int,
                        uri: Uri,
                        actionTag: Int
                    ) {
                        if (actionTag == ImageWatcher.STATE_ENTER_DISPLAYING) {
                            //  Toast.makeText(getApplicationContext(), "点击了图片 [" + position + "]" + uri + "", Toast.LENGTH_SHORT).show();
                        } else if (actionTag == ImageWatcher.STATE_EXIT_HIDING) {
                            //  Toast.makeText(getApplicationContext(), "退出了查看大图", Toast.LENGTH_SHORT).show();
                        }
                    }
                })
                .setIndexProvider(CustomDotIndexProvider()) //自定义页码指示器（默认数字）
                .setLoadingUIProvider(CustomLoadingUIProvider()) // 自定义LoadingUI
        mAdapter = PublishPhotoAdapter(mActivity, this, this)
        id_rl_choose_photo?.layoutManager = GridLayoutManager(mActivity, COLUMN)
        id_rl_choose_photo.addItemDecoration(GridSpacingItemDecoration(COLUMN, 20, false))
        id_rl_choose_photo.setAdapter(mAdapter)
    }

    var headImg: MultipartBody.Part? = null
    fun saveInfo() {
        // if()
        if (TextUtils.isEmpty(id_tv_birth?.text.toString()) || TextUtils.isEmpty(id_edit_desc?.text.toString()) ||
            TextUtils.isEmpty(id_tv_height?.text.toString()) || TextUtils.isEmpty(id_tv_nianxin?.text.toString()) || TextUtils.isEmpty(
                id_edit_nickname?.text.toString()
            ) ||
            TextUtils.isEmpty(id_tv_zhiye?.text.toString()) || TextUtils.isEmpty(id_tv_address?.text.toString()) ||
            TextUtils.isEmpty(id_tv_weight?.text.toString())
        ) {
            showToast("请继续完善未填写项哦~")
            return
        }

        if (!selectList.isNullOrEmpty()) {
            val f = File(selectList!![0].compressPath)
            val requestFile = RequestBody.create("multipart/form-data".toMediaTypeOrNull(), f)
            headImg = MultipartBody.Part.createFormData("headImage", f.name, requestFile)
            mPresenter?.updateUserInfo(
                id_tv_birth?.text.toString(),
                id_edit_desc?.text.toString(),
                headImg,
                id_tv_height.text.toString(),
                id_tv_nianxin.text.toString(),
                id_edit_nickname.text.toString(),
                id_tv_zhiye.text.toString(),
                id_tv_address.text.toString(),
                id_tv_weight.text.toString()
            )
        } else {
            mPresenter?.updateUserInfoNoHeadImg(
                id_tv_birth?.text.toString(),
                id_edit_desc?.text.toString(),
                id_tv_height.text.toString(),
                id_tv_nianxin.text.toString(),
                id_edit_nickname.text.toString(),
                id_tv_zhiye.text.toString(),
                id_tv_address.text.toString(),
                id_tv_weight.text.toString()
            )
        }



        mLoading?.setLoading("loading")
        mLoading?.show()
    }

    var description: String = ""
    override fun setData(result: UserInfo?) {
        if (result != null) {
            id_edit_nickname?.setText(result?.nickname)
            if (!TextUtils.isEmpty(result.headImage)) {
                Glide.with(this).load(result.headImage)
                    .apply(RequestOptions.bitmapTransform(CircleCrop()))
                    .into(id_img_head)
            } else {
                id_img_head.setImageResource(R.drawable.icon_user_photo_default)
            }
            if(result?.location!=null){
                id_tv_location?.text=result.location.en?.country
            }

            id_tv_birth?.text = "${result.age}"
            if (!TextUtils.isEmpty(result.description)) {
                description = result.description
                id_tv_introduction?.text = "${result.description}"
            }

            if (TextUtils.equals(result.sex.toString(), "1")) {
                id_tv_gender?.text = "Boy"
            } else {
                id_tv_gender?.text = "Girl"
            }

            if (!TextUtils.isEmpty(result.description)) {
                id_edit_desc?.setText(result.description)
                id_tv_length.text = (30 - result.description.length).toString()
            } else {
                id_tv_length.text = "30"
            }
            if (!TextUtils.isEmpty(result.height)) {
                id_tv_height?.text = result.height
            }
            if (!TextUtils.isEmpty(result.weight)) {
                id_tv_weight?.text = result.weight
            }
            if (!TextUtils.isEmpty(result.province)) {
                id_tv_address?.setText(result.province)
            }
            if (!TextUtils.isEmpty(result.occupation)) {
                id_tv_zhiye?.setText(result.occupation)
            }
            if (!TextUtils.isEmpty(result.income)) {
                id_tv_nianxin?.setText(result.income)
            }
            if (!TextUtils.isEmpty(result.voice)) {
                SettingPreference.setVoiceUrl(result.voice)
            } else {
                SettingPreference.setVoiceUrl("")
            }
            if (!TextUtils.isEmpty(result.voiceTime)) {
                SettingPreference.setVoiceTime(result.voiceTime)
            } else {
                SettingPreference.setVoiceTime("")
            }

        }

    }


    fun showPickerView() {
        val pvOptions: OptionsPickerView<*> = OptionsPickerBuilder(
            this
        ) { options1, options2, options3, v -> //返回的分别是三个级别的选中位置
            id_tv_address.setText(
                options1Items[options1].pickerViewText
                        + options2Items[options1][options2]
                        + options3Items[options1][options2][options3]
            )
        }
            .setTitleText("城市选择")
            .setSubmitColor(resources.getColor(R.color.color_aa60ff))
            .setTitleBgColor(Color.WHITE)
            .setCancelColor(resources.getColor(R.color.color_333333))//取消按钮文字颜色
            .setDividerColor(resources.getColor(R.color.color_ededed))
            .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
            .setContentTextSize(20)
            .build<Any>()
        pvOptions.setPicker(
            options1Items as List<Nothing>?,
            options2Items as List<Nothing>?, options3Items as List<Nothing>?
        ) //三级选择器

        pvOptions.show()

    }

    //检查用的权限
    fun checkPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            NicePermission(this, object : NicePermissionListener {
                override fun onGranted() {
                    openPhoto()
                }

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

    }

    fun openPhoto() {
        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
            .isDragFrame(false)
            .showCropGrid(false)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false    true or false
            .forResult(PictureConfig.REQUEST_CAMERA)//结果回调onActivityResult code

    }

    private val mImgList = ArrayList<LocalMedia>()
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (data != null && resultCode == -1) {
            if (requestCode == PictureConfig.REQUEST_CAMERA) {
                selectList = PictureSelector.obtainMultipleResult(data)
                updateHeadImg()
                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_head)
                        }

                        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
                        }
                    }
                    )
            } else if (requestCode == PictureConfig.CHOOSE_REQUEST) {
                val selectList = PictureSelector.obtainMultipleResult(data)
                if (mAdapter != null) {
                    //   mPhtoList?.addAll(mAdapter?.list!!)
                }
                if (!selectList.isNullOrEmpty()) {
                    mImgList?.clear()
                    mImgList?.addAll(selectList)
                    checkImgList(0)
                }
            }
        }
    }

    fun checkImgList(num: Int) {
        if (mImgList.size > 0) {
            val data = mImgList[0]
            mImgList?.removeAt(0)
            uploadFile(data, num)
        } else {
            uploadPhotoUrl()
        }
    }

    //上传本地图片获取url
    fun uploadFile(data: LocalMedia, num: Int) {
        Log.e("MXL", "本地路径" + data.compressPath)
        val f = File(data.compressPath)
        val requestFile =
            RequestBody.create("multipart/form-data".toMediaTypeOrNull(), f)
        val fileBody =
            MultipartBody.Part.createFormData("file", f.name, requestFile)
        mLoading?.setLoading("上传中")
        mLoading?.show()
        mPresenter?.upload(fileBody)
        //写上报地址获取url逻辑，成功or失败， 成功调 mImgUrlList.add(url)  checkImgList(0)
        //失败
//        if (num < 3) {
//            val s = num + 1
//            uploadFile(data, s)
//        } else if (num == 3) {
//            //重试了三次失败的。
//            // data 做记录
//            // checkImgList(0)
//        } else {
//            checkImgList(0)
//        }
    }

    fun uploadPhotoUrl() {
        if (mImgUrlList.size > 0) {
            //走打包上报url逻辑
            val sb = StringBuilder()
            for (str in mImgUrlList!!) {
                if (sb.length > 0) {
                    sb.append(",")
                }
                sb.append(str)
            }
            Log.e("MXL", "参数" + sb.toString())
            mPresenter?.pictures(sb.toString())

        } else {
            //删到最后一张了
            mPresenter?.pictures("")
        }
    }

    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) {
                    openPhoto()
                } else {
                    // 权限被用户拒绝了。
                    if (!ActivityCompat.shouldShowRequestPermissionRationale(
                            this,
                            Manifest.permission.CAMERA
                        )
                    ) {
                        //提示用户前往设置界面自己打开权限
                        Toast.makeText(this, "请前往设置界面打开权限", Toast.LENGTH_SHORT).show()
                        return
                    }
                }
            }
        }
    }


    fun parseData(result: String?): ArrayList<JsonBean>? { //Gson 解析
        val detail: ArrayList<JsonBean> = ArrayList()
        try {
            val data = JSONArray(result)
            val gson = Gson()
            for (i in 0 until data.length()) {
                val entity = gson.fromJson(
                    data.optJSONObject(i).toString(),
                    JsonBean::class.java
                )
                detail.add(entity)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return detail
    }

    private fun initJsonData() { //解析数据 （省市区三级联动）
        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         */
        val JsonData = GetJsonDataUtil().getJson(this, "province.json") //获取assets目录下的json文件数据
        val jsonBean = parseData(JsonData) //用Gson 转成实体
        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean!!
        for (i in 0 until jsonBean.size) { //遍历省份
            val CityList: ArrayList<String> = ArrayList() //该省的城市列表（第二级）
            val Province_AreaList: ArrayList<ArrayList<String>> = ArrayList() //该省的所有地区列表（第三级）
            for (c in 0 until jsonBean[i].cityList.size) { //遍历该省份的所有城市
                val CityName = jsonBean[i].cityList[c].name
                CityList.add(CityName) //添加城市
                val City_AreaList: ArrayList<String> = ArrayList() //该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean[i].cityList[c].area == null
                    || jsonBean[i].cityList[c].area.size === 0
                ) {
                    City_AreaList.add("")
                } else {
                    City_AreaList.addAll(jsonBean[i].cityList[c].area)
                }
                Province_AreaList.add(City_AreaList) //添加该省所有地区数据
            }
            /**
             * 添加城市数据
             */
            options2Items.add(CityList)
            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList)
        }
    }

    override fun chooseData(data: String?) {
        if (TextUtils.isEmpty(data)) {
        } else {
            id_tv_birth?.text = "$data"
        }
    }

    override fun chooseHeight(string: String?) {
        if (TextUtils.isEmpty(string)) {
        } else {
            id_tv_height?.text = string
        }
    }

    override fun chooseWeight(string: String?) {
        if (TextUtils.isEmpty(string)) {
        } else {
            id_tv_weight?.text = string
        }
    }

    override fun chooseIncom(string: String?) {
        if (TextUtils.isEmpty(string)) {
        } else {
            id_tv_nianxin?.text = string
        }
    }

    override fun chooseOccupation(string: String?) {
        if (TextUtils.isEmpty(string)) {
        } else {
            id_tv_zhiye?.text = string
        }
    }

    override fun chooseGender(string: String?) {
        if (TextUtils.isEmpty(string)) {
        } else {
            mLoading?.setLoading("loading")
            mLoading?.show()
            id_tv_gender?.text = string
            if (TextUtils.equals(string, "Boy")) {
                mPresenter?.updateUserSex("1")
            } else {
                mPresenter?.updateUserSex("2")
            }

        }
    }

    override fun onItemClick(view: View?, position: Int, data: String?) {
        when (view?.id) {
            R.id.id_img_add -> {
                EventUtils.onEvent("UploadAlbumImage", "相册上传图")
                PictureSelector.create(this)
                    .openGallery(PictureConfig.TYPE_IMAGE)
                    .imageSpanCount(4)// 每行显示个数 int
                    .maxSelectNum(getSize())
                    .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(false)// 是否裁剪 true or false
                    .compress(true)// 是否压缩 true or false
                    .compressSavePath(Const.getImgPath())//压缩图片保存地址
                    .showCropFrame(true)// 是否显示裁剪矩形边框 圆形裁剪时建议设为 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
            }
            R.id.id_img_del -> {
                delet(position)
            }
            R.id.id_img_show -> {
                Log.e("MXL","mImgUrlList:"+mImgList.size)
                iwHelper?.show(
                    getImageUriList(mImgUrlList), position
                )
            }
        }
    }

    fun getSize(): Int {
        if (mAdapter == null) {
            return 6
        } else {
            return 7 - mAdapter?.itemCount!!
        }

    }

    fun getImageUriList(files: List<String?>?): List<Uri>? {
        val imageUriList: MutableList<Uri> = java.util.ArrayList()
        if (files != null && files.size > 0) {
            for (str in files) {
                imageUriList.add(Uri.parse(str))
            }
        }
        return imageUriList
    }

    override fun onPictureLongPress(v: ImageView?, uri: Uri?, pos: Int) {

    }

    override fun moveFinish() {

    }

    override fun onResult(code: Int, result: String?) {
        updateView()

    }

    override fun onResume() {
        super.onResume()
        updateNickName()
    }
    //返回更新用户姓名和签名
    fun updateNickName() {
        val user = SettingPreference.getUserInfoData()
        if (user == null) {
            return
        }
        id_edit_nickname?.text=user.nickname
        if(!TextUtils.isEmpty(user.description)){
            id_tv_introduction.text=user.description
        }

    }

    fun updateView() {
        val user = SettingPreference.getUserInfoData()
        if (user == null) {
            return
        }
        if (!user.picturesList.isNullOrEmpty()) {
            mImgUrlList?.clear()
            mImgUrlList?.addAll(user.picturesList)
            if (mAdapter != null) {
                mAdapter?.clear()
            }
            mAdapter?.appendToList(user.picturesList)
            mAdapter?.notifyDataSetChanged()
        } else {
            if (mAdapter != null) {
                mAdapter?.clear()
            }
        }
    }

    fun delet(position: Int) {
        mImgUrlList?.removeAt(position)
        mLoading?.setLoading("loading")
        mLoading?.show()
        uploadPhotoUrl()
    }

    override fun updateSuc() {
        mLoading?.setResult(true, "success", 1000)
        // finish()
    }

    override fun updateFail() {
        mLoading?.setResult(false, "fail", 1000)
    }

    override fun uploadSuc(result: String) {
        mImgUrlList.add(result)
        checkImgList(0)
    }

    override fun uploadFail() {

    }

    override fun updatePicSuc() {
        mImgUrlList.clear()
        mLoading?.setResult(true, "Success", 1000)
        UserDataUtils.updateUserInfo(this)

    }

    override fun updatePicFail() {
        mLoading?.setResult(true, "Fail", 1000)
    }

    fun updateHeadImg() {
        if (!selectList.isNullOrEmpty()) {
            val f = File(selectList!![0].compressPath)
            val requestFile = RequestBody.create("multipart/form-data".toMediaTypeOrNull(), f)
            headImg = MultipartBody.Part.createFormData("headImage", f.name, requestFile)
            mPresenter?.updateUserHeadImg(headImg)
        }
    }
    override fun onBackPressed() {
        if (!iwHelper!!.handleBackPressed()) {
            super.onBackPressed()
        }
    }


}