/*
*  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.hutool.core.bean.BeanUtil;
import cn.ysk.cashier.exception.BadRequestException;
import cn.ysk.cashier.pojo.product.TbProduct;
import cn.ysk.cashier.pojo.shop.TbMerchantCoupon;
import cn.ysk.cashier.repository.product.TbProductRepository;
import cn.ysk.cashier.utils.ValidationUtil;
import cn.ysk.cashier.utils.FileUtil;
import cn.ysk.cashier.vo.CouponVO;
import lombok.RequiredArgsConstructor;
import cn.ysk.cashier.repository.shop.TbMerchantCouponRepository;
import cn.ysk.cashier.service.shop.TbMerchantCouponService;
import cn.ysk.cashier.dto.shop.TbMerchantCouponDto;
import cn.ysk.cashier.dto.shop.TbMerchantCouponQueryCriteria;
import cn.ysk.cashier.mapper.shop.TbMerchantCouponMapper;
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 cn.ysk.cashier.utils.PageUtil;
import cn.ysk.cashier.utils.QueryHelp;

import java.sql.Timestamp;
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-03-20
**/
@Service
@RequiredArgsConstructor
public class TbMerchantCouponServiceImpl implements TbMerchantCouponService {

    private final TbMerchantCouponRepository tbMerchantCouponRepository;
    private final TbMerchantCouponMapper tbMerchantCouponMapper;
    private final TbProductRepository tbProductRepository;

    @Override
    public Map<String,Object> queryAll(TbMerchantCouponQueryCriteria criteria, Pageable pageable){
        Page<TbMerchantCoupon> page = tbMerchantCouponRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        List<CouponVO> objects = new ArrayList<>();
        for (TbMerchantCoupon o :page.getContent()) {
            CouponVO couponVO = new CouponVO();
            BeanUtils.copyProperties(o,couponVO);
            if (!o.getRelationIds().isEmpty()) {
                List<Integer> integers = new ArrayList<>();
                integers.add(Integer.valueOf(o.getRelationIds()));
                List<TbProduct> byIds = tbProductRepository.findByIds(integers);
                couponVO.setName(byIds.get(0).getName());
                couponVO.setCoverImg(byIds.get(0).getCoverImg());
            }
            objects.add(couponVO);
        }
        HashMap<String, Object> couponvoMap = new HashMap<>();
        couponvoMap.put("content", objects);
        couponvoMap.put("totalElements", page.getTotalElements());
        return couponvoMap;
//        return PageUtil.toPage(page.map(tbMerchantCouponMapper::toDto));
    }
    @Override
    public List<TbMerchantCouponDto> queryAll(TbMerchantCouponQueryCriteria criteria){
        return tbMerchantCouponMapper.toDto(tbMerchantCouponRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public TbMerchantCouponDto findById(Integer id) {
        TbMerchantCoupon tbMerchantCoupon = tbMerchantCouponRepository.findById(id).orElseGet(TbMerchantCoupon::new);
        ValidationUtil.isNull(tbMerchantCoupon.getId(),"TbMerchantCoupon","id",id);
        return tbMerchantCouponMapper.toDto(tbMerchantCoupon);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public TbMerchantCoupon create(TbMerchantCoupon resources) {
        resources.setCreatedAt(Instant.now().toEpochMilli());
        resources.setUpdatedAt(Instant.now().toEpochMilli());
        if (resources.getEffectType() == 1){
            if (resources.getToTime() == null && resources.getFromTime() == null){
                throw new BadRequestException("开始时间结束时间为空");
            }
        }else {
            resources.setToTime(null);
            resources.setFromTime(null);
        }

        if ("product".equals(resources.getClassType())){
            if (resources.getRelationIds() == null){
                throw new BadRequestException("商品不能为空");
            }
        }
        if (resources.getNumber() == 0){
            resources.setLeftNumber(0);
        }else {
            resources.setLeftNumber(resources.getNumber());
        }
        return tbMerchantCouponRepository.save(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(TbMerchantCoupon resources) {
        TbMerchantCoupon tbMerchantCoupon = tbMerchantCouponRepository.findById(resources.getId()).orElseGet(TbMerchantCoupon::new);
        ValidationUtil.isNull( tbMerchantCoupon.getId(),"TbMerchantCoupon","id",resources.getId());
        tbMerchantCoupon.copy(resources);
        tbMerchantCouponRepository.save(tbMerchantCoupon);
    }

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

    @Override
    public void download(List<TbMerchantCouponDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (TbMerchantCouponDto tbMerchantCoupon : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("状态0-关闭 1 正常", tbMerchantCoupon.getStatus());
            map.put(" 优惠券名称", tbMerchantCoupon.getTitle());
            map.put(" templateId",  tbMerchantCoupon.getTemplateId());
            map.put(" shopId",  tbMerchantCoupon.getShopId());
            map.put(" shopSnap",  tbMerchantCoupon.getShopSnap());
            map.put("开始时间", tbMerchantCoupon.getFromTime());
            map.put("到期时间", tbMerchantCoupon.getToTime());
            map.put("限领数量", tbMerchantCoupon.getLimitNumber());
            map.put("发放数量", tbMerchantCoupon.getNumber());
            map.put("剩余数量", tbMerchantCoupon.getLeftNumber());
            map.put("优惠金额", tbMerchantCoupon.getAmount());
            map.put("订单满赠金额", tbMerchantCoupon.getLimitAmount());
            map.put("是否显示0-不显示 1显示", tbMerchantCoupon.getIsShow());
            map.put("图标", tbMerchantCoupon.getPic());
            map.put("0-满减  1-折扣", tbMerchantCoupon.getType());
            map.put("折扣 ，一位小数", tbMerchantCoupon.getRatio());
            map.put("最大折扣金额", tbMerchantCoupon.getMaxRatioAmount());
            map.put("优惠券途径，首充|分销", tbMerchantCoupon.getTrack());
            map.put("品类product 商品券 ---cateogry 品类券common -通 用券", tbMerchantCoupon.getClassType());
            map.put("有效期类型：0-toTime有效  1-effectDays有效", tbMerchantCoupon.getEffectType());
            map.put("领取之日有效天数", tbMerchantCoupon.getEffectDays());
            map.put("关联商品Id", tbMerchantCoupon.getRelationIds());
            map.put(" relationList",  tbMerchantCoupon.getRelationList());
            map.put("发放人", tbMerchantCoupon.getEditor());
            map.put("说明", tbMerchantCoupon.getNote());
            map.put(" createdAt",  tbMerchantCoupon.getCreatedAt());
            map.put(" updatedAt",  tbMerchantCoupon.getUpdatedAt());
            map.put("支持堂食", tbMerchantCoupon.getFurnishMeal());
            map.put("支持配送", tbMerchantCoupon.getFurnishExpress());
            map.put("支持自提", tbMerchantCoupon.getFurnishDraw());
            map.put("支持虚拟", tbMerchantCoupon.getFurnishVir());
            map.put(" disableDistribute",  tbMerchantCoupon.getDisableDistribute());
            map.put("商户Id", tbMerchantCoupon.getMerchantId());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}