/*
 * ********************************************************************************************************************
 *
 *                     :*$@@%$*:                         ;:                ;;    ;;
 *                   :@@%!  :!@@%:                       %!             ;%%@@%$ =@@@@@@@%;     @%@@@%%%%@@@@@
 *                  :@%;       :$=                       %%$$$%$$         ;$$  ;$@=   !@$
 *                  =@!                                  %!              @ $=;%   !@@@%:      !$$$$$$$$$$$$$$=
 *                  =@*                                  %!              @ $= % %@=   =%@!      %=
 *             *$%%! @@=        ;=$%%%$*:                %!              @ $= % =%%%%%%@$      *%:         =%
 *           %@@!:    !@@@%=$@@@@%!  :*@@$:              %!              @ $= % $*     ;@      @*          :%*
 *         ;@@!          ;!!!;:         ;@%:      =======@%========*     @ $$ % $%*****$@     :@$=*********=@$
 *         $@*   ;@@@%=!:                *@*
 *         =@$    ;;;!=%@@@@=!           =@!
 *          %@$:      =@%: :*@@@*       %@=                    Copyright (c) 2016-2019.  北京上格云技术有限公司
 *           ;%@@$=$@@%*       *@@@$=%@@%;
 *              ::;::             ::;::                                              All rights reserved.
 *
 * ********************************************************************************************************************
 */

package com.persagy.server.messagecenter.services.base

import com.persagy.server.messagecenter.models.entities.base.BaseInfo
import com.alibaba.druid.support.json.JSONParser
import com.persagy.database.SAbstractDao
import com.persagy.database.SFilter
import com.persagy.server.messagecenter.models.request.BasicRequest
import com.persagy.service.SBaseService
import com.persagy.service.SPageContext
import com.persagy.service.models.enums.SResponseType
import com.persagy.service.models.requests.SQueryRequest
import com.persagy.service.models.requests.SUpdateRequest
import com.persagy.service.models.responses.SBaseResponse
import com.persagy.service.models.responses.SQueryResponse
import org.springframework.web.bind.annotation.RequestBody
import java.util.*
import kotlin.collections.ArrayList


open class Service<ENTITY : BaseInfo>(daoClass: SAbstractDao<ENTITY>)
    : SBaseService<ENTITY>(daoClass) {

    /**
     * 创建
     *
     * @param       request
     * @return      返回创建id
     */
    open fun create(request: ENTITY): SBaseResponse {
        return try {
            request.id = UUID.randomUUID().toString()
            request.projectId = getProject()
            baseDao.insert(request)
            SBaseResponse(SResponseType.success)
        } catch (e: Exception) {
            e.printStackTrace()
            SBaseResponse(SResponseType.failure, e.message!!)
        }
    } // Function create()

    /**
     * 获取项目号
     *
     * @return      返回项目号
     */
    open fun getProject(): String {
        return SPageContext.getHeader("ProjectId").toString()
    }// Function getProject()

    /**
     * 根据id删除
     *
     * @param       request
     * @return      返回成功/失败ID列表
     */
    open fun deleteList(request: ArrayList<*>): SBaseResponse {
        return try {
            for (id in request) {
                baseDao.delete(SFilter.eq("id", id), SFilter.eq("projectId", getProject()))

            }
            SBaseResponse(SResponseType.success)
        } catch (e: Exception) {
            e.printStackTrace()
            SBaseResponse(SResponseType.failure, e.message!!)
        }
    } // Function deleteList()

    /**
     * 更新
     *
     * @param       request
     * @return      返回成功/失败ID列表
     */
    open fun updateList(request: SUpdateRequest<ENTITY>): SBaseResponse {
        return try {
            for (info in request.content!!) {
                info.projectId = getProject()
                baseDao.update(info, request.projection, SFilter.eq("id", info.id!!), SFilter.eq("projectId", getProject()))
            }
            SBaseResponse(SResponseType.success)
        } catch (e: Exception) {
            e.printStackTrace()
            SBaseResponse(SResponseType.failure, e.message!!)
        }

    } // Function updateList()

    /**
     * 查询
     *
     * @param       request
     * @return      返回点位列表
     */
    open fun pageQuery(@RequestBody request: SQueryRequest, withFilterList: ArrayList<SFilter>): SQueryResponse<ENTITY> {
        return try {
            val queryBuilder = baseDao.select(request.filters).filter(SFilter.eq("ProjectId", getProject()))
            if (null != request.projection) {
                queryBuilder.projection(request.projection!!)
            }
            if (null != request.orders) {
                queryBuilder.order(request.orders!!)
            }
            val pageInfo = queryBuilder.pageQuery(request.pageNumber, request.pageSize)
            SQueryResponse(pageInfo)
        } catch (e: Exception) {
            e.printStackTrace()
            SQueryResponse(SResponseType.failure, e.message!!)
        }
    } // Function pageQuery()

    /**
     * 根据dataRuleType,dataRuleContent获取单位Map
     *
     * @param       dataRuleType
     * @param       dataRuleContent
     */
    open fun getUnitMap(dataRuleType: String?, dataRuleContent: String?): ArrayList<String?> {
        val result = ArrayList<String?>()
        try {
            if (dataRuleType != null && dataRuleContent != null && "需自动单位转换" == dataRuleType) {
                val parser = JSONParser(dataRuleContent)
                val array = parser.parseArray()
                for (obj in array) {
                    val contentArray = (obj as HashMap<String, Any>)["content"]
                    for (contentObject in (contentArray as ArrayList<Any>)) {
                        result.add(((contentObject as HashMap<String, String>)["from"]!!).split("-")[1])
                        result.add(contentObject["to"] as String)
                    }
                }
            } else {
                result.add(null)
                result.add(null)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return result
    }

    /**
     * 批量创建
     *
     * @param       request
     * @return      返回创建状态
     */
    open fun create(request: ArrayList<ENTITY>): Boolean {
        val result: Boolean
        result = try {
            for (et in request) {
                et.projectId = getProject()
                baseDao.insert(et)
            }
            true
        } catch (e: Exception) {
            e.printStackTrace()
            false
        }
        return result
    } // Function create()

    /**
     * 查询全部
     *
     * @param       request
     * @return      返回id列表
     */
    open fun allQuery(@RequestBody request: BasicRequest): ArrayList<String> {
        val result = ArrayList<String>()
        try {
            val list = baseDao.select(SFilter.eq("ProjectId", request.projectId!!.replace("Pj", "", true))).exec()
            for (data in list) {
                result.add(data.id!!)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return result
    } // Function allQuery()

} // Class Service
