package {{packageName}}.client.{{lowerCase api.codeName}}.runtime.service;

import lombok.extern.slf4j.Slf4j;
import net.ibizsys.central.r8.service.R8SubSysServiceAPIDERuntime;
import net.ibizsys.central.service.SubSysServiceAPIDERuntimeException;
import net.ibizsys.central.util.EntityDTO;
import net.ibizsys.central.util.IEntityDTO;
import net.ibizsys.central.util.ISearchContextDTO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Sort;

import java.util.Iterator;

/**
 * 提供外部容器启动服务能力
 */
@Slf4j
public class {{api.codeName}}R8SubSysServiceAPIDERuntime extends R8SubSysServiceAPIDERuntime {

    protected IEntityDTO createClientEntity() {
        return new EntityDTO();
    }

    protected IEntityDTO convert2ClientEntity(Object entityDTO) {
        if (entityDTO == null)
            return null;
        IEntityDTO clientEntityDTO = createClientEntity();
        try {
            clientEntityDTO.reload(entityDTO, true);
        } catch (Exception e) {
            throw new SubSysServiceAPIDERuntimeException(this, String.format("调用外部系统接口参数转换发异常:%s", e.getMessage()));
        }
        return clientEntityDTO;
    }

    protected IEntityDTO convert2Entity(Object clientEntityDTO) {
        if (clientEntityDTO == null)
            return null;
        IEntityDTO entityDTO = createClientEntity();
        try {
            entityDTO.reload(clientEntityDTO, true);
        } catch (Exception e) {
            throw new SubSysServiceAPIDERuntimeException(this, String.format("调用外部系统接口参数转换发异常:%s", e.getMessage()));
        }
        return entityDTO;
    }

    protected void convertCondition(ISearchContextDTO dto) {
        dto.any().put("page", dto.getPageable().getPageNumber());
        dto.any().put("size", dto.getPageable().getPageSize());
        if (dto.getPageSort() != null && dto.getPageSort() != Sort.unsorted()) {
            String strSort = "";
            Iterator<Sort.Order> iterator = dto.getPageSort().iterator();
                if (iterator.hasNext()) {
                    Sort.Order order = iterator.next();
                    if (StringUtils.isNotEmpty(strSort)) {
                    strSort += ";";
                }
                strSort += order.getProperty();
                if (order.isAscending()) {
                    strSort += ",asc";
                } else if (order.isDescending()) {
                    strSort += ",desc";
                }
            }
            if (StringUtils.isNotEmpty(strSort)) {
                dto.any().put("sort", strSort);
            }
        }
    }

}