/*
*  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.dto.shop.TbMerchantRegisterDto;
import cn.ysk.cashier.dto.shop.TbMerchantRegisterQueryCriteria;
import cn.ysk.cashier.exception.BadRequestException;
import cn.ysk.cashier.mapper.shop.TbMerchantRegisterMapper;
import cn.ysk.cashier.pojo.shop.TbMerchantRegister;
import cn.ysk.cashier.repository.shop.TbMerchantRegisterRepository;
import cn.ysk.cashier.service.shop.TbMerchantRegisterService;
import cn.ysk.cashier.utils.ValidationUtil;
import cn.ysk.cashier.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
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.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

/**
* @website https://eladmin.vip
* @description 服务实现
* @author lyf
* @date 2024-02-23
**/
@Service
@RequiredArgsConstructor
public class TbMerchantRegisterServiceImpl implements TbMerchantRegisterService {

    private final TbMerchantRegisterRepository tbMerchantRegisterRepository;
    private final TbMerchantRegisterMapper tbMerchantRegisterMapper;

    @Override
    public Map<String,Object> queryAll(TbMerchantRegisterQueryCriteria criteria){
        Sort sort = Sort.by(Sort.Direction.DESC, "id");
        Pageable pageable = PageRequest.of(criteria.getPage(), criteria.getSize(), sort);


        Page<TbMerchantRegister> page = tbMerchantRegisterRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        for (TbMerchantRegister data : page.getContent()) {
            data.setName(data.getName() == null?"":data.getName());
            data.setTelephone(data.getTelephone() == null?"": data.getTelephone());
            data.setType(data.getType() == null?"": data.getType());
            data.setProxyId(data.getProxyId() == null?"":data.getProxyId());
        }

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

//    @Override
//    public List<TbMerchantRegisterDto> queryAll(TbMerchantRegisterQueryCriteria criteria){
//        return tbMerchantRegisterMapper.toDto(tbMerchantRegisterRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
//    }

    @Override
    @Transactional
    public TbMerchantRegisterDto findById(Integer id) {
        TbMerchantRegister tbMerchantRegister = tbMerchantRegisterRepository.findById(id).orElseGet(TbMerchantRegister::new);
        ValidationUtil.isNull(tbMerchantRegister.getId(),"TbMerchantRegister","id",id);
        return tbMerchantRegisterMapper.toDto(tbMerchantRegister);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public TbMerchantRegisterDto create(TbMerchantRegisterDto resources) {
        if (resources.getNumber()>10){
            throw new BadRequestException("每次最多生成10条激活码");
        }
        for (int i = 0; i < resources.getNumber(); i++) {
            TbMerchantRegister tbMerchantRegister = new TbMerchantRegister();
            tbMerchantRegister.setRegisterCode(UUID.randomUUID().toString().replaceAll("-", ""));
            tbMerchantRegister.setStatus(0);
            tbMerchantRegister.setCreatedAt(Instant.now().toEpochMilli());
            tbMerchantRegister.setUpdatedAt(Instant.now().toEpochMilli());
            tbMerchantRegister.setPeriodYear(resources.getPeriodYear());
            tbMerchantRegisterRepository.save(tbMerchantRegister);
        }

        return tbMerchantRegisterMapper.toDto(new TbMerchantRegister());
    }

    public static void main(String[] args) {
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        System.out.println(uuid);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(TbMerchantRegister resources) {
        TbMerchantRegister tbMerchantRegister = tbMerchantRegisterRepository.findById(resources.getId()).orElseGet(TbMerchantRegister::new);
        ValidationUtil.isNull( tbMerchantRegister.getId(),"TbMerchantRegister","id",resources.getId());
        tbMerchantRegister.copy(resources);
        tbMerchantRegisterRepository.save(tbMerchantRegister);
    }

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

    @Override
    public void download(List<TbMerchantRegisterDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (TbMerchantRegisterDto tbMerchantRegister : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("激活码", tbMerchantRegister.getRegisterCode());
            map.put("授权token", tbMerchantRegister.getAppCode());
            map.put(" telephone",  tbMerchantRegister.getTelephone());
            map.put(" merchantId",  tbMerchantRegister.getMerchantId());
            map.put("店铺id", tbMerchantRegister.getShopId());
            map.put("版本类型", tbMerchantRegister.getType());
            map.put("激活码金额", tbMerchantRegister.getAmount());
            map.put("激活时长（月）", tbMerchantRegister.getPeriodYear());
            map.put(" name",  tbMerchantRegister.getName());
            map.put(" address",  tbMerchantRegister.getAddress());
            map.put(" logo",  tbMerchantRegister.getLogo());
            map.put(" industry",  tbMerchantRegister.getIndustry());
            map.put(" industryName",  tbMerchantRegister.getIndustryName());
            map.put("状态0未使用1已使用", tbMerchantRegister.getStatus());
            map.put(" limitShopNumber",  tbMerchantRegister.getLimitShopNumber());
            map.put(" sourcePath",  tbMerchantRegister.getSourcePath());
            map.put("创建时间", tbMerchantRegister.getCreatedAt());
            map.put(" updatedAt",  tbMerchantRegister.getUpdatedAt());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}