package com.izouma.dingdong.service.merchant;

import cn.hutool.core.util.ObjectUtil;
import com.izouma.dingdong.config.Constants;
import com.izouma.dingdong.converter.LongArrayConverter;
import com.izouma.dingdong.converter.StringArrayConverter;
import com.izouma.dingdong.domain.backstage.Email;
import com.izouma.dingdong.domain.merchant.*;
import com.izouma.dingdong.dto.AppraisalMerDTO;
import com.izouma.dingdong.enums.ApplyStatus;
import com.izouma.dingdong.exception.BusinessException;
import com.izouma.dingdong.repo.backstage.EmailRepo;
import com.izouma.dingdong.repo.merchant.*;
import com.izouma.dingdong.service.AppraisalService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
@AllArgsConstructor
public class GoodsService {

    private GoodsRepo goodsRepo;
    private MerchantSettingsRepo merchantSettingsRepo;
    private MerchantClassificationRepo merchantClassificationRepo;
    private MerchantClassificationService merchantClassificationService;
    private EmailRepo emailRepo;
    private MerchantRepo merchantRepo;
    private AppraisalService appraisalService;
    private GoodsSpecificationRepo goodsSpecificationRepo;

    /**
     * 添加修改商品
     *
     * @param goods 商品
     * @return 商品
     */
    public Goods save(Goods goods) {
        if (ObjectUtil.isNull(goods.getMerchantId())) {
            throw new BusinessException("缺少商家");
        }
        MerchantSettings merchantSettings = merchantSettingsRepo.findByMerchantId(goods.getMerchantId()).orElseThrow(new BusinessException("商家不存在"));
        if (ObjectUtil.isNull(goods.getInventory()) || goods.getInventory() < 1) {
            throw new BusinessException("商品供应数量不足");
        }
        if (BigDecimal.ZERO.compareTo(goods.getAmount()) >= 0) {
            throw new BusinessException("价格不得小于等于0");
        }

        if (ObjectUtil.isNull(goods.getDiscountAmount())) {
            goods.setDiscountAmount(goods.getAmount());
        }

        if (BigDecimal.ZERO.compareTo(goods.getDiscountAmount()) >= 0) {
            throw new BusinessException("折扣价不得小于等于0");
        }

        int i = goods.getAmount().compareTo(goods.getDiscountAmount());
        if (i < 0) {
            throw new BusinessException("折扣价不得大于原价");
        }

        if (goods.getStartTime().isBefore(merchantSettings.getStartTime()) || goods.getEndTime().isAfter(merchantSettings.getEndTime())) {
            throw new BusinessException("商品销售时间不得早于/晚于营业时间");
        }

/*        if (containsWeek(goods.getWeek(), merchantSettings.getWeek())) {
            throw new BusinessException("商品销售日期不在营业日期内");
        }*/

        if (goods.getId() == null) {
            goods.setLikes(0);
            goods.setBad(0);
            goods.setTotalSales(0);
            goods.setTakeOff(false);
            goods.setSignboard(false);
            goods.setEnabled(true);
            //审核
            goods.setIsPass(false);
            goods.setStatus(ApplyStatus.PENDING);
        }

        MerchantClassification classification = merchantClassificationRepo.findByMerchantIdAndName(goods.getMerchantId(), Constants.CLASSIFICATION_NAME2);

        //折扣价不参与满减
        if (i == 0) {
            goods.setIsFullReduction(true);

            //移除折扣商品
            if (goods.getId() != null) {
                LongArrayConverter converter = new LongArrayConverter();
                String goodsIds = classification.getGoodsIds();
                List<Long> list = converter.convertToEntityAttribute(goodsIds);
                list.remove(goods.getId());
            }

        } else {
            goods.setIsFullReduction(false);
        }


        goods = goodsRepo.save(goods);

        if (i > 0) {
            //如果有折扣价，自动加入折扣分类
            //MerchantClassification classification = merchantClassificationRepo.findByMerchantIdAndName(goods.getMerchantId(), Constants.CLASSIFICATION_NAME2);
            if (!classification.getIsShow() || ObjectUtil.isNull(classification.getIsShow())) {
                classification.setIsShow(true);
                merchantClassificationRepo.save(classification);
            }
            merchantClassificationService.saveOneGoods(classification.getId(), goods.getId());
        }

        return goods;
    }


    /**
     * 购买时销量是否充足
     *
     * @param goodsId 商品ID
     * @param num     商品数量
     * @return 商品
     */
    public Goods buy(Long goodsId, Integer num) {
        Goods goods = goodsRepo.findById(goodsId).orElseThrow(new BusinessException("无商品"));

        //库存
        Integer inventory = goods.getInventory();
        if (inventory <= 0) {
            throw new BusinessException("已售馨");
        }
        if (inventory - num < 0) {
            throw new BusinessException("库存不足");
        }
        return goods;
    }


    /**
     * 商品上下架
     *
     * @param goodsId 商品ID
     */
    public void take(Long goodsId) {
        Goods goods = goodsRepo.findById(goodsId).orElseThrow(new BusinessException("无商品"));
        Boolean takeOff = goods.getTakeOff();
        if (takeOff) {
            goods.setTakeOff(false);
        } else {
            goods.setTakeOff(true);
        }
        goodsRepo.save(goods);
    }

    /**
     * 审核
     *
     * @param goodsId 商品ID
     * @param pass    是否通过
     */
    public Goods audit(Long goodsId, Boolean pass, String reason) {
        Goods goods = goodsRepo.findById(goodsId).orElseThrow(new BusinessException("无商品"));

        Long userId = merchantRepo.findUserIdById(goods.getMerchantId());

        Email email;

        if (pass) {
            goods.setIsPass(true);
            goods.setStatus(ApplyStatus.PASS);
            //发送邮件
            email = Email.builder()
                    .sendTime(LocalDate.now())
                    .title("提交商品审核通过")
                    .content(goods.getName() + "：恭喜你所提交的商品已审核通过！")
                    .receiveUserId(userId)
                    .build();

        } else {
            goods.setIsPass(false);
            goods.setStatus(ApplyStatus.DENY);
            //发送邮件
            email = Email.builder()
                    .sendTime(LocalDate.now())
                    .title("提交商品审核未通过")
                    .content(goods.getName() + "：" + reason)
                    .receiveUserId(userId)
                    .build();
        }

        emailRepo.save(email);
        return goodsRepo.save(goods);
    }


    /*
       周几
    */
    public Boolean containsWeek(String goodsWeek, String merWeek) {

        List<String> merWeeks = new StringArrayConverter().convertToEntityAttribute(merWeek);
        List<String> goodsWeeks = new StringArrayConverter().convertToEntityAttribute(goodsWeek);

        if (merWeeks.contains("EVERY")) {
            return true;
        }

        for (String g : goodsWeeks) {
            if (!merWeeks.contains(g)) {
                return false;
            }
        }
        return true;

    }

    /*
    显示商品所有信息
     */
    public Map<String,Object> goodsAllInfo(Long goodsId){
        HashMap<String, Object> map = new HashMap<>();
        Goods goods = goodsRepo.findById(goodsId).orElseThrow(new BusinessException("无记录"));
        map.put("goods",goods);

        List<AppraisalMerDTO> appraisals = appraisalService.goodsAppraisals(goodsId);
        map.put("appraisal",appraisals);

        List<GoodsSpecification> specifications = goodsSpecificationRepo.findAllByGoodsId(goodsId);
        map.put("specification",specifications);

        return map;
    }
}
