package com.izouma.nineth.web;

import com.fasterxml.jackson.annotation.JsonView;
import com.izouma.nineth.TokenHistory;
import com.izouma.nineth.domain.Asset;
import com.izouma.nineth.domain.GiftOrder;
import com.izouma.nineth.dto.*;
import com.izouma.nineth.enums.CollectionType;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.repo.AssetRepo;
import com.izouma.nineth.repo.OrderRepo;
import com.izouma.nineth.service.AssetService;
import com.izouma.nineth.service.CacheService;
import com.izouma.nineth.service.GiftOrderService;
import com.izouma.nineth.utils.SecurityUtils;
import com.izouma.nineth.utils.excel.ExcelUtils;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ExecutionException;

@RestController
@RequestMapping("/asset")
@AllArgsConstructor
public class AssetController extends BaseController {
    private AssetService assetService;
    private AssetRepo assetRepo;
    private GiftOrderService giftOrderService;
    private OrderRepo orderRepo;
    private CacheService cacheService;

    //@PreAuthorize("hasRole('ADMIN')")
//    @PostMapping("/save")
//    public Asset save(@RequestBody Asset record) {
//        if (record.getId() != null) {
//            Asset orig = assetRepo.findById(record.getId()).orElseThrow(new BusinessException("无记录"));
//            ObjUtils.merge(orig, record);
//            return assetRepo.save(orig);
//        }
//        return assetRepo.save(record);
//    }


    //@PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/all")
    @JsonView(Asset.View.Basic.class)
    public Page<Asset> all(@RequestBody PageQuery pageQuery) {
        pageQuery.getQuery().put("userId", SecurityUtils.getAuthenticatedUser().getId());
        return assetService.all(pageQuery);
    }

    /**
     * 资产查询，除未开启盲盒prefixName相同叠加数量
     *
     * @param pageQuery 查询条件
     * @return 资产叠加后结果
     */
    @PostMapping({"/userSummary", "/superimposition"})
    public List<AssetDTO> userSummary(@RequestBody PageQuery pageQuery) {
        pageQuery.getQuery().put("userId", SecurityUtils.getAuthenticatedUser().getId());
        return assetService.userSummary(pageQuery);
    }

    @GetMapping("/get/{id}")
    @JsonView(Asset.View.Basic.class)
    public Asset get(@PathVariable Long id) {
        Asset asset = assetRepo.findById(id).orElseThrow(new BusinessException("无记录"));
//        orderRepo.findByIdAndDelFalse(asset.getOrderId()).ifPresent(order -> asset.setOpened(order.isOpened()));
        return asset;
    }

//    @PostMapping("/del/{id}")
//    public void del(@PathVariable Long id) {
//        assetRepo.softDelete(id);
//    }

    @PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/excel")
    @ResponseBody
    public void excel(HttpServletResponse response, PageQuery pageQuery) throws IOException {
        List<Asset> data = all(pageQuery).getContent();
        ExcelUtils.export(response, data);
    }

    @PostMapping("/publicShow")
    @ApiOperation("公开展示")
    public void publicShow(@RequestParam Long id) {
        assetService.publicShow(id);
    }

    @PostMapping("/cancelPublic")
    @ApiOperation("取消展示")
    public void cancelPublic(@RequestParam Long id) {
        assetService.cancelPublic(id);
    }

    @PostMapping("/usePrivilege")
    @ApiOperation("使用特权")
    public void usePrivilege(@RequestParam Long assetId, @RequestParam Long privilegeId) {
        assetService.usePrivilege(assetId, privilegeId);
    }

    @PostMapping("/consignment")
    @ApiOperation("寄售")
    public void consignment(@RequestParam Long id, @RequestParam BigDecimal price, @RequestParam String tradeCode,
                            @RequestParam(defaultValue = "false") boolean safeFlag) {
        assetService.consignment(id, price, tradeCode, safeFlag);
    }

    @PostMapping("/cancelConsignment")
    @ApiOperation("取消寄售")
    public void cancelConsignment(@RequestParam Long id) {
        assetService.cancelConsignment(id);
    }

    @PostMapping("/gift")
    @ApiOperation("转赠")
    public GiftOrder gift(@RequestParam Long assetId, @RequestParam Long toUserId, @RequestParam String tradeCode) {
        return giftOrderService.gift(SecurityUtils.getAuthenticatedUser().getId(), assetId, toUserId, tradeCode);
    }

    @PostMapping("/giftWithoutGasFee")
    @ApiOperation("转赠(无gas费)")
    public GiftOrder giftWithoutGasFee(@RequestParam Long assetId, @RequestParam Long toUserId, @RequestParam String tradeCode) {
        return giftOrderService.giftWithoutGasFee(SecurityUtils.getAuthenticatedUser()
                .getId(), assetId, toUserId, tradeCode);
    }

    @GetMapping("/tokenHistory")
    @ApiOperation("交易历史")
    public List<TokenHistory> tokenHistory(@RequestParam(required = false) String tokenId, @RequestParam(required = false) Long assetId) {
        return assetService.tokenHistory(tokenId, assetId);
    }

    @GetMapping("/userHistory")
    @ApiOperation("交易历史")
    public Page<UserHistory> userHistory(PageQuery pageQuery) {
        return assetService.userHistory(SecurityUtils.getAuthenticatedUser().getId(), pageQuery);
    }

    @GetMapping("/mint")
    public String mint(@RequestParam(required = false) LocalDateTime time) {
        return assetService.mint(time);
    }

    @GetMapping("/breakdown")
    @ApiOperation("收支总计")
    public Map<String, BigDecimal> breakdown() {
        return assetService.breakdown(SecurityUtils.getAuthenticatedUser().getId());
    }

    @PostMapping("/cdn")
    @PreAuthorize("hasRole('ADMIN')")
    public String cdn() throws ExecutionException, InterruptedException {
        new Thread(() -> {
            try {
                assetService.transferCDN();
            } catch (ExecutionException | InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        return "ok";
    }

    @GetMapping("/assetsForMint")
    @JsonView(Asset.View.Basic.class)
    public Page<Asset> assetsForMint(@RequestParam Long mintActivityId, Boolean refresh, Pageable pageable) {
        if (Objects.equals(refresh, true)) {
            cacheService.clearFmaa();
        }
        return assetService.findMintActivityAssetsWrap(SecurityUtils.getAuthenticatedUser().getId(),
                mintActivityId, pageable).toPage();
    }

    @GetMapping("/byTag")
    public Page<Asset> byTag(@RequestParam Long tagId, Pageable pageable) {
        return assetRepo.byTag(SecurityUtils.getAuthenticatedUser().getId(), tagId, pageable);
    }

    @ApiOperation("销毁")
    @PostMapping("/destroy")
    public void destroy(@RequestParam Long id, @RequestParam String tradeCode) {
        assetService.destroy(id, SecurityUtils.getAuthenticatedUser().getId(), tradeCode);
    }

    @ApiOperation("开盲盒")
    @PostMapping("/open")
    public void open(@RequestParam Long id) {
        if (SecurityUtils.getAuthenticatedUser().getId() == null) {
            return;
        }
        Asset asset = assetRepo.findById(id).orElseThrow(new BusinessException("无盲盒"));
        if (!SecurityUtils.getAuthenticatedUser().getId().equals(asset.getUserId())) {
            return;
        }
        if (!asset.isOpened() && CollectionType.BLIND_BOX.equals(asset.getType())) {
            asset.setOpened(true);
            assetRepo.save(asset);
        }
    }

    @PostMapping("/getRoyalties")
    public double getRoyalties(@RequestParam Long id) {
        Asset asset = assetRepo.findById(id).orElseThrow(new BusinessException("无记录"));
        return assetService.getRoyalties(asset.getMinterId(), asset.getRoyalties(), SecurityUtils.getAuthenticatedUser()
                .getId());
    }

    @GetMapping("/hcChain")
    public void hcChain() throws ExecutionException, InterruptedException {
        assetService.hcChain();
    }

    @PostMapping("/lockAsset")
    public void lockAsset(@RequestParam Long assetId, @RequestParam Duration duration) {
        assetService.lockAsset(SecurityUtils.getAuthenticatedUser().getId(), assetId, duration);
    }

    @GetMapping("/{userId}/metaPlayerRole")
    public List<MetaPlayerRoleClassify> MetaPlayerRoles(@PathVariable Long userId) {
        return assetService.metaPlayerRole(userId);
    }
}


