package com.ysnows.base.utils

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.text.TextUtils
import android.widget.Toast
import com.yanzhenjie.permission.AndPermission
import com.yanzhenjie.permission.runtime.Permission
import com.ysnows.base.R
import com.ysnows.base.utils.Toasts.toast
import java.util.regex.Pattern

object DialUtils {
    /**
     * 拨打电话（跳转到拨号界面，用户手动点击拨打）
     *
     * @param phoneNum 电话号码
     */
    fun dialPhone(context: Context?, phoneNum: String) {
        if (TextUtils.isEmpty(phoneNum)) {
            toast(context, context?.getString(R.string.mobile_number_must_not_be_empty), Toast.LENGTH_SHORT)
            return
        }

//        if (!isMobileNO(phoneNum)) {
//            Toasts.toast(context, context.getString(R.string.wrong_format_of_mobile_number));
//            return;
//        }
        AndPermission.with(context)
                .runtime()
                .permission(Permission.CALL_PHONE)
                .onGranted {
                    val intent = Intent(Intent.ACTION_DIAL)
                    val uri_data = Uri.parse("tel:$phoneNum")
                    intent.data = uri_data
                    context?.startActivity(intent)
                }.start()
    }

    /**
     * 拨打电话（直接拨打电话）
     *
     * @param phoneNum 电话号码
     */
    fun callPhone(context: Context?, phoneNum: String) {
        val intent = Intent(Intent.ACTION_CALL)
        val data = Uri.parse("tel:$phoneNum")
        intent.data = data
        context?.startActivity(intent)
    }

    /**
     * 验证手机号是否正确
     *
     * @param mobiles
     *
     * @return
     */
    fun isMobileNO(mobiles: String?): Boolean {
        val p = Pattern.compile("^(13[0-9]|14[57]|15[0-35-9]|17[6-8]|18[0-9])[0-9]{8}$")
        val m = p.matcher(mobiles)
        return m.matches()
    }
}