package com.za.call

import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.provider.CallLog
import androidx.core.app.ActivityCompat
import com.blankj.utilcode.util.TimeUtils
import com.tencent.mmkv.MMKV
import com.za.common.GlobalData
import com.za.common.log.LogUtil
import com.za.ext.toJson
import com.za.net.BaseObserver
import com.za.net.RetrofitHelper
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.schedulers.Schedulers

object CallLogManager {
	private const val TAG = "CallLogManager"
	private var lastUploadTime : Long? = null
		set(value) {
			MMKV.defaultMMKV().encode("lastUploadCallLogTime", value ?: 0)
			field = value
		}
		get() {
			return MMKV.defaultMMKV().decodeLong("lastUploadCallLogTime", 0)
		}

	//要上传的电话
	var phoneCallContactBean : ContactRecordBean? = null

	fun uploadCallLog(context : Context) {
		if (ActivityCompat.checkSelfPermission(context,
				Manifest.permission.READ_CALL_LOG) != PackageManager.PERMISSION_GRANTED
		) {
			LogUtil.print(TAG, "没有通话记录读取权限")
			return
		}

		if (phoneCallContactBean == null || phoneCallContactBean?.phone.isNullOrEmpty()) {
			if (GlobalData.currentOrder == null) {
				return
			}
			phoneCallContactBean = ContactRecordBean(taskId = GlobalData.currentOrder?.taskId,
				taskCode = GlobalData.currentOrder?.taskCode,
				phone = GlobalData.currentOrder?.customerPhone)
		}

		val cursor = context.contentResolver.query(CallLog.Calls.CONTENT_URI,
			arrayOf(CallLog.Calls.NUMBER,
				CallLog.Calls.DATE,
				CallLog.Calls.DURATION,
				CallLog.Calls.TYPE),
			"${CallLog.Calls.NUMBER} = ${phoneCallContactBean?.phone} ",
			null,
			"${CallLog.Calls.DATE} DESC")

		LogUtil.print("call  count", "${cursor?.columnCount}")

		cursor?.use { c ->
			while (c.moveToNext()) {
				val date = c.getLong(c.getColumnIndexOrThrow(CallLog.Calls.DATE))
				val duration = c.getLong(c.getColumnIndexOrThrow(CallLog.Calls.DURATION))
				val type = c.getInt(c.getColumnIndexOrThrow(CallLog.Calls.TYPE))

				val callLong = c.getLong(c.getColumnIndexOrThrow(CallLog.Calls.DATE))

				if (System.currentTimeMillis() - callLong > 1000 * 60 * 50 * 24) {
					break
				}

				if (lastUploadTime != null && callLong <= lastUploadTime !!) {
					continue
				}

				uploadCallLogToServer(contactRecordBean = phoneCallContactBean,
					date,
					duration,
					type)
			}
		}
	}

	private fun uploadCallLogToServer(contactRecordBean : ContactRecordBean?,
		date : Long,
		duration : Long,
		type : Int) {
		if (contactRecordBean == null) {
			LogUtil.print("uploadCallLogToServer", "没有需要上传的电话")
			return
		}

		val state = if (duration == 0L) {
			if (type == CallLog.Calls.REJECTED_TYPE) { // 被拒接
				3
			} else {
				2
			}
		} else {
			1
		}

		val contactRecordRequest = ContactRecordRequest(taskId = contactRecordBean.taskId,
			state = state,
			taskCode = contactRecordBean.taskCode,
			callTime = TimeUtils.millis2String(date),
			duration = formatDuration(duration),
			remarkPath = "")
		doUploadCallLog(contactRecordRequest)
		LogUtil.print(TAG, "uploadCallLogToServer params=${contactRecordRequest.toJson()}")
	}

	private fun doUploadCallLog(contactRecordRequest : ContactRecordRequest) {
		RetrofitHelper.getDefaultService().uploadContactRecord(contactRecordRequest)
			.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
			.subscribe(object : BaseObserver<String>() {
				override fun doSuccess(it : String?) {
					lastUploadTime = System.currentTimeMillis()
				}

				override fun doFailure(code : Int, msg : String?) {
					LogUtil.print(TAG, "doFailure code=$code, msg=$msg")
				}
			})
	}

	// 将秒数转换为友好的时分秒格式
	fun formatDuration(duration : Long) : String {
		val hours = duration / 3600
		val minutes = (duration % 3600) / 60
		val seconds = duration % 60
		return when {
			hours > 0 && minutes == 0L && seconds == 0L -> "${hours}小时" // 只有小时
			hours > 0 -> "${hours}小时${minutes}分钟${seconds}秒" // 包含小时、分钟、秒
			minutes > 0 && seconds == 0L -> "${minutes}分钟" // 只有分钟
			minutes > 0 -> "${minutes}分钟${seconds}秒" // 包含分钟、秒
			seconds > 0 -> "${seconds}秒" // 只有秒
			else -> "" // 其他情况
		}
	}
}

//public int taskId;
//public int state;
//public String taskCode;
//public String callTime;
//public String duration;
//
//public String remarkPath;
data class ContactRecordRequest(val taskId : Int? = null,
	val state : Int? = null,
	val taskCode : String? = null,
	val callTime : String? = null,
	val duration : String? = null,
	val remarkPath : String? = null)

data class ContactRecordBean(val taskId : Int? = null,
	val taskCode : String? = null,
	val phone : String? = null)