package com.huigou.topsun.sap.permit.application.impl;

import com.huigou.cache.DictUtil;
import com.huigou.data.query.model.QueryDescriptor;
import com.huigou.data.query.model.QueryModel;


import com.huigou.topsun.sap.permit.application.SapPermitItemApplication;
import com.huigou.topsun.sap.permit.domain.SapPermitItem;
import com.huigou.topsun.sap.permit.domain.query.SapPermitQueryRequest;
import com.huigou.topsun.sap.permit.repository.SapPermitItemRepository;
import com.huigou.uasp.bmp.common.application.BaseApplication;
import com.huigou.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Auther: LXH
 * @Date: 2024/03/26/10:16
 * @Description:
 */
@Service("sapPermitApplicationItemApplication")
public class SapPermitItemApplicationImpl extends BaseApplication implements SapPermitItemApplication {
    @Autowired
    private SapPermitItemRepository sapPermitItemRepository;
    @Override
    public void saveSapPermitItems(String sapPermitId, List<SapPermitItem> items) {
        for (SapPermitItem item : items) {
            item.setSapPermitId(sapPermitId);
            sapPermitItemRepository.save(item);
        }
    }

    @Override
    public Map<String, Object> querySapPermitItems(SapPermitQueryRequest queryRequest) {
        Map<String, Object> map = new HashMap<>();
        if (StringUtil.isNotBlank(queryRequest.getSapPermitId())){
            QueryDescriptor queryDescriptor = this.sqlExecutorDao.getQuery(QUERY_XML_FILE_PATH, "sapPermitItems");

            QueryModel queryModel = this.sqlExecutorDao.getQueryModel(queryDescriptor, queryRequest);
            if (queryRequest.getSapPermitId() != null) {
                queryModel.addCriteria(" and t.sap_permit_id =:sapPermitId");
                queryModel.putParam("sapPermitId", queryRequest.getSapPermitId());
            }
            queryModel.putDictionary("unit", DictUtil.getDictionary("sapPermitUnit"));
            map = this.sqlExecutorDao.executeSlicedQuery(queryModel);
        }
        return map;
    }

    @Override
    public void deleteByIds(List<String> ids) {
        ids.forEach(id->{
            sapPermitItemRepository.delete(id);
        });
    }

    @Override
    public List<SapPermitItem> findBySapPermitId(String sapPermitId) {
        return sapPermitItemRepository.findBySapPermitId(sapPermitId);
    }
}
