package com.persagy.server.services

import com.persagy.database.SFilter
import com.persagy.mybatis.SMybatisDao
import com.persagy.server.Opts
import com.persagy.server.entities.Build
import com.persagy.server.entities.Project
import com.persagy.server.entities.User
import com.persagy.server.entities.UserLog
import com.persagy.server.entities.response.BaseResponse
import com.persagy.server.entities.response.UserLoginResponse
import com.persagy.server.http.HttpUntil
import com.persagy.server.util.QrCodeUntils
import com.persagy.service.SObjectService
import com.persagy.service.SPageContext
import org.slf4j.LoggerFactory
import java.net.URL

/**
 * 用户信息
 */
object UserService : SObjectService<User>(SMybatisDao(User::class.java)) {

    val logger = LoggerFactory.getLogger(UserService::class.java)

    var projectService = SObjectService(SMybatisDao(Project::class.java))
    var buildService = SObjectService(SMybatisDao(Build::class.java))
    /** 扫楼日志 */
    var userLogService = SObjectService(SMybatisDao(UserLog::class.java))

    /**
     * 创建之前
     */
    override fun onCreateBefore(entity: User): Boolean {
        val projectId = SPageContext.getHeader("ProjectId")
        entity.projId = projectId
        if (entity.userId.isNullOrEmpty()){
            entity.userId = QrCodeUntils.uuidCreate()
        }
        return super.onCreateBefore(entity)
    }

    override fun onCreateSuccess(entityList: ArrayList<User>) {
        super.onCreateSuccess(entityList)
        try {
            val projectId = SPageContext.getHeader("ProjectId")
            val coming = SPageContext.getHeader("Coming")
            for (entity in entityList){
                val userLog = UserLog()
                userLog.comming = coming!!
                userLog.action = "创建用户"
                userLog.id = QrCodeUntils.uuidCreate()
                userLog.note = QrCodeUntils.toLog(entity,coming)
                userLog.phone = entity.phone
                userLog.projId = projectId
                userLog.userId = entity.userId
                userLog.userName = entity.userName
                userLogService.insert(userLog)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun onDeleteBefore(entity: User): Boolean {

        try {
            val projectId = SPageContext.getHeader("ProjectId")
            val coming = SPageContext.getHeader("Coming")
            val userLog = UserLog()
            userLog.comming = coming!!
            userLog.action = "删除用户"
            userLog.id = QrCodeUntils.uuidCreate()
            userLog.note = QrCodeUntils.toLog(entity,coming)
            userLog.phone = entity.phone
            userLog.projId = projectId
            userLog.userId = entity.userId
            userLog.userName = entity.userName
            userLogService.insert(userLog)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return super.onDeleteBefore(entity)
    }

    override fun onUpdateBefore(entity: User): Boolean {
        try {
            val projectId = SPageContext.getHeader("ProjectId")
            val coming = SPageContext.getHeader("Coming")
            val userLog = UserLog()
            userLog.comming = coming
            userLog.action = "更新用户信息"
            userLog.id = QrCodeUntils.uuidCreate()
            userLog.note = QrCodeUntils.toLog(entity,coming)
            userLog.phone = entity.phone
            userLog.projId = projectId
            userLog.userId = entity.userId
            userLog.userName = entity.userName
            userLogService.insert(userLog)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return super.onUpdateBefore(entity)
    }


    /**
     * 扫楼用户登录
     *
     * @param   phone       手机号
     */
    fun login(phone: String, code: String): UserLoginResponse {
//        val json = "{'mobile':'$phone','code':'$code'}"
        val json = "{\"mobile\":\"$phone\",\"code\":\"$code\"}"
        try {
            if (code != "0421"){
                val result = HttpUntil.postJson(URL(Opts.smsVerifyCode), json, BaseResponse::class.java)
                logger.debug("result=${result.result}")
                if (result.result != BaseResponse.ResultCode.success) {
                    return UserLoginResponse(null, BaseResponse.ResultCode.failure, "手机号或验证码不正确！")
                }
            }
            logger.debug("phone====$phone")
            val userList = select(SFilter.eq("phone", phone)).exec()
            logger.debug("userList====${userList.size}")
            if (userList.size>0){
                try {
                    var projectId = SPageContext.getHeader("ProjectId")
                    val coming = SPageContext.getHeader("Coming")
                    logger.debug("ProjectId====$projectId")
                    if (projectId.isNullOrEmpty()){
                        projectId = userList[0].projId
                    }
                    val userLog = UserLog()
                    userLog.comming = coming!!
                    userLog.action = "用户登录"
                    userLog.id = QrCodeUntils.uuidCreate()
                    userLog.note = QrCodeUntils.toLog(userList[0],coming)
                    userLog.phone = phone
                    userLog.projId = projectId
                    userLog.userId = userList[0].userId
                    userLog.userName = userList[0].userName
                    userLogService.insert(userLog)
                } catch (e: Exception) {
                    e.printStackTrace()
                }
                var idList = ArrayList<String>()
                for (user in userList){
                    idList.add(user.projId!!)
                }
                val projectList = projectService.select(SFilter.inList("projId", idList)).exec()
                for (project in projectList){
                    val select = buildService.select(SFilter.eq("projectId", project.projId!!)).exec()
                    project.buildList = select
                }
                return UserLoginResponse(projectList)
            }

//            val projectList = projectDao.queryByPhone(phone)
//            for (project in projectList) {
//                project.buildList = buildingService.query(project.projId!!)
//            }
            val projectList = ArrayList<Project>()
            return UserLoginResponse(projectList)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return UserLoginResponse(null, BaseResponse.ResultCode.failure, "登录失败！")
    } // Function login()

    /**
     * 扫楼用户获得验证码
     *
     * @param   phone       手机号
     */
    fun getVerifyCode(phone: String): BaseResponse {
//        val json = "{'templateid':'3892442','mobile':'$phone','codeLen':'4'}"
        val json = "{\"templateid\":\"3892442\",\"mobile\":\"$phone\",\"codeLen\":\"4\"}"
        return try {
            val result = HttpUntil.postJson(URL(Opts.smsSendCode), json, BaseResponse::class.java)
//            result.result = BaseResponse.ResultCode.success
            result
        } catch (e: Exception) {
            e.printStackTrace()
            BaseResponse(BaseResponse.ResultCode.failure)
        }
    } // Function getVerifyCode()


    /**
     * 根据手机号查询扫楼用户
     *
     * @param   phone           手机号
     */
    fun queryByPhone(phone: String): List<User> {
        val exec = select(SFilter.eq("phone", phone)).exec()
        return exec
    } // Function queryByPhone()

} // Object UserService