package com.haha.admin.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.haha.admin.annotation.RequirePermission;
import com.haha.common.annotation.Log;
import com.haha.common.enums.OperationType;
import com.haha.common.vo.PageResult;
import com.haha.common.vo.Result;
import com.haha.entity.Distributor;
import com.haha.entity.DistributorCommission;
import com.haha.entity.DistributorConfig;
import com.haha.entity.DistributorMonthlyReport;
import com.haha.entity.DistributorReferral;
import com.haha.entity.DistributorWithdrawal;
import com.haha.entity.dto.CommissionQueryDTO;
import com.haha.entity.dto.DistributorConfigDTO;
import com.haha.entity.dto.DistributorCreateDTO;
import com.haha.entity.dto.DistributorQueryDTO;
import com.haha.entity.dto.DistributorUpdateDTO;
import com.haha.entity.dto.MonthlyReportQueryDTO;
import com.haha.entity.dto.ReferralQueryDTO;
import com.haha.entity.dto.WithdrawalQueryDTO;
import com.haha.entity.dto.WithdrawalReviewDTO;
import com.haha.service.DistributorCommissionService;
import com.haha.service.DistributorConfigService;
import com.haha.service.DistributorQrcodeService;
import com.haha.service.DistributorReferralService;
import com.haha.service.DistributorReportService;
import com.haha.service.DistributorService;
import com.haha.service.DistributorWithdrawalService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/distribution")
@RequiredArgsConstructor
public class DistributorAdminController {

    private final DistributorService distributorService;
    private final DistributorReferralService referralService;
    private final DistributorCommissionService commissionService;
    private final DistributorWithdrawalService withdrawalService;
    private final DistributorReportService reportService;
    private final DistributorConfigService configService;
    private final DistributorQrcodeService qrcodeService;

    @RequirePermission("distribution:distributor:create")
    @Log(module = "分销管理", operation = OperationType.INSERT, summary = "创建分销员")
    @PostMapping("/distributor")
    public Result<Distributor> createDistributor(@RequestBody @Valid DistributorCreateDTO dto) {
        Long creatorId = StpUtil.getLoginIdAsLong();
        String creatorName = (String) StpUtil.getSession().get("name");
        Distributor distributor = distributorService.create(dto, creatorId, creatorName);
        return Result.success("创建成功", distributor);
    }

    @RequirePermission("distribution:distributor:update")
    @Log(module = "分销管理", operation = OperationType.UPDATE, summary = "更新分销员")
    @PutMapping("/distributor")
    public Result<Distributor> updateDistributor(@RequestBody @Valid DistributorUpdateDTO dto) {
        Distributor result = distributorService.update(dto);
        return Result.success("更新成功", result);
    }

    @RequirePermission("distribution:distributor:read")
    @GetMapping("/distributor/list")
    public Result<PageResult<Distributor>> listDistributors(DistributorQueryDTO queryDTO) {
        IPage<Distributor> page = distributorService.getPage(queryDTO);
        return Result.success("查询成功", PageResult.of(page));
    }

    @RequirePermission("distribution:distributor:read")
    @GetMapping("/distributor/{id}")
    public Result<Distributor> getDistributorDetail(@PathVariable Long id) {
        Distributor result = distributorService.getDetail(id);
        return Result.success("查询成功", result);
    }

    @RequirePermission("distribution:distributor:update")
    @Log(module = "分销管理", operation = OperationType.UPDATE, summary = "激活分销员")
    @PutMapping("/distributor/{id}/activate")
    public Result<Void> activateDistributor(@PathVariable Long id) {
        distributorService.activate(id);
        qrcodeService.generateQrcode(id);
        return Result.success("激活成功", null);
    }

    @RequirePermission("distribution:distributor:update")
    @Log(module = "分销管理", operation = OperationType.UPDATE, summary = "停用分销员")
    @PutMapping("/distributor/{id}/deactivate")
    public Result<Void> deactivateDistributor(@PathVariable Long id) {
        distributorService.deactivate(id);
        return Result.success("停用成功", null);
    }

    @RequirePermission("distribution:distributor:delete")
    @Log(module = "分销管理", operation = OperationType.DELETE, summary = "删除分销员")
    @DeleteMapping("/distributor/{id}")
    public Result<Void> deleteDistributor(@PathVariable Long id) {
        distributorService.delete(id);
        return Result.success("删除成功", null);
    }

    @RequirePermission("distribution:distributor:update")
    @Log(module = "分销管理", operation = OperationType.UPDATE, summary = "生成二维码")
    @PostMapping("/distributor/{id}/qrcode")
    public Result<String> generateQrcode(@PathVariable Long id) {
        String qrcodeContent = qrcodeService.generateQrcode(id);
        return Result.success("二维码生成成功", qrcodeContent);
    }

    @RequirePermission("distribution:referral:read")
    @GetMapping("/referral/list")
    public Result<PageResult<DistributorReferral>> listReferrals(ReferralQueryDTO queryDTO) {
        IPage<DistributorReferral> page = referralService.getPage(queryDTO);
        return Result.success("查询成功", PageResult.of(page));
    }

    @RequirePermission("distribution:commission:read")
    @GetMapping("/commission/list")
    public Result<PageResult<DistributorCommission>> listCommissions(CommissionQueryDTO queryDTO) {
        IPage<DistributorCommission> page = commissionService.getPage(queryDTO);
        return Result.success("查询成功", PageResult.of(page));
    }

    @RequirePermission("distribution:withdrawal:read")
    @GetMapping("/withdrawal/list")
    public Result<PageResult<DistributorWithdrawal>> listWithdrawals(WithdrawalQueryDTO queryDTO) {
        IPage<DistributorWithdrawal> page = withdrawalService.getPage(queryDTO);
        return Result.success("查询成功", PageResult.of(page));
    }

    @RequirePermission("distribution:withdrawal:review")
    @Log(module = "分销管理", operation = OperationType.UPDATE, summary = "审核提现")
    @PutMapping("/withdrawal/review")
    public Result<DistributorWithdrawal> reviewWithdrawal(@RequestBody @Valid WithdrawalReviewDTO dto) {
        Long reviewerId = StpUtil.getLoginIdAsLong();
        String reviewerName = (String) StpUtil.getSession().get("name");
        DistributorWithdrawal result = withdrawalService.reviewWithdrawal(dto, reviewerId, reviewerName);
        return Result.success("审核成功", result);
    }

    @RequirePermission("distribution:withdrawal:review")
    @Log(module = "分销管理", operation = OperationType.UPDATE, summary = "确认到账")
    @PutMapping("/withdrawal/{id}/confirm")
    public Result<DistributorWithdrawal> confirmTransfer(@PathVariable Long id) {
        DistributorWithdrawal result = withdrawalService.confirmTransfer(id);
        return Result.success("确认到账成功", result);
    }

    @RequirePermission("distribution:report:read")
    @GetMapping("/report/list")
    public Result<PageResult<DistributorMonthlyReport>> listReports(MonthlyReportQueryDTO queryDTO) {
        IPage<DistributorMonthlyReport> page = reportService.getPage(queryDTO);
        return Result.success("查询成功", PageResult.of(page));
    }

    @RequirePermission("distribution:report:generate")
    @Log(module = "分销管理", operation = OperationType.INSERT, summary = "生成月度报表")
    @PostMapping("/report/generate")
    public Result<Void> generateReport(@RequestParam String yearMonth) {
        reportService.generateMonthlyReport(yearMonth);
        return Result.success("报表生成成功", null);
    }

    @RequirePermission("distribution:report:export")
    @GetMapping("/report/export")
    public Result<List<DistributorMonthlyReport>> exportReport(@RequestParam String yearMonth) {
        List<DistributorMonthlyReport> list = reportService.exportMonthlyReport(yearMonth);
        return Result.success("查询成功", list);
    }

    @RequirePermission("distribution:dashboard:read")
    @GetMapping("/dashboard")
    public Result<Object> getDashboard() {
        Object result = reportService.getDashboard();
        return Result.success("查询成功", result);
    }

    @RequirePermission("distribution:config:read")
    @GetMapping("/config/list")
    public Result<List<DistributorConfig>> listConfigs() {
        List<DistributorConfig> list = configService.getAllConfigs();
        return Result.success("查询成功", list);
    }

    @RequirePermission("distribution:config:update")
    @Log(module = "分销管理", operation = OperationType.UPDATE, summary = "更新分销配置")
    @PutMapping("/config")
    public Result<DistributorConfig> updateConfig(@RequestBody @Valid DistributorConfigDTO dto) {
        DistributorConfig result = configService.updateConfig(dto);
        return Result.success("更新成功", result);
    }
}
