package com.izouma.dingdong.service.merchant;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.izouma.dingdong.config.Constants;
import com.izouma.dingdong.domain.User;
import com.izouma.dingdong.domain.merchant.Merchant;
import com.izouma.dingdong.domain.merchant.MerchantClassification;
import com.izouma.dingdong.domain.merchant.MerchantSettings;
import com.izouma.dingdong.dto.MerchantDTO;
import com.izouma.dingdong.enums.ApplyStatus;
import com.izouma.dingdong.exception.BusinessException;
import com.izouma.dingdong.repo.UserRepo;
import com.izouma.dingdong.repo.merchant.MerchantClassificationRepo;
import com.izouma.dingdong.repo.merchant.MerchantRepo;
import com.izouma.dingdong.repo.merchant.MerchantSettingsRepo;
import com.izouma.dingdong.utils.ObjUtils;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

@Service
@AllArgsConstructor
public class MerchantService {

    private MerchantRepo merchantRepo;

    private MerchantSettingsRepo merchantSettingsRepo;

    private UserRepo userRepo;

    private MerchantClassificationRepo merchantClassificationRepo;

    /*
    商户注册申请
     */
    public MerchantDTO registerApply(MerchantDTO merchantDTO) {
        //注册商家用户
        // User user = userService.register(merchantDTO.getPhone(), merchantDTO.getPassword());
        User user = userRepo.findByPhone(merchantDTO.getPhone());


        //查看商家是否已存在
        Merchant merchant1 = merchantRepo.findByPhone(merchantDTO.getPhone());

        if (ObjectUtil.isNotNull(merchant1)) {
            if (merchant1.getStatus().equals(ApplyStatus.PENDING)) {
                return merchantDTO;
                //throw new BusinessException("申请中");
            }
            if (merchant1.getStatus().equals(ApplyStatus.PASS)) {
                return merchantDTO;
                //throw new BusinessException("已申请");
            }
        }

//        user.setPassword(new BCryptPasswordEncoder().encode(merchantDTO.getPassword()));
//        if (ObjectUtil.isNotNull(merchantDTO.getLogo())) {
//            user.setAvatar(merchantDTO.getLogo());
//        }
//        if (ObjectUtil.isNotNull(merchantDTO.getShowName())) {
//            user.setNickname(merchantDTO.getShowName());
//        }
//    user.setIdentity(Identity.MERCHANT);
//        userRepo.save(user);

        //新建商家
        Merchant merchant = new Merchant();
        MerchantSettings merchantSettings = new MerchantSettings();

        //dto转merchant实体
        BeanUtil.copyProperties(merchantDTO, merchant);
        merchant.setUserId(user.getId());
        merchant.setStatus(ApplyStatus.PENDING);

        merchant.setEnabled(true);
        merchant.setBlacklist(false);
        merchant = merchantRepo.save(merchant);

        //dto转merchantSettings实体
        BeanUtil.copyProperties(merchantDTO, merchantSettings);
        merchantSettings.setMerchantId(merchant.getId());
        //默认不自动接单
        merchantSettings.setAutomaticOrder(false);

        //新用户和首单金额未设置时
/*        if (ObjectUtil.isNull(merchantDTO.getNewUser())) {
            merchantSettings.setNewUser(BigDecimal.ZERO);
        }*/
        if (ObjectUtil.isNull(merchantDTO.getFirstOrder())) {
            merchantSettings.setFirstOrder(BigDecimal.ZERO);
        }

        merchantSettings.setEnabled(true);
        merchantSettings.setIsOpening(true);

        merchantSettingsRepo.save(merchantSettings);


        //新建 系统预制分类：好评热销/折扣/点单必读
        merchantClassificationRepo.save(MerchantClassification.builder()
                .merchantId(merchant.getId())
                .name(Constants.CLASSIFICATION_NAME)
                .sort(1)
                .isOpen(false)
                .isShow(true)
                .build());
        merchantClassificationRepo.save(MerchantClassification.builder()
                .merchantId(merchant.getId())
                .name(Constants.CLASSIFICATION_NAME2)
                .sort(2)
                .isOpen(true)
                .isShow(false)
                .build());
       merchantClassificationRepo.save(MerchantClassification.builder()
                .merchantId(merchant.getId())
                .name(Constants.CLASSIFICATION_NAME3)
                .sort(3)
                .isOpen(true)
                .isShow(false)
                .build());

        return merchantDTO;
    }

    /**
     * 商户修改信息
     *
     * @param merchantDTO 修改的信息
     * @return 修改
     */
    public MerchantDTO change(MerchantDTO merchantDTO) {
        if (merchantDTO.getMid() == null) {
            return registerApply(merchantDTO);
        }
        Merchant merchant = merchantRepo.findById(merchantDTO.getMid()).orElseThrow(new BusinessException("商户不存在"));
        MerchantSettings merchantSettings = merchantSettingsRepo.findByMerchantId(merchantDTO.getMid()).orElseThrow(new BusinessException("商户不存在"));

        MerchantDTO dto = new MerchantDTO(merchant, merchantSettings);
        ObjUtils.merge(dto, merchantDTO);

        User user = merchant.getUser();
        user.setAvatar(dto.getLogo());
        user.setPhone(dto.getPhone());
        user.setNickname(dto.getShowName());
        userRepo.save(user);

        //dto转实体
        BeanUtil.copyProperties(dto, merchant);
        BeanUtil.copyProperties(dto, merchantSettings);
        merchantRepo.save(merchant);
        merchantSettingsRepo.save(merchantSettings);

        return dto;
    }

    /**
     * 商家过审
     *
     * @param merchantId 商户ID
     * @param pass       是否过审
     */
    public void audit(Long merchantId, Boolean pass) {
        Merchant merchant = merchantRepo.findById(merchantId).orElseThrow(new BusinessException("商户不存在"));

        if (pass) {
            merchant.setStatus(ApplyStatus.PASS);
            merchant.setIsPass(true);
            merchant.setEstablishTime(LocalDateTime.now());


        } else {
            merchant.setStatus(ApplyStatus.DENY);
            merchant.setIsPass(false);
        }
        merchantRepo.save(merchant);

    }

    /**
     * 显示所有商家信息
     *
     * @param pageable 分页
     * @return 分页列表
     */
    public Page<MerchantDTO> showAll(Pageable pageable) {
        List<MerchantDTO> merchantDTOS = CollUtil.newArrayList();
        List<Merchant> merchants = merchantRepo.findAll();
        for (Merchant merchant : merchants) {
            MerchantSettings merchantSettings = merchantSettingsRepo.findByMerchantId(merchant.getId()).orElseThrow(new BusinessException("商户不存在"));
            merchantDTOS.add(new MerchantDTO(merchant, merchantSettings));
        }
        return new PageImpl<>(merchantDTOS, pageable, merchantDTOS.size());
    }

    /**
     * 显示个人的商户信息
     *
     * @param userId 用户的ID
     * @return 个人的商户信息
     */
    public MerchantDTO my(Long userId) {
        Merchant merchant = merchantRepo.findByUserId(userId).orElseThrow(new BusinessException("商户不存在"));
        MerchantSettings merchantSettings = merchantSettingsRepo.findByMerchantId(merchant.getId()).orElseThrow(new BusinessException("商户不存在"));
        return new MerchantDTO(merchant, merchantSettings);
    }

    /**
     * 用户查找商家
     *
     * @param userId 用户ID
     * @return 商家ID
     */
    public Long findMerchantId(Long userId) {
        Merchant merchant = merchantRepo.findByUserId(userId).orElseThrow(new BusinessException("商户不存在"));
        return merchant.getId();
    }

    /*
    开始/停止营业
     */
    public void closeMer(Long merchantId) {
        MerchantSettings merchant = merchantSettingsRepo.findByMerchantId(merchantId).orElseThrow(new BusinessException("无商户"));
        if (merchant.getIsOpening()) {
            merchant.setIsOpening(false);
        } else {
            merchant.setIsOpening(true);
        }
        merchantSettingsRepo.save(merchant);
    }
    

}
