/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package cn.ysk.cashier.service.impl.shopimpl;

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

import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;

/**
* @website https://eladmin.vip
* @description 服务实现
* @author lyf
* @date 2024-01-02
**/
@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) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),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);
    }
}