package com.huigou.bpm.webservice.common;

import com.huigou.bpm.webservice.call.domain.model.SapWebServiceConfig;
import com.huigou.data.domain.model.CommonDomainConstants;
import com.huigou.data.domain.query.QueryAbstractRequest;
import com.huigou.data.query.model.QueryDescriptor;
import com.huigou.exception.ApplicationException;
import com.huigou.uasp.bmp.common.application.BaseApplication;
import com.huigou.util.StringUtil;
import org.springframework.util.Assert;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CommonApplicationImpl<T> extends BaseApplication implements CommonApplication<T>{


    public void saveBean(T t) {
        this.generalRepository.save(t);
    }

    public void updateBean(T t) {
        this.generalRepository.save(t);
    }

    public Map<String, Object> slicedQueryBean(QueryAbstractRequest request) {
        Map<String,Object> staticMap = getStaticFields(request);
        String queryFilePath = staticMap.get("QUERY_XML_FILE_PATH")==null?"":staticMap.get("QUERY_XML_FILE_PATH").toString();
        String queryName = staticMap.get("QUERY_NAME")==null?"":staticMap.get("QUERY_NAME").toString();
        if(StringUtil.isBlank(queryFilePath)){
            throw new ApplicationException(request.getClass().getName()+"未获取到xml文件路径");
        }
        if(StringUtil.isBlank(queryName)){
            throw new ApplicationException(request.getClass().getName()+"未获取到【QUERY_NAME】");
        }
        QueryDescriptor descriptor = this.sqlExecutorDao.getQuery(queryFilePath,queryName);
        return this.sqlExecutorDao.executeQuery(descriptor,request);
    }

    public void deleteBean(Class<T> t,List<String> ids) {
        for (String id:ids) {
            this.generalRepository.delete(t,id);
        }
    }

    public void updateStatus(List<String> ids, Integer status,Class t) {
        checkIdsNotEmpty(ids);
        Assert.notNull(status, String.format(CommonDomainConstants.PARAMETER_NOT_NULL_FORMAT, CommonDomainConstants.STATUS_FIELD_NAME));
        commonDomainService.updateStatus(t,ids,status);
    }

    private Map<String,Object> getStaticFields(Object o){
        Map<String,Object> map = new HashMap<String,Object>();
        Field[] fields = o.getClass().getDeclaredFields();
        for (Field field:fields) {
            if(Modifier.isStatic(field.getModifiers())){
                try {
                    map.put(field.getName(),field.get(o));
                }catch (Exception e){
                    throw new ApplicationException("获取静态变量出错");
                }

            }
        }
        return map;
    }
}
