package com.izouma.nineth.service;

import com.izouma.nineth.config.GeneralProperties;
import com.izouma.nineth.domain.*;
import com.izouma.nineth.dto.PageQuery;
import com.izouma.nineth.dto.oasis.OasisDistrictCollectionDTO;
import com.izouma.nineth.dto.oasis.OasisDistrictDTO;
import com.izouma.nineth.enums.AssetStatus;
import com.izouma.nineth.enums.CollectionSource;
import com.izouma.nineth.enums.CollectionStatus;
import com.izouma.nineth.enums.CollectionType;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.repo.*;
import com.izouma.nineth.utils.JpaUtils;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@AllArgsConstructor
public class CompanyCollectionService {

    private CompanyCollectionRepo   companyCollectionRepo;
    private CollectionRepo          collectionRepo;
    private UserRepo                userRepo;
    private CollectionPrivilegeRepo collectionPrivilegeRepo;
    private SysConfigService        sysConfigService;
    private AssetRepo               assetRepo;
    private GeneralProperties       generalProperties;
    private ShowroomRepo            showroomRepo;
    private ShowCollectionRepo      showCollectionRepo;
    private OrderRepo               orderRepo;

    public Page<CompanyCollection> all(PageQuery pageQuery) {
        return companyCollectionRepo.findAll(JpaUtils.toSpecification(pageQuery, CompanyCollection.class), JpaUtils
                .toPageRequest(pageQuery));
    }

    public void audit(Long id, CollectionStatus status, String reason) {
        CompanyCollection companyCollection = companyCollectionRepo.findById(id)
                .orElseThrow(new BusinessException("无申请"));


        if (!CollectionStatus.PENDING.equals(companyCollection.getStatus())) {
            throw new BusinessException("已审核");
        }

        companyCollection.setStatus(status);
        companyCollection.setReason(reason);

        if (CollectionStatus.FAIL.equals(status)) {
            //存状态
            companyCollectionRepo.save(companyCollection);
            return;
        }

        CollectionPrivilege privilege = collectionPrivilegeRepo.findByCompanyCollectionId(id);
        if (ObjectUtils.isNotEmpty(privilege)) {
            return;
        }

        Collection collection = new Collection();
        BeanUtils.copyProperties(companyCollection, collection);
        collection.setSource(CollectionSource.COMPANY);
        collection.setType(CollectionType.DEFAULT);
        collection.setStock(companyCollection.getTotal());

        //铸造者/持有者
        Long userId = companyCollection.getUserId();
        User user = userRepo.findById(userId).orElseThrow(new BusinessException("无企业"));
        collection.setMinter(user.getNickname());
        collection.setMinterId(userId);
        collection.setMinterAvatar(user.getAvatar());
        collection.setOwner(user.getNickname());
        collection.setOwnerId(userId);
        collection.setOwnerAvatar(user.getAvatar());

//        Showroom showroom = showroomRepo.findFirstByUserId(userId);
        int royalties = sysConfigService.getInt("royalties");
        int serviceCharge = sysConfigService.getInt("service_charge");
        collection.setRoyalties(royalties);
        collection.setServiceCharge(serviceCharge);
        collection.setId(null);
        collection = collectionRepo.save(collection);

        //企业属性
        collectionPrivilegeRepo.save(CollectionPrivilege.builder()
                .collectionId(collection.getId())
                .companyCollectionId(id)
                .build());

        //存状态
        companyCollectionRepo.save(companyCollection);
    }


    public List<OasisDistrictCollectionDTO> oasisSearch(List<Long> oasisIds) {
        List<OasisDistrictCollectionDTO> oasisDistrictCollectionDTOS = new ArrayList<>();
        List<AssetStatus> assetStatuses = new ArrayList<>();
        assetStatuses.add(AssetStatus.NORMAL);
        assetStatuses.add(AssetStatus.AUCTION_TRADING);
        assetStatuses.add(AssetStatus.GIFTING);
        assetStatuses.add(AssetStatus.TRADING);
        assetStatuses.add(AssetStatus.MINTING);
        assetStatuses.add(AssetStatus.AUCTIONING);
        List<Asset> assets = assetRepo
                .findAllByOasisIdInAndStatusIn(oasisIds, assetStatuses);
        List<CompanyCollection> companyCollections = companyCollectionRepo
                .findAllByOasisIdInAndStatusNot(oasisIds, CollectionStatus.SUCCESS);
        List<CollectionSource> collectionSources = new ArrayList<>();
        collectionSources.add(CollectionSource.COMPANY);
        collectionSources.add(CollectionSource.OFFICIAL);
        List<Collection> officialCollections = collectionRepo
                .findAllByOasisIdInAndSourceInAndStockGreaterThan(oasisIds, collectionSources, 0);

        assets.forEach(asset -> {
            OasisDistrictCollectionDTO oasisDistrictCollectionDTO = new OasisDistrictCollectionDTO();
            oasisDistrictCollectionDTO.setOasisId(asset.getOasisId());
            oasisDistrictCollectionDTO.setCollectionName(asset.getName());
            oasisDistrictCollectionDTO.setOriginPrice(asset.getPrice());
            oasisDistrictCollectionDTO.setSellPrice(asset.getSellPrice());
            oasisDistrictCollectionDTO.setScanOnly(false);
            oasisDistrictCollectionDTO.setOwnerId(asset.getOwnerId());
            oasisDistrictCollectionDTO.setOwnerName(asset.getOwner());
            oasisDistrictCollectionDTO.setOwnerAvatar(asset.getOwnerAvatar());
            oasisDistrictCollectionDTO.setCollectionId(asset.getId());
            if (!asset.getStatus().equals(AssetStatus.NORMAL)) {
                oasisDistrictCollectionDTO.setStatus(asset.getStatus().getDescription());
            } else {
                if (asset.isPublicShow()) {
                    Collection collection = collectionRepo.findFirstByOnShelfAndAssetId(true, asset.getId());
                    oasisDistrictCollectionDTO.setUrl(
                            generalProperties.getHost() + "/9th/productDetail/" + collection
                                    .getId() + "?id=" + collection.getId());
                    if (asset.isConsignment()) {
                        oasisDistrictCollectionDTO.setStatus("寄售中");
                    } else {
                        oasisDistrictCollectionDTO.setStatus("仅展示");
                    }
                } else {
                    oasisDistrictCollectionDTO.setStatus("未展示");
                }
            }
            oasisDistrictCollectionDTO.setSource("二手");
            //查询展厅信息
            Optional<Showroom> showroom = showroomRepo.findByOasisId(asset.getOasisId());
            showroom.ifPresent(t -> {
                //查询展厅内藏品
                List<ShowCollection> showCollections = showCollectionRepo.findAllByShowroomId(t.getId());
                showCollections.forEach(y -> {
                    y.setSaleUrl(
                            generalProperties.getHost() + "/9th/productDetail/" + y
                                    .getCollectionId());
                });
                t.setCollections(showCollections);
                oasisDistrictCollectionDTO.setShowroomInfo(t);
            });
            oasisDistrictCollectionDTOS.add(oasisDistrictCollectionDTO);
        });

        officialCollections.forEach(collection -> {
            OasisDistrictCollectionDTO oasisDistrictCollectionDTO = new OasisDistrictCollectionDTO();
            oasisDistrictCollectionDTO.setOasisId(collection.getOasisId());
            oasisDistrictCollectionDTO.setCollectionName(collection.getName());
            oasisDistrictCollectionDTO.setOriginPrice(collection.getPrice());
            oasisDistrictCollectionDTO.setSellPrice(collection.getPrice());
            oasisDistrictCollectionDTO.setSalable(collection.isSalable());
            oasisDistrictCollectionDTO.setOwnerId(collection.getOwnerId());
            oasisDistrictCollectionDTO.setOwnerName(collection.getOwner());
            oasisDistrictCollectionDTO.setOwnerAvatar(collection.getOwnerAvatar());
            oasisDistrictCollectionDTO.setCollectionId(collection.getId());
            oasisDistrictCollectionDTO.setScanOnly(collection.isScanCode());
            oasisDistrictCollectionDTO.setSource("官方");
            if (collection.isOnShelf()) {
                oasisDistrictCollectionDTO.setUrl(
                        generalProperties.getHost() + "/9th/productDetail/" + collection
                                .getId() + "?id=" + collection.getId());
                if (collection.isSalable()) {
                    oasisDistrictCollectionDTO.setStatus("在售");
                    if (collection.getStock() == 0) {
                        oasisDistrictCollectionDTO.setStatus("已有订单，订单处理中");
                    }
                } else {
                    oasisDistrictCollectionDTO.setStatus("仅展示");
                }
            } else {
                oasisDistrictCollectionDTO.setStatus("未上架");
            }

            //查询展厅信息
            Optional<Showroom> showroom = showroomRepo.findByOasisId(collection.getOasisId());
            showroom.ifPresent(t -> {
                //查询展厅内藏品
                List<ShowCollection> showCollections = showCollectionRepo.findAllByShowroomId(t.getId());
                showCollections.forEach(y -> {
                    y.setSaleUrl(
                            generalProperties.getHost() + "/9th/productDetail/" + y
                                    .getCollectionId());
                });
                t.setCollections(showCollections);
                oasisDistrictCollectionDTO.setShowroomInfo(t);
            });
            oasisDistrictCollectionDTOS.add(oasisDistrictCollectionDTO);
        });

        companyCollections.forEach(companyCollection -> {
            OasisDistrictCollectionDTO oasisDistrictCollectionDTO = new OasisDistrictCollectionDTO();
            oasisDistrictCollectionDTO.setOasisId(companyCollection.getOasisId());
            oasisDistrictCollectionDTO.setCollectionName(companyCollection.getName());
            oasisDistrictCollectionDTO.setScanOnly(false);
            oasisDistrictCollectionDTO.setOriginPrice(companyCollection.getPrice());
            oasisDistrictCollectionDTO.setOwnerName(companyCollection.getMinter());
            oasisDistrictCollectionDTO.setCollectionId(companyCollection.getId());
            oasisDistrictCollectionDTO.setSalable(false);
            oasisDistrictCollectionDTO.setStatus("审核中");
            oasisDistrictCollectionDTO.setSource("官方");
            oasisDistrictCollectionDTO.setSellPrice(companyCollection.getPrice());

            //查询展厅信息
            Optional<Showroom> showroom = showroomRepo.findByOasisId(companyCollection.getOasisId());
            showroom.ifPresent(t -> {
                //查询展厅内藏品
                List<ShowCollection> showCollections = showCollectionRepo.findAllByShowroomId(t.getId());
                showCollections.forEach(y -> {
                    y.setSaleUrl(
                            generalProperties.getHost() + "/9th/productDetail/" + y
                                    .getCollectionId());
                });
                t.setCollections(showCollections);
                oasisDistrictCollectionDTO.setShowroomInfo(t);
            });
            oasisDistrictCollectionDTOS.add(oasisDistrictCollectionDTO);
        });
        return oasisDistrictCollectionDTOS;
    }

    public Order checkOasisIdOrder(Long collectionId) {
        return orderRepo.findFirstByCollectionIdOrderByCreatedAtDesc(collectionId);
    }
}
