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

import cn.ysk.cashier.exception.BadRequestException;
import cn.ysk.cashier.enums.PayTypeEnum;
import cn.ysk.cashier.repository.TbShopPayTypeRepository;
import cn.ysk.cashier.dto.TbShopPayTypeDto;
import cn.ysk.cashier.dto.TbShopPayTypeQueryCriteria;
import cn.ysk.cashier.mapper.TbShopPayTypeMapper;
import cn.ysk.cashier.pojo.TbShopPayType;
import cn.ysk.cashier.utils.ValidationUtil;
import cn.ysk.cashier.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import cn.ysk.cashier.service.TbShopPayTypeService;
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 2023-11-03
**/
@Service
@RequiredArgsConstructor
public class TbShopPayTypeServiceImpl implements TbShopPayTypeService {

    private final TbShopPayTypeRepository tbShopPayTypeRepository;
    private final TbShopPayTypeMapper tbShopPayTypeMapper;

    @Override
    public Map<String,Object> queryAll(TbShopPayTypeQueryCriteria criteria, Pageable pageable){
        Page<TbShopPayType> page = tbShopPayTypeRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.getContent(),page.getTotalElements());
    }

    @Override
    public List<TbShopPayTypeDto> queryAll(TbShopPayTypeQueryCriteria criteria){
        return tbShopPayTypeMapper.toDto(tbShopPayTypeRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public TbShopPayTypeDto findById(Integer id) {
        TbShopPayType tbShopPayType = tbShopPayTypeRepository.findById(id).orElseGet(TbShopPayType::new);
        ValidationUtil.isNull(tbShopPayType.getId(),"TbShopPayType","id",id);
        return tbShopPayTypeMapper.toDto(tbShopPayType);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public TbShopPayTypeDto create(TbShopPayType resources) {
        if (resources.getPayName() == null || "".equals(resources.getPayName())){
            throw new BadRequestException("付款方式不能为空");
        }
        if (resources.getIcon() == null || "".equals(resources.getIcon())){
            throw new BadRequestException("支付方式图标不能为空");
        }
        //类型转换
        resources.setIsRefundable(0);
        resources.setIsShowShortcut(1);
        resources.setIsSystem(0);
        resources.setCreatedAt(Instant.now().toEpochMilli());
        resources.setUpdatedAt(Instant.now().toEpochMilli());
        return tbShopPayTypeMapper.toDto(tbShopPayTypeRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(TbShopPayType resources) {
        if (resources.getPayName() == null || "".equals(resources.getPayName())){
            throw new BadRequestException("付款方式不能为空");
        }
        TbShopPayType tbShopPayType = tbShopPayTypeRepository.findById(resources.getId()).orElseGet(TbShopPayType::new);
        //类型转换
        resources.setUpdatedAt(Instant.now().toEpochMilli());
        ValidationUtil.isNull( tbShopPayType.getId(),"TbShopPayType","id",resources.getId());
        tbShopPayType.copy(resources);
        tbShopPayTypeRepository.save(tbShopPayType);
    }

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

    @Override
    public void download(List<TbShopPayTypeDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (TbShopPayTypeDto tbShopPayType : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("支付类型cash,alipay,weixin,deposit,arrears,virtual,member-account", tbShopPayType.getPayType());
            map.put("支付类型名称支付类型名称：现金，支付宝，刷卡deposit，挂单arrears，储值member-account自定义virtual", tbShopPayType.getPayName());
            map.put("是否快捷展示1是0否", tbShopPayType.getIsShowShortcut());
            map.put("店铺id", tbShopPayType.getShopId());
            map.put("0允许退款 1-不允许退款", tbShopPayType.getIsRefundable());
            map.put("是否打开钱箱", tbShopPayType.getIsOpenCashDrawer());
            map.put("0不是 1是 [系统级支付]", tbShopPayType.getIsSystem());
            map.put("0-非虚拟 1虚拟 virtual", tbShopPayType.getIsIdeal());
            map.put("0-不显示1显示", tbShopPayType.getIsDisplay());
            map.put(" createdAt",  tbShopPayType.getCreatedAt());
            map.put(" updatedAt",  tbShopPayType.getUpdatedAt());
            map.put("排序", tbShopPayType.getSorts());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}