package com.izouma.nineth.web;

import com.izouma.nineth.TokenHistory;
import com.izouma.nineth.domain.Asset;
import com.izouma.nineth.domain.GiftOrder;
import com.izouma.nineth.domain.User;
import com.izouma.nineth.dto.LeaderboardDTO;
import com.izouma.nineth.dto.PageQuery;
import com.izouma.nineth.dto.UserHistory;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.repo.AssetRepo;
import com.izouma.nineth.repo.TokenHistoryRepo;
import com.izouma.nineth.service.AssetMintService;
import com.izouma.nineth.service.AssetService;
import com.izouma.nineth.service.GiftOrderService;
import com.izouma.nineth.utils.ObjUtils;
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.web.bind.annotation.*;

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

@RestController
@RequestMapping("/asset")
@AllArgsConstructor
public class AssetController extends BaseController {
    private AssetService     assetService;
    private AssetRepo        assetRepo;
    private GiftOrderService giftOrderService;
    private TokenHistoryRepo tokenHistoryRepo;
    private AssetMintService assetMintService;

    //@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")
    public Page<Asset> all(@RequestBody PageQuery pageQuery) {
        return assetService.all(pageQuery);
    }

    @GetMapping("/get/{id}")
    public Asset get(@PathVariable Long id) {
        return assetRepo.findById(id).orElseThrow(new BusinessException("无记录"));
    }

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

    @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) {
        assetService.consignment(id, price);
    }

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

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

    @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(@RequestParam(defaultValue = "2") int projectId, Pageable pageable) {
        return assetService.userHistory(SecurityUtils.getAuthenticatedUser().getId(), projectId, pageable);
    }

    @PostMapping("/holdQuery")
    public String holdQuery(@RequestParam List<String> names, @RequestParam LocalDateTime start, @RequestParam LocalDateTime end) {
        Map<User, Integer> match = assetService.holdQuery(names, start, end);
        StringBuilder builder = new StringBuilder("用户ID,昵称,手机,持有套数\n");
        for (Map.Entry<User, Integer> e : match.entrySet()) {
            User user = e.getKey();
            builder.append(String.format("%d,%s,%s,%d%n", user.getId(), user.getNickname(), user.getPhone(), e.getValue()));
        }
        return builder.toString();
    }

    @GetMapping("/mint")
    public String mint() {
        for (Asset asset : assetRepo.findByTxHashIsNullAndTokenIdNotNullAndCreatedAtBefore(LocalDateTime.now())) {
            assetMintService.mint(asset);
        }
        return "ok";
    }

    @ApiOperation("排行榜")
    @PostMapping("/ranking")
    public List<LeaderboardDTO> ranking() {
        return assetService.ranking(SecurityUtils.getAuthenticatedUser().getId(), 100);
    }
}


