package com.cim.idm.service.Impl;

import com.alibaba.fastjson.JSON;
import com.cim.idm.constants.storage.StorageRulesEnums;
import com.cim.idm.dao.WareHouseDao;
import com.cim.idm.exception.GlobalException;
import com.cim.idm.model.dto.PageDto;
import com.cim.idm.model.dto.WareHouseEditDto;
import com.cim.idm.model.dto.storage.*;
import com.cim.idm.model.po.storage.StorageSpec;
import com.cim.idm.service.IWareHouseService;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.page.PageMethod;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
public class WareHouseServiceImpl implements IWareHouseService {

    @Resource
    private WareHouseDao wareHouseDao;


    @Override
    @Transactional
    public int edit(WareHouseEditDto dto) {
        return wareHouseDao.edit(dto);
    }

    @Override
    public PageInfo<StorageSpec> page(PageDto dto) {
        PageMethod.startPage(dto.getPageNum(), dto.getPageSize());
        StoragePageDto storagePageDto = JSON.toJavaObject(dto.getParams(), StoragePageDto.class);
        return new PageInfo<>(wareHouseDao.page(storagePageDto));
    }

    @Override
    public StorageSpec get(String siteName, String storageName) {
        return wareHouseDao.get(siteName, storageName);
    }

    @Override
    @Transactional
    public int add(StorageAddDto storageAddDto) {
        return wareHouseDao.add(storageAddDto);
    }

    @Override
    @Transactional
    public int editStorage(StorageEditDto storageEditDto) {
        return wareHouseDao.editStorage(storageEditDto);
    }

    @Override
    @Transactional
    public int delStorage(StorageDelDto storageDelDto) {
        return wareHouseDao.delStorage(storageDelDto);
    }

    @Override
    public List<StorageSpec> search(StorageSearchDto storageSearchDto) {
        List<String> prefix = StorageRulesEnums.getPrefix(storageSearchDto.getOrgNo());
        if (prefix.isEmpty()) {
            throw new GlobalException("当前组织无法查询数据");
        }
        return wareHouseDao.search(storageSearchDto.getStorageName(), prefix);
    }

    @Override
    public StorageSpec getLocation(String erpLocation) {
        return wareHouseDao.getLocation(erpLocation);
    }
}
