package com.rj.controller;

import com.rj.dto.LbOrderRowGenerateSumRequest;
import com.rj.dto.LbOrderRowSyncFromHxrRequest;
import com.rj.entity.LbOrderRow;
import com.rj.service.ILbOrderRowService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/api/lbOrderRow")
@Tag(name = "LB 订单行", description = "lb_order_row 增删改查与分页")
public class LbOrderRowController {

    @Autowired
    private ILbOrderRowService lbOrderRowService;

    @PostMapping("/add")
    @Operation(summary = "新增")
    public ResponseEntity<Map<String, Object>> add(
            @Parameter(description = "实体（id 为订单 id，需调用方指定）", required = true) @RequestBody LbOrderRow entity) {
        Map<String, Object> result = lbOrderRowService.add(entity);
        Boolean success = (Boolean) result.get("success");
        if (success != null && success) {
            return ResponseEntity.ok(result);
        }
        return ResponseEntity.badRequest().body(result);
    }

    @PutMapping("/update")
    @Operation(summary = "编辑")
    public ResponseEntity<Map<String, Object>> update(
            @Parameter(description = "实体", required = true) @RequestBody LbOrderRow entity) {
        Map<String, Object> result = lbOrderRowService.update(entity);
        Boolean success = (Boolean) result.get("success");
        if (success != null && success) {
            return ResponseEntity.ok(result);
        }
        return ResponseEntity.badRequest().body(result);
    }

    @DeleteMapping("/delete/{id}")
    @Operation(summary = "删除")
    public ResponseEntity<Map<String, Object>> delete(
            @Parameter(description = "主键（订单 id）", required = true) @PathVariable Long id) {
        Map<String, Object> result = lbOrderRowService.deleteById(id);
        Boolean success = (Boolean) result.get("success");
        if (success != null && success) {
            return ResponseEntity.ok(result);
        }
        return ResponseEntity.badRequest().body(result);
    }

    @GetMapping("/list")
    @Operation(summary = "分页查询")
    public ResponseEntity<Map<String, Object>> list(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String isResell,
            @Parameter(description = "数据类型") @RequestParam(required = false) String dataType,
            @RequestParam(required = false) String orderSn,
            @Parameter(description = "电话") @RequestParam(required = false) String phone,
            @RequestParam(required = false) Long buyerId,
            @RequestParam(required = false) Long sellerId,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) Long merchandiseId) {
        Map<String, Object> result =
                lbOrderRowService.pageQuery(
                        current,
                        size,
                        isResell,
                        dataType,
                        orderSn,
                        phone,
                        buyerId,
                        sellerId,
                        status,
                        merchandiseId);
        Boolean success = (Boolean) result.get("success");
        if (success != null && success) {
            return ResponseEntity.ok(result);
        }
        return ResponseEntity.internalServerError().body(result);
    }

    @PostMapping("/sync-order-from-third")
    @Operation(
            summary = "从 外部系统 同步订单",
            description = "按购买时间区间、租户 id、转卖状态调用后台 order/select，将结果写入 lb_order_row（按订单 id upsert）")
    public ResponseEntity<Map<String, Object>> syncFromHxr(
            @Parameter(description = "同步条件", required = true) @RequestBody LbOrderRowSyncFromHxrRequest request) {
        Map<String, Object> result =
                lbOrderRowService.syncFromHxrAdmin(
                        request.getBuyTimeStart(),
                        request.getBuyTimeEnd(),
                        request.getTenantId(),
                        request.getIsResell());
        Boolean success = (Boolean) result.get("success");
        if (success != null && success) {
            return ResponseEntity.ok(result);
        }
        return ResponseEntity.badRequest().body(result);
    }

    @PostMapping("/generate-daily-sum")
    @Operation(
            summary = "按日汇总生成 sum_data",
            description =
                    "按购买时间区间、租户 id 查询 lb_order_row 明细，每天生成一条 sum_data（today_total_money_sum、"
                            + "today_unresell_count、today_order_count 等）并写入表")
    public ResponseEntity<Map<String, Object>> generateDailySum(
            @Parameter(description = "汇总条件", required = true) @RequestBody
                    LbOrderRowGenerateSumRequest request) {
        Map<String, Object> result =
                lbOrderRowService.generateDailySumData(
                        request.getBuyTimeStart(),
                        request.getBuyTimeEnd(),
                        request.getTenantId());
        Boolean success = (Boolean) result.get("success");
        if (success != null && success) {
            return ResponseEntity.ok(result);
        }
        return ResponseEntity.badRequest().body(result);
    }

    @PostMapping("/send-seller-confirm-to-dingtalk")
    @Operation(
            summary = "发送卖家确认通知到钉钉",
            description =
                    "按购买时间区间、租户 id 查询 lb_order_row 明细，将卖家姓名以「买家已支付，不要影响 对方寄卖，"
                            + "请如下卖家确认：」为前缀发送至钉钉，每批最多 15 条记录")
    public ResponseEntity<Map<String, Object>> sendSellerConfirmToDingTalk(
            @Parameter(description = "查询与发送条件", required = true) @RequestBody
                    LbOrderRowGenerateSumRequest request) {
        Map<String, Object> result =
                lbOrderRowService.sendSellerConfirmToDingTalk(
                        request.getBuyTimeStart(),
                        request.getBuyTimeEnd(),
                        request.getTenantId());
        Boolean success = (Boolean) result.get("success");
        if (success != null && success) {
            return ResponseEntity.ok(result);
        }
        return ResponseEntity.badRequest().body(result);
    }
}
