package com.bizzan.bitrade.controller.system;

import com.bizzan.bitrade.controller.common.BaseAdminController;
import com.bizzan.bitrade.entity.ConfigSymbol;
import com.bizzan.bitrade.entity.ConfigSymbolSlippage;
import com.bizzan.bitrade.service.ConfigSymbolService;
import com.bizzan.bitrade.util.MessageResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/system/config-symbol")
@Slf4j
public class ConfigSymbolController extends BaseAdminController {

    @Autowired
    private ConfigSymbolService configSymbolService;

    @Autowired
    @Qualifier("plainRestTemplate")
    private RestTemplate restTemplate;

    @Value("${spot.api.url}")
    private String spotUrl;

    @PostMapping("page-query")
    public MessageResult pageQuery(
            @RequestParam(defaultValue = "1") int pageNo,
            @RequestParam(defaultValue = "15") int pageSize,
            @RequestParam(required = false) String base,
            @RequestParam(required = false) String quote,
            @RequestParam(required = false) String zone,
            @RequestParam(required = false) String isOpen
    ) {
        Pageable pageable = new PageRequest(pageNo - 1, pageSize, new Sort(Sort.Direction.DESC, "mtime"));
        Page<ConfigSymbol> page = configSymbolService.pageQuery(base, quote, zone, isOpen, pageable);
        return success(page);
    }

    @GetMapping("detail")
    public MessageResult detail(@RequestParam Long id) {
        ConfigSymbol symbol = configSymbolService.findOne(id);
        Assert.notNull(symbol, "记录不存在");
        return success(symbol);
    }

    @PostMapping("create")
    public MessageResult create(@RequestBody ConfigSymbol symbol) {
        if (configSymbolService.findBySymbol(symbol.getSymbol()) != null) {
            return error("交易对已存在: " + symbol.getSymbol());
        }
        return success(configSymbolService.create(symbol));
    }

    @PostMapping("update")
    public MessageResult update(@RequestBody ConfigSymbol symbol) {
        ConfigSymbol existing = configSymbolService.findOne(symbol.getId());
        Assert.notNull(existing, "记录不存在");
        if (!existing.getSymbol().equals(symbol.getSymbol())) {
            ConfigSymbol dup = configSymbolService.findBySymbol(symbol.getSymbol());
            if (dup != null) {
                return error("交易对已存在: " + symbol.getSymbol());
            }
        }
        // 只更新前端表单中可编辑的字段，null 表示前端未传，保留数据库现有值
        existing.setSymbol(symbol.getSymbol());
        existing.setBase(symbol.getBase());
        existing.setQuote(symbol.getQuote());
        existing.setIsOpen(symbol.getIsOpen());
        if (symbol.getTakerFee() != null) existing.setTakerFee(symbol.getTakerFee());
        if (symbol.getMakerFee() != null) existing.setMakerFee(symbol.getMakerFee());
        if (symbol.getPricePre() != null) existing.setPricePre(symbol.getPricePre());
        if (symbol.getVolumePre() != null) existing.setVolumePre(symbol.getVolumePre());
        existing.setSort(symbol.getSort());
        if (symbol.getPublish() != null) existing.setPublish(symbol.getPublish());
        if (symbol.getCustomize() != null) existing.setCustomize(symbol.getCustomize());
        if (symbol.getMaxOrdersPerUser() != null) existing.setMaxOrdersPerUser(symbol.getMaxOrdersPerUser());
        if (symbol.getDailyVolumeLimit() != null) existing.setDailyVolumeLimit(symbol.getDailyVolumeLimit());
        if (symbol.getCategory() != null) existing.setCategory(symbol.getCategory());
        if (symbol.getLabel() != null) existing.setLabel(symbol.getLabel());
        if (symbol.getLimitPriceMin() != null) existing.setLimitPriceMin(symbol.getLimitPriceMin());
        if (symbol.getLimitVolumeMin() != null) existing.setLimitVolumeMin(symbol.getLimitVolumeMin());
        if (symbol.getMarketBuyMin() != null) existing.setMarketBuyMin(symbol.getMarketBuyMin());
        if (symbol.getMarketSellMin() != null) existing.setMarketSellMin(symbol.getMarketSellMin());
        if (symbol.getDepth0Pre() != null) existing.setDepth0Pre(symbol.getDepth0Pre());
        if (symbol.getDepth1Pre() != null) existing.setDepth1Pre(symbol.getDepth1Pre());
        if (symbol.getDepth2Pre() != null) existing.setDepth2Pre(symbol.getDepth2Pre());
        existing.setSlippageList(symbol.getSlippageList());
        return success(configSymbolService.update(existing));
    }

    @PostMapping("delete")
    public MessageResult delete(@RequestParam Long id) {
        configSymbolService.delete(id);
        return success();
    }

    @PostMapping("toggle-status")
    public MessageResult toggleStatus(@RequestParam Long id) {
        configSymbolService.toggleStatus(id);
        return success();
    }

    @PostMapping("toggle-publish")
    public MessageResult togglePublish(@RequestParam Long id) {
        configSymbolService.togglePublish(id);
        return success();
    }

    @GetMapping("slippage-list")
    public MessageResult slippageList(@RequestParam String symbol) {
        List<ConfigSymbolSlippage> list = configSymbolService.getSlippageList(symbol);
        return success(list);
    }

    @PostMapping("cancel-all-orders")
    public MessageResult cancelAllOrders(@RequestParam String symbol) {
        try {
            Map<String, String> params = new HashMap<>();
            params.put("symbol", symbol);
            String result = restTemplate.postForObject(
                    spotUrl + "/admin/order/cancel/all?symbol={symbol}",
                    null, String.class, symbol);
            log.info("cancelAllOrders for symbol: {}, result: {}", symbol, result);
            return success(result);
        } catch (Exception e) {
            log.error("撤销订单失败 - symbol: {}", symbol, e);
            return error("撤销订单失败: " + e.getMessage());
        }
    }
}
