/*
 * *********************************************************************************************************************
 *
 *          !!
 *        .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.messagecenter.services.base

import com.alibaba.druid.support.json.JSONParser
import com.persagy.database.SAbstractDao
import com.persagy.database.SFilter
import com.persagy.server.messagecenter.models.entities.base.BaseInfo
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, null, 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
