package cn.ysk.cashier.service.impl.shopimpl;

import cn.ysk.cashier.dto.shop.TbShopUnitDto;
import cn.ysk.cashier.dto.shop.TbShopUnitQueryCriteria;
import cn.ysk.cashier.exception.NewBadRequestException;
import cn.ysk.cashier.mapper.shop.TbShopUnitMapper;
import cn.ysk.cashier.pojo.shop.TbShopUnit;
import cn.ysk.cashier.repository.shop.TbShopUnitRepository;
import cn.ysk.cashier.service.shop.TbShopUnitService;
import cn.ysk.cashier.utils.FileUtil;
import cn.ysk.cashier.utils.PageUtil;
import cn.ysk.cashier.utils.QueryHelp;
import cn.ysk.cashier.utils.ValidationUtil;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.Predicate;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.Instant;
import java.util.*;

@Service
@RequiredArgsConstructor
public class TbShopUnitServiceImpl implements TbShopUnitService {

    private final TbShopUnitRepository tbShopUnitRepository;
    private final TbShopUnitMapper tbShopUnitMapper;

    @Override
    public Map<String, Object> queryAll(TbShopUnitQueryCriteria criteria, Pageable pageable) {
        Page<TbShopUnit> page = tbShopUnitRepository.findAll((root, criteriaQuery, criteriaBuilder) -> {
            Predicate predicate = QueryHelp.getPredicate(root, null, criteriaBuilder);

//            predicate = criteriaBuilder.and(predicate, criteriaBuilder.in(root.get("shopId")).value(criteria.getShopId()).value("1"));
            predicate = criteriaBuilder.and(predicate, criteriaBuilder.or(
                    criteriaBuilder.equal(root.get("shopId"), criteria.getShopId()),
                    criteriaBuilder.equal(root.get("shopId"), "1")));

            if(StringUtils.isNotBlank(criteria.getName())){
                predicate = criteriaBuilder.and(predicate, criteriaBuilder.like(root.get("name"), criteria.getName()));
            }
            return predicate;
        }, pageable);
        return PageUtil.toPage(page.map(tbShopUnitMapper::toDto));
    }

    @Override
    public List<TbShopUnitDto> queryAll(TbShopUnitQueryCriteria criteria){
        return tbShopUnitMapper.toDto(tbShopUnitRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public TbShopUnitDto findById(Integer id) {
        TbShopUnit tbShopUnit = tbShopUnitRepository.findById(id).orElseGet(TbShopUnit::new);
        ValidationUtil.isNull(tbShopUnit.getId(),"TbShopUnit","id",id);
        return tbShopUnitMapper.toDto(tbShopUnit);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public TbShopUnitDto create(TbShopUnit resources){

        TbShopUnit name = tbShopUnitRepository.findName(resources.getName(), resources.getShopId());
        if (name != null){
            throw new NewBadRequestException(HttpStatus.OK,"单位名称重复");
        }
        resources.setDecimalsDigits(0);
        resources.setUnitType("number");
        resources.setIsSystem(0);
        resources.setStatus(1);
        resources.setCreatedAt(Instant.now().toEpochMilli());
        resources.setUpdatedAt(Instant.now().toEpochMilli());
        return tbShopUnitMapper.toDto(tbShopUnitRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(TbShopUnit resources) {
        TbShopUnit tbShopUnit = tbShopUnitRepository.findById(resources.getId()).orElseGet(TbShopUnit::new);
        TbShopUnit name = tbShopUnitRepository.findName(resources.getName(), resources.getShopId());
        if (name != null){
            throw new NewBadRequestException(HttpStatus.OK,"单位名称重复");
        }
        ValidationUtil.isNull( tbShopUnit.getId(),"TbShopUnit","id",resources.getId());
        tbShopUnit.copy(resources);
        tbShopUnitRepository.save(tbShopUnit);
    }

    @Override
    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            tbShopUnitRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<TbShopUnitDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (TbShopUnitDto tbShopUnit : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("单位名称", tbShopUnit.getName());
            map.put("小数位（个数大于0，表示小数据精度位数）", tbShopUnit.getDecimalsDigits());
            map.put("单位类型(weight代表重量，小数单位，为number代表个数)", tbShopUnit.getUnitType());
            map.put("0后台添加   -1系统默认 （公斤、瓶）", tbShopUnit.getIsSystem());
            map.put("预留字段1-正常", tbShopUnit.getStatus());
            map.put(" merchantId",  tbShopUnit.getMerchantId());
            map.put("店铺Id", tbShopUnit.getShopId());
            map.put(" createdAt",  tbShopUnit.getCreatedAt());
            map.put(" updatedAt",  tbShopUnit.getUpdatedAt());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}