/*
*  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.productimpl;

import cn.ysk.cashier.exception.BadRequestException;
import cn.ysk.cashier.pojo.product.TbProductSpec;
import cn.ysk.cashier.repository.product.TbProductSpecRepository;
import cn.ysk.cashier.service.product.TbProductSpecService;
import cn.ysk.cashier.utils.*;
import cn.ysk.cashier.vo.TbProductSpecVo;
import cn.ysk.cashier.dto.product.SpecDto;
import cn.ysk.cashier.dto.product.TbProductSpecDto;
import cn.ysk.cashier.dto.product.TbProductSpecQueryCriteria;
import lombok.RequiredArgsConstructor;
import cn.ysk.cashier.mapper.product.TbProductSpecMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

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-03
**/
@Service
@RequiredArgsConstructor
public class TbProductSpecServiceImpl implements TbProductSpecService {

    private final TbProductSpecRepository tbProductSpecRepository;
    private final TbProductSpecMapper tbProductSpecMapper;

    @Override
    public Map<String,Object> queryAll(TbProductSpecQueryCriteria criteria, Pageable pageable){

        Page<TbProductSpec> page = tbProductSpecRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        List<TbProductSpecVo> specList = new ArrayList<>();
        for (TbProductSpec spec :page.getContent()) {
            TbProductSpecVo specVo = new TbProductSpecVo();
            specVo.setSpecList(ListUtil.stringChangeList(spec.getSpecList()));
            BeanUtils.copyProperties(spec, specVo);
            specList.add(specVo);
        }

        return PageUtil.toPage(specList, page.getTotalElements());
    }

    @Override
    public List<TbProductSpecDto> queryAll(TbProductSpecQueryCriteria criteria){
        return tbProductSpecMapper.toDto(tbProductSpecRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public TbProductSpecDto findById(Integer id) {
        TbProductSpec tbProductSpec = tbProductSpecRepository.findById(id).orElseGet(TbProductSpec::new);
        ValidationUtil.isNull(tbProductSpec.getId(),"TbProductSpec","id",id);
        return tbProductSpecMapper.toDto(tbProductSpec);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public TbProductSpecDto create(SpecDto specDto) {
        TbProductSpec allByName = tbProductSpecRepository.findAllByName(specDto.getShopId(), specDto.getName());
        if (allByName != null){
            throw new BadRequestException("规格名称重复");
        }
        TbProductSpec tbProductSpec = new TbProductSpec();
        tbProductSpec.setName(specDto.getName());
        tbProductSpec.setSpecList(specDto.getSpecList().toString().replace(" ", ""));
        tbProductSpec.setShopId(specDto.getShopId());
        tbProductSpec.setCreatedAt(Instant.now().toEpochMilli());
        tbProductSpec.setUpdatedAt(Instant.now().toEpochMilli());
        return tbProductSpecMapper.toDto(tbProductSpecRepository.save(tbProductSpec));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(TbProductSpec resources) {
        TbProductSpec tbProductSpec = tbProductSpecRepository.findById(resources.getId()).orElseGet(TbProductSpec::new);
//        TbProductSpec allByName = tbProductSpecRepository.findAllByName(resources.getShopId(), resources.getName());
//        if (allByName != null){
//            throw new BadRequestException("规格名称重复");
//        }
        ValidationUtil.isNull(tbProductSpec.getId(),"TbProductSpec","id",resources.getId());
        tbProductSpec.copy(resources);
        tbProductSpecRepository.save(tbProductSpec);
    }

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

    @Override
    public void download(List<TbProductSpecDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (TbProductSpecDto tbProductSpec : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put(" shopId",  tbProductSpec.getShopId());
            map.put("商品属性名称", tbProductSpec.getName());
            map.put("规格属性", tbProductSpec.getSpecTag());
            map.put("属性介绍", tbProductSpec.getSpecTagDetail());
            map.put(" specList",  tbProductSpec.getSpecList());
            map.put("排序", tbProductSpec.getSort());
            map.put(" createdAt",  tbProductSpec.getCreatedAt());
            map.put(" updatedAt",  tbProductSpec.getUpdatedAt());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}