package com.fs.company.controller.qw;

import com.fs.common.core.controller.BaseController;
import com.fs.common.core.domain.AjaxResult;
import com.fs.common.core.page.TableDataInfo;
import com.fs.common.utils.ServletUtils;
import com.fs.framework.security.LoginUser;
import com.fs.framework.service.TokenService;
import com.fs.sop.domain.SopGenerationFailedLog;
import com.fs.sop.service.ISopGenerationFailedLogService;
import com.fs.sop.vo.SopGenerationFailedLogVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

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

/**
 * SOP生成失败日志Controller
 * 用于查询被过滤的客户信息，支持补发操作
 *
 * @author fs
 * @date 2026-01-23
 */
@RestController
@RequestMapping("/qwSop/failedLog")
public class SopGenerationFailedLogController extends BaseController {

    @Autowired
    private ISopGenerationFailedLogService failedLogService;

    @Autowired
    private TokenService tokenService;


    private Long getCurrentCompanyId() {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        return loginUser.getUser().getCompanyId();
    }

    /**
     * 查询SOP生成失败日志列表
     *
     * @param log 查询条件
     * @return 失败日志列表
     */
    @GetMapping("/list")
    public TableDataInfo list(SopGenerationFailedLog log) {
        log.setCompanyId(getCurrentCompanyId().toString());

        startPage();
        List<SopGenerationFailedLog> list = failedLogService.selectFailedLogList(log);
        return getDataTable(list);
    }

    /**
     * 查询失败日志列表（带客户名称等扩展信息）
     * @param log 查询条件
     * @return 失败日志VO列表
     */
    @GetMapping("/voList")
    public TableDataInfo voList(SopGenerationFailedLog log) {
        log.setCompanyId(getCurrentCompanyId().toString());

        startPage();
        List<SopGenerationFailedLogVO> list = failedLogService.selectFailedLogVOList(log);
        return getDataTable(list);
    }

    /**
     * 根据营期ID查询失败日志
     *
     * @param userLogsId 营期ID
     * @return 失败日志列表
     */
    @GetMapping("/listByUserLogsId/{userLogsId}")
    public AjaxResult listByUserLogsId(@PathVariable String userLogsId) {
        SopGenerationFailedLog query = new SopGenerationFailedLog();
        query.setUserLogsId(userLogsId);
        query.setCompanyId(getCurrentCompanyId().toString());

        List<SopGenerationFailedLog> list = failedLogService.selectFailedLogList(query);
        return AjaxResult.success(list);
    }

    /**
     * 根据SOP ID查询失败日志
     *
     * @param sopId SOP ID
     * @return 失败日志列表
     */
    @GetMapping("/listBySopId/{sopId}")
    public AjaxResult listBySopId(@PathVariable String sopId) {
        SopGenerationFailedLog query = new SopGenerationFailedLog();
        query.setSopId(sopId);
        query.setCompanyId(getCurrentCompanyId().toString());

        List<SopGenerationFailedLog> list = failedLogService.selectFailedLogList(query);
        return AjaxResult.success(list);
    }

    /**
     * 查询失败统计信息
     *
     * @param sopId SOP ID
     * @param userLogsId 营期ID（可选）
     * @return 统计信息
     */
    @GetMapping("/statistics")
    public AjaxResult statistics(@RequestParam(required = false) String sopId,
                                  @RequestParam(required = false) String userLogsId) {
        SopGenerationFailedLog query = new SopGenerationFailedLog();
        query.setSopId(sopId);
        query.setUserLogsId(userLogsId);
        query.setCompanyId(getCurrentCompanyId().toString());

        List<SopGenerationFailedLog> list = failedLogService.selectFailedLogList(query);

        Map<Integer, Long> typeCountMap = new HashMap<>();
        Map<Integer, String> typeNameMap = new HashMap<>();

        typeNameMap.put(1, "未注册小程序");
        typeNameMap.put(2, "E级客户过滤");
        typeNameMap.put(3, "数据缺失");
        typeNameMap.put(4, "营期超期");
        typeNameMap.put(5, "其他原因");

        for (SopGenerationFailedLog log : list) {
            Integer failType = log.getFailType();
            typeCountMap.put(failType, typeCountMap.getOrDefault(failType, 0L) + 1);
        }

        Map<String, Object> result = new HashMap<>();
        result.put("total", list.size());
        result.put("notRetryCount", list.stream().filter(l -> l.getIsRetry() == 0).count());
        result.put("retriedCount", list.stream().filter(l -> l.getIsRetry() == 1).count());
        result.put("typeStatistics", typeCountMap);
        result.put("typeNames", typeNameMap);

        return AjaxResult.success(result);
    }

    /**
     * 获取失败日志详情
     *
     * @param id 主键ID
     * @return 失败日志详情
     */
    @GetMapping("/{id}")
    public AjaxResult getInfo(@PathVariable Long id) {
        return AjaxResult.success(failedLogService.selectFailedLogById(id));
    }

    /**
     * 标记为已补发
     *
     * @param id 主键ID
     * @param retryBy 补发人
     * @return 操作结果
     */
    @PutMapping("/markRetried/{id}")
    public AjaxResult markRetried(@PathVariable Long id,
                                   @RequestParam(required = false) String retryBy) {
        if (retryBy == null || retryBy.trim().isEmpty()) {
            retryBy = getUsername();
        }

        int rows = failedLogService.updateRetryStatus(id, retryBy);
        return toAjax(rows);
    }

    /**
     * 批量标记为已补发
     *
     * @param ids 主键ID数组
     * @param retryBy 补发人
     * @return 操作结果
     */
    @PutMapping("/batchMarkRetried")
    public AjaxResult batchMarkRetried(@RequestParam Long[] ids,
                                        @RequestParam(required = false) String retryBy) {
        if (retryBy == null || retryBy.trim().isEmpty()) {
            retryBy = getUsername();
        }

        int successCount = 0;
        for (Long id : ids) {
            try {
                int rows = failedLogService.updateRetryStatus(id, retryBy);
                if (rows > 0) {
                    successCount++;
                }
            } catch (Exception e) {
                logger.error("标记补发状态失败: id={}, error={}", id, e.getMessage(), e);
            }
        }

        return AjaxResult.success("成功标记" + successCount + "条记录为已补发");
    }

    /**
     *
     * @param sopId SOP ID
     * @param userLogsId 营期ID
     * @return 未补发的失败日志列表
     */
    @GetMapping("/listNotRetried")
    public TableDataInfo listNotRetried(@RequestParam(required = false) String sopId,
                                        @RequestParam(required = false) String userLogsId) {
        startPage();
        SopGenerationFailedLog query = new SopGenerationFailedLog();
        query.setSopId(sopId);
        query.setUserLogsId(userLogsId);
        query.setIsRetry(0); // 未补发
        query.setCompanyId(getCurrentCompanyId().toString());

        List<SopGenerationFailedLog> list = failedLogService.selectFailedLogList(query);
        return getDataTable(list);
    }
}
