/*
 * *********************************************************************************************************************
 *
 *          !!
 *        .F88X
 *        X8888Y
 *      .}888888N;
 *        i888888N;        .:!              .I$WI:
 *          R888888I      .'N88~            i8}+8Y&8"l8i$8>8W~'>W8}8]KW+8IIN"8&
 *          .R888888I    .;N8888~          .X8'  "8I.!,/8"  !%NY8`"8I8~~8>,88I
 *            +888888N;  .8888888Y                                  "&&8Y.}8,
 *            ./888888N;  .R888888Y        .'}~    .>}'.`+>  i}!    "i'  +/'  .'i~  !11,.:">,  .~]!  .i}i
 *              ~888888%:  .I888888l      .]88~`1/iY88Ii+1'.R$8$8]"888888888>  Y8$  W8E  X8E  W8888'188Il}Y88$*
 *              18888888    E8888881    .]W%8$`R8X'&8%++N8i,8N%N8+l8%`  .}8N:.R$RE%N88N%N$K$R  188,FE$8%~Y88I
 *            .E888888I  .i8888888'      .:$8I;88+`E8R:/8N,.>881.`$8E/1/]N8X.Y8N`"KF&&FK!'88*."88K./$88%RN888+~
 *            8888888I  .,N888888~        ~88i"8W,!N8*.I88.}888%F,i$88"F88"  888:E8X.>88!i88>`888*.}Fl1]*}1YKi'
 *          i888888N'      I888Y          ]88;/EX*IFKFK88X  K8R  .l8W  88Y  ~88}'88E&%8W.X8N``]88!.$8K  .:W8I
 *        .i888888N;        I8Y          .&8$  .X88!  i881.:%888>I88  ;88]  +88+.';;;;:.Y88X  18N.,88l  .+88/
 *      .:R888888I
 *      .&888888I                                          Copyright (c) 2009-2020.  博锐尚格科技股份有限公司
 *        ~8888'
 *        .!88~                                                                     All rights reserved.
 *
 * *********************************************************************************************************************
 */

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.projectId = 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.projectId = 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.projectId = 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.projectId = 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].projectId
                    }
                    val userLog = UserLog()
                    userLog.comming = coming!!
                    userLog.action = "用户登录"
                    userLog.id = QrCodeUntils.uuidCreate()
                    userLog.note = QrCodeUntils.toLog(userList[0],coming)
                    userLog.phone = phone
                    userLog.projectId = 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.projectId!!)
                }
                val projectList = projectService.select(SFilter.inList("projId", idList)).exec()
                for (project in projectList){
                    val select = buildService.select(SFilter.eq("projectId", project.id!!)).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