package com.bizzan.bitrade.controller.activity;

import com.bizzan.bitrade.annotation.AccessLog;
import com.bizzan.bitrade.constant.AdminModule;
import com.bizzan.bitrade.controller.common.BaseAdminController;
import com.bizzan.bitrade.dao.AdminDao;
import com.bizzan.bitrade.entity.Admin;
import com.bizzan.bitrade.entity.ExperienceGiftGrantType;
import com.bizzan.bitrade.entity.ExperienceGiftRecord;
import com.bizzan.bitrade.service.ExperienceGiftRecordService;
import com.bizzan.bitrade.util.MessageResult;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 体验金列表管理接口
 */
@RestController
@RequestMapping("activity/experience-gift/record")
public class ExperienceGiftRecordController extends BaseAdminController {

    @Autowired
    private ExperienceGiftRecordService experienceGiftRecordService;

    @Autowired
    private AdminDao adminDao;

    /**
     * 分页查询体验金列表
     *
     * @param id              体验金ID（可选）
     * @param memberId        用户UID（可选）
     * @param productName     产品名称（可选，模糊）
     * @param statusGroup     状态分组：0=未使用,1=持仓中,2=已使用,4=已过期,5=已失效,null=全部
     * @param grantStartTime  领取开始日期 yyyy-MM-dd（可选）
     * @param grantEndTime    领取结束日期 yyyy-MM-dd（可选）
     * @param expireStartTime 失效开始日期 yyyy-MM-dd（可选）
     * @param expireEndTime   失效结束日期 yyyy-MM-dd（可选）
     * @param pageNo          页码
     * @param pageSize        每页大小
     */
    @PostMapping("page-query")
    @AccessLog(module = AdminModule.ACTIVITY, operation = "体验金列表分页查询")
    public MessageResult pageQuery(
            @RequestParam(required = false) Long id,
            @RequestParam(required = false) Long memberId,
            @RequestParam(required = false) Long productId,
            @RequestParam(required = false) String productName,
            @RequestParam(required = false) Integer statusGroup,
            @RequestParam(required = false) Integer grantType,
            @RequestParam(required = false) String grantStartTime,
            @RequestParam(required = false) String grantEndTime,
            @RequestParam(required = false) String expireStartTime,
            @RequestParam(required = false) String expireEndTime,
            @RequestParam(defaultValue = "1") int pageNo,
            @RequestParam(defaultValue = "15") int pageSize) {

        Page<Map> page = experienceGiftRecordService.pageQuery(
                id, memberId, productId, productName, statusGroup, grantType,
                grantStartTime, grantEndTime, expireStartTime, expireEndTime,
                pageNo, pageSize);
        return success(page);
    }

    /**
     * 统计数据（体验金金额、平仓盈利、平仓亏损），过滤条件与列表保持一致
     */
    @GetMapping("stats")
    @AccessLog(module = AdminModule.ACTIVITY, operation = "体验金列表统计")
    public MessageResult stats(
            @RequestParam(required = false) Long id,
            @RequestParam(required = false) Long memberId,
            @RequestParam(required = false) Long productId,
            @RequestParam(required = false) String productName,
            @RequestParam(required = false) Integer statusGroup,
            @RequestParam(required = false) Integer grantType,
            @RequestParam(required = false) String grantStartTime,
            @RequestParam(required = false) String grantEndTime,
            @RequestParam(required = false) String expireStartTime,
            @RequestParam(required = false) String expireEndTime) {

        Map<String, Object> stats = experienceGiftRecordService.stats(
                id, memberId, productId, productName, statusGroup, grantType,
                grantStartTime, grantEndTime, expireStartTime, expireEndTime);
        return success(stats);
    }

    /**
     * 手动赠送体验金（批量）
     *
     * @param productId  产品ID（必须是 ENABLED + MANUAL 类型）
     * @param memberIds  目标用户ID，英文分号/逗号分隔
     * @param remark     派发备注（可选）
     */
    @PostMapping("grant")
    @AccessLog(module = AdminModule.ACTIVITY, operation = "手动赠送体验金")
    public MessageResult grant(
            @RequestParam Long productId,
            @RequestParam String memberIds,
            @RequestParam(required = false) String remark,
            HttpServletRequest request) {

        Admin admin = getAdmin(request);
        if (admin == null) return error("请先登录");

        // 解析 UID 列表（支持分号/逗号分隔）
        String[] parts = memberIds.split("[;,；，\\s]+");
        List<Long> idList = new ArrayList<>();
        for (String part : parts) {
            String trimmed = part.trim();
            if (StringUtils.isNotBlank(trimmed)) {
                try {
                    idList.add(Long.parseLong(trimmed));
                } catch (NumberFormatException e) {
                    return error("用户UID格式错误：" + trimmed);
                }
            }
        }
        if (idList.isEmpty()) {
            return error("请输入至少一个用户UID");
        }

        int count = experienceGiftRecordService.grantManual(productId, idList, remark, admin.getId());
        int total = idList.size();
        if (count == 0) {
            return error("赠送失败，所有用户均已超出领取上限或产品已达总量上限");
        }
        if (count < total) {
            return success("赠送完成，共 " + total + " 人，成功 " + count + " 张，" + (total - count) + " 人因超出领取上限跳过");
        }
        return success("赠送成功，共赠送 " + count + " 张");
    }

    /**
     * 手动回收体验金（仅限未使用状态）
     */
    @PostMapping("recycle/{id}")
    @AccessLog(module = AdminModule.ACTIVITY, operation = "体验金手动回收")
    public MessageResult recycle(@PathVariable Long id, HttpServletRequest request) {
        Admin admin = getAdmin(request);
        if (admin == null) return error("请先登录");
        String errMsg = experienceGiftRecordService.recycle(id, admin.getId());
        if (errMsg != null) return error(errMsg);
        return success("回收成功");
    }

    /**
     * 查询体验金来源详情
     */
    @GetMapping("source/{id}")
    @AccessLog(module = AdminModule.ACTIVITY, operation = "体验金来源查询")
    public MessageResult source(@PathVariable Long id) {
        ExperienceGiftRecord record = experienceGiftRecordService.findById(id);
        if (record == null) return error("记录不存在");

        // 将内部枚举映射为前端显示用的数值：0=注册触发, 1=邀请触发, 2=手动派发
        int displayGrantType;
        if (record.getGrantType() == ExperienceGiftGrantType.MANUAL) {
            displayGrantType = 2;
        } else if (record.getInviterId() != null) {
            displayGrantType = 1;
        } else {
            displayGrantType = 0;
        }

        Map<String, Object> result = new HashMap<>();
        result.put("grantType", displayGrantType);
        result.put("memberId", record.getMemberId());
        result.put("inviterId", record.getInviterId());
        result.put("productName", record.getProductName());
        result.put("amount", record.getAmount());
        result.put("createdAt", record.getCreatedAt());
        result.put("positionId", record.getPositionId());
        result.put("usedAt", record.getUsedAt());
        result.put("closedAt", record.getClosedAt());
        result.put("operatorId", record.getOperatorId());

        // 手动派发：查出管理员用户名
        if (record.getOperatorId() != null) {
            Admin operator = adminDao.findOne(record.getOperatorId());
            result.put("operatorUsername", operator != null ? operator.getUsername() : String.valueOf(record.getOperatorId()));
        }

        return success(result);
    }
}
