package com.rdiot.yx485.net

import android.net.Uri
import com.drake.net.*
import com.drake.net.interfaces.ProgressListener
import com.rdiot.yx485.BuildConfig
import com.rdiot.yx485.base.LocalData
import com.rdiot.yx485.bean.*
import com.rdiot.yx485.ui.home.HomeFragment
import com.rdiot.yx485.util.RoomUtils
import com.rdiot.yx485.util.md5
import kotlinx.coroutines.CoroutineScope
import java.io.File

/**
 *
 * @author mR2hao
 * @date 2022/11/16
 */
object Api {
    /** Api地址 */
    const val TEST_HOST = "http://113.128.186.214:8199/api/v1/"
//    const val TEST_HOST = "https://app.yongxulvjian.com/api/v1/"

    /** 头像地址 */
    const val TEST_AVATAR_HOST = "http://yongxu.yehaoji.cn:18199"

    /** Api地址 */
    const val HOST = "https://app.yongxulvjian.com/api/v1/"

    /** 头像地址 */
    const val AVATAR_HOST = "https://app.yongxulvjian.com"

    /** App接口 */
    object App {
        /** 初始化 */
        const val BASE = "init"

        /** 检测版本 */
        const val CHECK_VERSION = "check_version"

        /** 天气 */
        const val WEATHER = "homepages/weather"

        /** 欢迎 */
        const val WELCOME = "system_parameter/app_homepage"
    }

    /** 登录接口 */
    object Login {
        private const val BASE = "login"

        /** 获取验证码 */
        const val GET_SMS_CODE = "${BASE}/code"

        /** 验证码登录 */
        const val SMS_LOGIN = "${BASE}/sms"

        /** 验证码登录 */
        const val PWD_LOGIN = "${BASE}/password"

        /** 登出 */
        const val SIGN_OUT = "${BASE}/exit"

        /** 注销 */
        const val LOG_OUT = "${BASE}/unsubscribe"

        /** 设置密码 */
        const val SET_PWD = "${BASE}/set_password"

        /** 更新密码 */
        const val RESET_PWD = "${BASE}/update_pass"

        /** 刷新Token */
        const val REFRESH_TOKEN = "${BASE}/refresh/token"
    }

    /** 用户接口 */
    object User {
        private const val BASE = "users"

        /** 获取当前用户信息 */
        const val GET_CURRENT_USER_DATA = "${BASE}/current"

        /** 用户信息 */
        const val USER_INFO = "${BASE}/%s"

    }

    /** 家庭管理接口 */
    object Family {
        const val BASE = "homes"

        /** 家庭成员管理 */
        const val MEMBER = "family_members"

        /** 默认家 */
        const val DEFAULT_FAMILY = "${BASE}/default"

        /** 家列表 */
        const val ALL_FAMILY = "${BASE}?q=list"

        /** 获取指定ID的家庭信息 */
        const val FAMILY_INFO = "${BASE}/%s"

        /** 添加家庭成员 */
        const val INVITE_MEMBER = "${MEMBER}/invite"

        /** 设置默认家庭 */
        const val SET_DEFAULT_FAMILY = "${MEMBER}/default/%s"
    }

    /** 房间管理 */
    object Room {
        const val BASE = "rooms"

        /** 获取指定ID的房间信息 */
        const val GET_ROOM_INFO = "${BASE}/%s"

        const val Room_Device = "${BASE}/%s/device_type"
    }

    /** 设备控制 */
    object Ctrl {
        private const val BASE = "control"

        /** 总开关 */
        const val POWER = "${BASE}/power"

        /** 新风开关 */
        const val FRESH_AIR = "${BASE}/new_fan"

        /** 睡眠开关 */
        const val SLEEP = "${BASE}/sleep"

        /** 模式 */
        const val MODE = "${BASE}/mode"

        /** 温度 */
        const val TEMP = "${BASE}/temp"

        /** 定时 */
        const val TIMER = "${BASE}/timer"

        /** 主控风速 */
        const val WIND_SPEED = "${BASE}/speed"

        /** 分控开关 */
        const val SUB_POWER = "${BASE}/fan_power"

        /** 分控风速 */
        const val SUB_WIND_SPEED = "${BASE}/fan_value"

        const val DEVICE_ONLINE = "${BASE}/online/%s"
    }

    object File {
        const val BASE = "files"

    }

    /** 设备接口 */
    object Device {
        /** 获取设备类型 */
        const val GET_DEVICE_TYPES = "device_types"
    }
}

/************************** App相关 **************************/
fun CoroutineScope.refreshToken() = Put<LoginData>(Api.Login.REFRESH_TOKEN)

/** 初始化 */
fun CoroutineScope.appInit() = Post<BaseResp<String>>(Api.App.BASE)

/** 检查版本号 */
fun CoroutineScope.checkVersion() = Post<AppVersionData>(Api.App.CHECK_VERSION) {
    json(
        "version" to BuildConfig.VERSION_NAME,
        "platform" to "ANDROID"
    )
}

/** 获取天气 */
fun CoroutineScope.getWeather(familyId: String? = null) = Get<WeatherData>(Api.App.WEATHER) {
    param("home_id", familyId ?: LocalData.selFamilyId.value)
}

/** 获取欢迎语 */
fun CoroutineScope.getWelcome() =
    Get<WelcomeData>(Api.App.WELCOME)

/************************** 登录、用户相关 **************************/
/** 短信类型 */
enum class SmsLimit(val limitType: Int) {
    /** 登录 */
    LOGIN(1),

    /** 忘记密码 */
    RESET_PWD(2)
}

/** 获取手机短信 */
fun CoroutineScope.getSms(phone: String?, limit: SmsLimit) =
    Post<BaseResp<String>>(Api.Login.GET_SMS_CODE) {
        json(
            "tel" to phone,
            "bzty" to limit.limitType,
            "resend_limit" to 1,
            "expired" to 999999999,
        )
    }

/** 短信登录 */
fun CoroutineScope.loginViaSMS(phone: String?, code: String?) =
    Post<LoginData>(Api.Login.SMS_LOGIN) {
        json(
            "phone" to phone,
            "code" to code
        )
    }

/** 密码登录 */
fun CoroutineScope.loginViaPwd(phone: String?, password: String?) =
    Post<LoginData>(Api.Login.PWD_LOGIN) {
        json(
            "phone" to phone,
            "password" to password?.md5()
        )
    }

/** （首次登录）设置密码 */
fun CoroutineScope.setPwd(pwd: String) = Put<BaseResp<String>>(Api.Login.SET_PWD) {
    json(
        "password" to pwd.md5()
    )
}

/** 更新密码（找回、重置密码） */
fun CoroutineScope.resetPwd(phone: String?, code: String?, newPwd: String?) =
    Put<BaseResp<String>>(Api.Login.RESET_PWD) {
        json(
            "phone" to phone,
            "code" to code,
            "new_password" to newPwd?.md5()
        )
    }

/** 注销账户 */
fun CoroutineScope.logOut() = Patch<BaseResp<String>>(Api.Login.LOG_OUT)

/** 登出 */
fun CoroutineScope.signOut() = Post<BaseResp<String>>(Api.Login.SIGN_OUT)

/** 获取当前用户信息 */
fun CoroutineScope.getCurrentUserData() = Get<UserData>(Api.User.GET_CURRENT_USER_DATA)

/** 头像上传 */
fun CoroutineScope.uploadAvatar(imgUri: Uri, listener: ProgressListener?) =
    Post<AvatarData>(Api.File.BASE) {
        param("file", File(imgUri.path))
        listener?.let {
            addUploadListener(it)
        }
    }

/** 通过手机号获取用户信息 */
fun CoroutineScope.getUserData(phone: String) =
    Get<UserData>(String.format(Api.User.USER_INFO, phone))

/** 更新用户信息 */
fun CoroutineScope.updateUserData(userData: UserData) =
    Put<BaseResp<String>>(String.format(Api.User.USER_INFO, userData.recordId)) {
        json(
            "user_name" to userData.userName,
            "photo" to userData.photo
        )
    }


/************************** 家庭管理 **************************/
/** 获取指定ID家信息，传入ID为空时候，默认为选择的家庭ID */
fun CoroutineScope.getFamilyData(familyId: String? = null) =
    Get<FamilyData>(
        String.format(
            Api.Family.FAMILY_INFO,
            familyId ?: LocalData.selFamilyId.value
        )
    )

/** 获取家列表 */
fun CoroutineScope.getAllFamilyData(isOnlyShowAdmin: Boolean) =
    Get<List<FamilyData>>(if (isOnlyShowAdmin) "${Api.Family.ALL_FAMILY}&is_admin=1" else Api.Family.ALL_FAMILY)

/** 更新信息家庭 */
fun CoroutineScope.updateFamilyData(familyData: FamilyData) = Put<BaseResp<String>>(
    String.format(
        Api.Family.FAMILY_INFO,
        familyData.recordId
    )
) {
    json(
        "name" to familyData.name,
        "city" to familyData.city,
    )
}

/** 邀请用户 */
fun CoroutineScope.inviteMember(familyData: FamilyData?, phone: String) =
    Post<BaseResp<String>>(Api.Family.INVITE_MEMBER) {
        json(
            "home_id" to familyData?.recordId,
            "phone" to phone
        )
    }

/** 删除用户 */
fun CoroutineScope.deleteMember(memberData: MemberData) =
    Delete<BaseResp<String>>(Api.Family.MEMBER) {
        json(
            "home_id" to memberData.homeId,
            "user_id" to memberData.userId
        )
    }

/** 通过家庭Id 设置默认家庭 */
fun CoroutineScope.setDefaultFamily(familyId: String?) =
    Put<BaseResp<String>>(String.format(Api.Family.SET_DEFAULT_FAMILY, familyId))

/** 新建家庭 */
fun CoroutineScope.addFamily(familyName: String, isSetDefault: Boolean) =
    Post<BaseResp<String>>(Api.Family.BASE) {
        json(
            "name" to familyName,
            "is_default" to isSetDefault
        )
    }

/** 删除家庭 */
fun CoroutineScope.deleteFamily(familyId: String?) =
    Delete<BaseResp<String>>(String.format(Api.Family.FAMILY_INFO, familyId))

/************************** 房间管理 **************************/
/** 添加房间（分控） */
fun CoroutineScope.addRoom(roomName: String, ctrlNum: String, recordId: String) =
    Post<BaseResp<String>>(Api.Room.BASE) {
        json(
            "name" to roomName,
            "home_id" to LocalData.selFamilyId.value,
            "control_number" to ctrlNum,
            "device_type_id" to recordId
        )
    }

fun CoroutineScope.addMasterRoom(roomName: String, ctrlNum: String, recordId: String) =
    Post<BaseResp<String>>(Api.Room.BASE) {
        json(
            "is_master" to 1,
            "name" to roomName,
            "home_id" to LocalData.selFamilyId.value,
            "control_number" to ctrlNum,
            "device_type_id" to recordId
        )
    }

/** 删除房间 */
fun CoroutineScope.delRoom(roomArray: List<RoomData>) = Delete<BaseResp<String>>(Api.Room.BASE) {
    val idArray = arrayListOf<String>()
    for (roomData in roomArray) {
        idArray.add(roomData.recordId)
    }
    json(
        "home_id" to LocalData.selFamilyId.value,
        "record_ids" to idArray
    )
}

/** 更新房间信息 */
fun CoroutineScope.updateRoomInfo(roomData: RoomData) =
    Put<BaseResp<String>>(String.format(Api.Room.GET_ROOM_INFO, roomData.recordId)) {
        json(
            "name" to roomData.name,
            "home_id" to roomData.homeId,
            "control_number" to roomData.controlNumber
        )
    }

/** 更新用户信息 */
fun CoroutineScope.updateRoomDeviceType(code:String,deviceTypeId:String) =
    Put<BaseResp<String>>(String.format(Api.Room.Room_Device, code)) {
        json(
            "device_type_id" to deviceTypeId,
        )
    }


/** 获取指定Id房间信息 */
fun CoroutineScope.getRoomInfo(roomId: String) =
    Get<RoomData>(String.format(Api.Room.GET_ROOM_INFO, roomId))


/************************** 设备控制 **************************/
/** 总控开关 */
fun CoroutineScope.setPower(gateway: String, roomData: RoomData) =
    Post<BaseResp<String>>(if (RoomUtils.isMaster(roomData.code)) Api.Ctrl.POWER else Api.Ctrl.SUB_POWER) {
        json(
            "record_id" to roomData.recordId,
            "gateway" to gateway,
            "control_number" to roomData.controlNumber,
            "power" to roomData.power
        )
    }

enum class ModeType(val typeCode: Int) {
    /** 制冷 */
    ZHI_LENG(0),

    /** 制热 */
    ZHI_RE(1),

    /** 除湿 */
    CHU_SHI(2),

    /** 送风 */
    SONG_FENG(3),

    /** 加湿 */
    JIA_SHI(4)

}

enum class DeviceCode(val typeCode: String) {
    /** 水系统-主控 */
    WATER_MASTER("YXK-Z/86-FC-B"),

    /** 水系统-分控 */
    WATER_SUB("YXK-F/86-FC-B"),

    /** 水系统-智能 */
    WATER_INTELLIGENCE("YXK-P/DN-JF-8"),

    /** 氟系统-主控 */
    FLUORINE_MASTER("YXK-Z/86-FG-A"),

    /** 氟系统-分控 */
    FLUORINE_SUB("YXK-F/86-FG-A"),

    INFRARED("INFRARED"),

    DRAUGHT_DISTRIBUTING_BOX("YXK-Z/86-FFX"),

    WATER_PLC("YXK-P/PLC-A"),
}

/** 设置模式 */
fun CoroutineScope.setMode(gateway: String, roomData: RoomData, modeType: ModeType) =
    Post<BaseResp<String>>(Api.Ctrl.MODE) {
        json(
            "record_id" to roomData.recordId,
            "gateway" to gateway,
            "control_number" to roomData.controlNumber,
            "mode" to modeType.typeCode
        )
    }

fun CoroutineScope.setFreshAir(gateway: String, roomData: RoomData) =
    Post<BaseResp<String>>(Api.Ctrl.FRESH_AIR) {
        json(
            "record_id" to roomData.recordId,
            "gateway" to gateway,
            "control_number" to roomData.controlNumber,
            "power" to roomData.freshAir
        )
    }

fun CoroutineScope.setSleep(gateway: String, roomData: RoomData) =
    Post<BaseResp<String>>(Api.Ctrl.SLEEP) {
        json(
            "gateway" to gateway,
            "control_number" to roomData.controlNumber,
            "power" to roomData.sleepMode
        )
    }

/** 设置定时 */
fun CoroutineScope.setTimer(
    gateway: String,
    roomData: RoomData,
    enable: Boolean,
    time: Float? = null
) = Post<BaseResp<String>>(Api.Ctrl.TIMER) {
    json(
        "record_id" to roomData.recordId,
        "gateway" to gateway,
        "control_number" to roomData.controlNumber,
        "timer_status" to enable,
        "timer" to time
    )
}

/** 设置温度 */
fun CoroutineScope.setTemp(gateway: String, roomData: RoomData, temp: Int) =
    Post<BaseResp<String>>(Api.Ctrl.TEMP) {
        json(
            "record_id" to roomData.recordId,
            "gateway" to gateway,
            "control_number" to roomData.controlNumber,
            "temp" to temp
        )
    }

/** 设置风速 */
fun CoroutineScope.setWindSpeed(
    gateway: String,
    roomData: RoomData,
    speed: Int,
    isMaster: Boolean
) =
    Post<BaseResp<String>>(if (isMaster) Api.Ctrl.WIND_SPEED else Api.Ctrl.SUB_WIND_SPEED) {
        json(
            "record_id" to roomData.recordId,
            "gateway" to gateway,
            "control_number" to roomData.controlNumber,
            "fan_value" to speed,
            "speed" to speed
        )
    }


fun CoroutineScope.getDeviceStatus(id: String? = null) =
    Get<DeviceStatus>(String.format(Api.Ctrl.DEVICE_ONLINE,  id))


/** 获取设备类型列表 */
fun CoroutineScope.getDeviceTypeList() =
    Get<List<DeviceTypeData>>(String.format(Api.Device.GET_DEVICE_TYPES))

