package com.rj.controller;

import com.rj.entity.LbPurchaseApply;
import com.rj.service.ILbPurchaseApplyService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import jakarta.servlet.http.HttpServletResponse;

import java.time.LocalDate;
import java.util.Map;

@RestController
@RequestMapping("/api/lbPurchaseApply")
@Tag(name = "进货申请", description = "lb_purchase_apply增删改查与分页")
public class LbPurchaseApplyController {

    @Autowired
    private ILbPurchaseApplyService lbPurchaseApplyService;

    @Data
    @Schema(description = "大模型解析订货信息请求体")
    public static class ParseOrderInfoRequest {
        @Schema(description = "订货信息原文", requiredMode = Schema.RequiredMode.REQUIRED)
        @NotBlank(message = "订货信息不能为空")
        private String orderInfo;

        @Schema(description = "当前登录人租户ID")
        private String tenantId;
    }

    @PostMapping("/parseFromOrderInfo")
    @Operation(summary = "大模型解析订货信息为进货申请实体", description = "根据自然语言订货信息调用大模型抽取字段，返回 LbPurchaseApply（不落库）")
    public ResponseEntity<Map<String, Object>> parseFromOrderInfo(
            @Parameter(description = "订货信息与租户ID", required = true) @Valid @RequestBody ParseOrderInfoRequest body) {
        Map<String, Object> result = lbPurchaseApplyService.parseFromOrderInfoByLlm(body.getOrderInfo(), body.getTenantId());
        Boolean success = (Boolean) result.get("success");
        if (success != null && success) {
            return ResponseEntity.ok(result);
        }
        return ResponseEntity.badRequest().body(result);
    }

    @PostMapping("/add")
    @Operation(summary = "新增或按申请人电话更新", description = "同一租户下若 applyPhone 已存在则更新该条，否则新增")
    public ResponseEntity<Map<String, Object>> add(
            @Parameter(description = "实体", required = true) @RequestBody LbPurchaseApply entity) {
        Map<String, Object> result = lbPurchaseApplyService.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 LbPurchaseApply entity) {
        Map<String, Object> result = lbPurchaseApplyService.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 = lbPurchaseApplyService.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 tenantId,
            @RequestParam(required = false) String applyUser,
            @RequestParam(required = false) String applyPhone,
            @RequestParam(required = false) String colleagueName,
            @RequestParam(required = false) String teamLeader,
            @RequestParam(required = false) String teamBigLeader,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate applyDate) {
        Map<String, Object> result = lbPurchaseApplyService.pageQuery(
                current, size, tenantId, applyUser, applyPhone, colleagueName, teamLeader, teamBigLeader, applyDate
        );
        Boolean success = (Boolean) result.get("success");
        if (success != null && success) {
            return ResponseEntity.ok(result);
        }
        return ResponseEntity.internalServerError().body(result);
    }

    @GetMapping("/syncHxrAdminUserVip")
    @Operation(summary = "按申请日期与租户同步 hxrd 用户 VIP 字段",
            description = "根据 lb_purchase_apply 的申请日期区间与 tenant_id 逐条处理记录，"
                    + "以每条记录的 apply_date 为起算日计算 viptime（周末先对齐到下一工作日，再顺延 3 个工作日），"
                    + "再 GET /app/admin/user/select、POST /app/admin/user/update（max_order、is_vip=1 等）。"
                    + "需配置 hxr.admin.cookie 或 hxr.admin.phpsid。")
    public ResponseEntity<Map<String, Object>> syncHxrAdminUserVip(
            @Parameter(description = "申请开始日期(yyyy-MM-dd)", required = true)
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate applyDateStart,
            @Parameter(description = "申请结束日期(yyyy-MM-dd)", required = true)
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate applyDateEnd,
            @Parameter(description = "租户ID", required = true)
            @RequestParam String tenantId,
            @Parameter(description = "最大订单数 max_order", required = true)
            @RequestParam("max_order") Integer maxOrder) {
        Map<String, Object> result = lbPurchaseApplyService.syncHxrAdminUserVipByApplyDateRange(
                applyDateStart, applyDateEnd, tenantId, maxOrder);
        Boolean success = (Boolean) result.get("success");
        if (success != null && success) {
            return ResponseEntity.ok(result);
        }
        return ResponseEntity.badRequest().body(result);
    }

    @GetMapping("/syncHxrAdminColleagueVip")
    @Operation(summary = "按申请日期与租户同步同事 hxrd 用户 VIP",
            description = "根据 lb_purchase_apply 的申请日期区间与 tenant_id 逐条处理，"
                    + "仅当 colleague_name 能在 lb_daily_user_trade（同租户 nickname）中查到时才开通；"
                    + "以 colleague_phone 查询 /app/admin/user/select，"
                    + "以每条记录的 apply_date 为起算日计算 viptime（周末先对齐到下一工作日，再顺延 2 个工作日），"
                    + "再 POST /app/admin/user/update（max_order 使用 select 返回的 HxrUserRow.max_order）。"
                    + "需配置 hxr.admin.cookie 或 hxr.admin.phpsid。")
    public ResponseEntity<Map<String, Object>> syncHxrAdminColleagueVip(
            @Parameter(description = "申请开始日期(yyyy-MM-dd)", required = true)
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate applyDateStart,
            @Parameter(description = "申请结束日期(yyyy-MM-dd)", required = true)
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate applyDateEnd,
            @Parameter(description = "租户ID", required = true)
            @RequestParam String tenantId) {
        Map<String, Object> result = lbPurchaseApplyService.syncHxrAdminColleagueVipByApplyDateRange(
                applyDateStart, applyDateEnd, tenantId);
        Boolean success = (Boolean) result.get("success");
        if (success != null && success) {
            return ResponseEntity.ok(result);
        }
        return ResponseEntity.badRequest().body(result);
    }

    @GetMapping("/exportColleagueVip")
    @Operation(summary = "导出同事特权开通提醒Excel",
            description = "筛选逻辑与 syncHxrAdminColleagueVip 一致：仅导出申请人当日有进货记录、"
                    + "且具备同事手机号的可开通记录，列含昵称、手机号、特权开通日期、开通日期")
    public void exportColleagueVip(
            @Parameter(description = "申请开始日期(yyyy-MM-dd)", required = true)
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate applyDateStart,
            @Parameter(description = "申请结束日期(yyyy-MM-dd)", required = true)
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate applyDateEnd,
            @Parameter(description = "租户ID", required = true)
            @RequestParam String tenantId,
            HttpServletResponse response) {
        lbPurchaseApplyService.exportColleagueVipExcel(applyDateStart, applyDateEnd, tenantId, response);
    }

    @GetMapping("/export")
    @Operation(summary = "导出进货申请Excel", description = "按租户ID与申请日期范围导出，按申请日分组并合并首列")
    public void export(
            @Parameter(description = "申请开始日期(yyyy-MM-dd)", required = true)
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate applyDateStart,
            @Parameter(description = "申请结束日期(yyyy-MM-dd)", required = true)
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate applyDateEnd,
            @Parameter(description = "租户ID", required = true)
            @RequestParam String tenantId,
            HttpServletResponse response) {
        lbPurchaseApplyService.exportExcel(applyDateStart, applyDateEnd, tenantId, response);
    }

    @GetMapping("/needPrivilegeRecommenders")
    @Operation(summary = "按日期范围查询需要添加特权的推荐人")
    public ResponseEntity<Map<String, Object>> needPrivilegeRecommenders(
            @Parameter(description = "开始日期(yyyy-MM-dd)", required = true)
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startDate,
            @Parameter(description = "结束日期(yyyy-MM-dd)", required = true)
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endDate) {
        Map<String, Object> result = lbPurchaseApplyService.listNeedPrivilegeRecommenders(startDate, endDate);
        Boolean success = (Boolean) result.get("success");
        if (success != null && success) {
            return ResponseEntity.ok(result);
        }
        return ResponseEntity.badRequest().body(result);
    }
}
