package com.fs.qw.controller;

import com.fs.common.annotation.Log;
import com.fs.common.constant.HttpStatus;
import com.fs.common.core.controller.BaseController;
import com.fs.common.core.domain.AjaxResult;
import com.fs.common.core.page.PageDomain;
import com.fs.common.core.page.TableDataInfo;
import com.fs.common.core.page.TableSupport;
import com.fs.common.enums.BusinessType;
import com.fs.common.utils.poi.ExcelUtil;
import com.fs.fastGpt.domain.FastGptPushTokenTotal;
import com.fs.qw.domain.QwPushCount;
import com.fs.qw.service.IQwPushCountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ResourceLoader;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 定义销售推送不同类型的企业消息的次数Controller
 *
 * @author fs
 * @date 2025-08-22
 */
@RestController
@RequestMapping("/qw/qwPushCount")
public class QwPushCountController extends BaseController {
    @Autowired
    private IQwPushCountService qwPushCountService;
    @Autowired
    private ResourceLoader resourceLoader;

    /**
     * 查询定义销售推送不同类型的企业消息的次数列表
     */
    @PreAuthorize("@ss.hasPermi('qw:qwPushCount:list')")
    @GetMapping("/list")
    public TableDataInfo list(QwPushCount qwPushCount) {
        startPage();
        List<QwPushCount> list = qwPushCountService.selectQwPushCountList(qwPushCount);
        return getDataTable(list);
    }

    /**
     * 导出定义销售推送不同类型的企业消息的次数列表
     */
    @PreAuthorize("@ss.hasPermi('qw:qwPushCount:export')")
    @Log(title = "定义销售推送不同类型的企业消息的次数", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(QwPushCount qwPushCount) {
        List<QwPushCount> list = qwPushCountService.selectQwPushCountList(qwPushCount);
        ExcelUtil<QwPushCount> util = new ExcelUtil<QwPushCount>(QwPushCount.class);
        return util.exportExcel(list, "定义销售推送不同类型的企业消息的次数数据");
    }

    /**
     * 获取定义销售推送不同类型的企业消息的次数详细信息
     */
    @PreAuthorize("@ss.hasPermi('qw:qwPushCount:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        List<Long> companyIdList=new ArrayList<>();
        QwPushCount qwPushCount = qwPushCountService.selectQwPushCountById(id);
        companyIdList.add(qwPushCount.getCompanyId());
        qwPushCount.setCompanyIdList(companyIdList);
        return AjaxResult.success(qwPushCount);
    }


    /**
     * 新增定义销售推送不同类型的企业消息的次数
     */
    @PreAuthorize("@ss.hasPermi('qw:qwPushCount:add')")
    @Log(title = "定义销售推送不同类型的企业消息的次数", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody QwPushCount qwPushCount) {
        List<Long> existingIds = new ArrayList<>();
        Map<String, Long> existingDataMap = new HashMap<>();
        List<QwPushCount> existingPushCounts = qwPushCountService.selectQwPushCountLists();
        if (existingPushCounts != null && !existingPushCounts.isEmpty()) {
            existingPushCounts.forEach(item -> {
                String key = buildDataKey(item.getType(), item.getCompanyId());
                existingDataMap.put(key, item.getId());
            });
        }
        // 处理公司ID列表（可能为null或空）
        List<Long> companyIdList = qwPushCount.getCompanyIdList();
        boolean isEmptyList = companyIdList == null || companyIdList.isEmpty();

        if (isEmptyList) {
            // 处理无公司ID列表的情况
            String key = buildDataKey(qwPushCount.getType(), null);
            if (existingDataMap.containsKey(key)) {
                existingIds.add(qwPushCount.getId());
            } else {
                qwPushCountService.insertQwPushCount(qwPushCount);
            }
        } else {
            // 处理有公司ID列表的情况
            companyIdList.forEach(companyId -> {
                String key = buildDataKey(qwPushCount.getType(), companyId);
                if (existingDataMap.containsKey(key)) {
                    existingIds.add(companyId);
                } else {
                    qwPushCount.setCompanyId(companyId);
                    qwPushCountService.insertQwPushCount(qwPushCount);
                }
            });
        }

        // 统一处理返回结果
        if (!existingIds.isEmpty()) {
            return error("新增限定类型已存在:失败条数" + existingIds.size());
        } else {
            return toAjax(1);
        }
    }
    private String buildDataKey(Integer type, Long companyId) {
        return type + "_" + (companyId == null ? "null" : companyId);
    }

    /**
     * 修改定义销售推送不同类型的企业消息的次数
     */
    @PreAuthorize("@ss.hasPermi('qw:qwPushCount:edit')")
    @Log(title = "定义销售推送不同类型的企业消息的次数", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody QwPushCount qwPushCount) {
        QwPushCount pushCount;
        if (qwPushCount.getCompanyId() != null) {
            pushCount = qwPushCountService.SelectQwPushCountByCompanyId(qwPushCount.getType(), qwPushCount.getCompanyId());
        } else {
            pushCount = qwPushCountService.SelectQwPushCountByType(qwPushCount.getType());
        }
        if (pushCount != null) {
            if (!Objects.equals(pushCount.getId(), qwPushCount.getId()) && Objects.equals(pushCount.getCompanyId(), qwPushCount.getCompanyId()) && Objects.equals(pushCount.getType(), qwPushCount.getType())) {
                return toAjax(0);
            }
            if (Objects.equals(pushCount.getPushCount(), qwPushCount.getPushCount())) {
                return toAjax(0);
            }
        }
        return toAjax(qwPushCountService.updateQwPushCount(qwPushCount));
    }

    /**
     * 删除定义销售推送不同类型的企业消息的次数
     */
    @PreAuthorize("@ss.hasPermi('qw:qwPushCount:remove')")
    @Log(title = "定义销售推送不同类型的企业消息的次数", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(qwPushCountService.deleteQwPushCountByIds(ids));
    }

    @PreAuthorize("@ss.hasPermi('qw:qwPushCount:tokenList')")
    @GetMapping("/tokenList")
    public TableDataInfo tokenList(FastGptPushTokenTotal pushTokenInfo) {
        List<FastGptPushTokenTotal> list = qwPushCountService.selectFastGptPushTokenTotalList(pushTokenInfo);


        // 计算总和
        FastGptPushTokenTotal sumTotal = new FastGptPushTokenTotal();
        sumTotal.setCompanyName("合计"); // 假设有一个字段用于显示“合计”标签，具体字段名根据实际情况替换
        Long sum = list.stream().mapToLong(FastGptPushTokenTotal::getCount).sum(); // 假设有一个数字字段需要求和，具体字段名根据实际情况替换
        sumTotal.setCount(sum); // 设置合计值，具体字段名根据实际情况替换

        // 获取分页参数
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();

        int total = list.size();
        // 在内存中进行分页处理
        if (pageNum != null && pageSize != null) {
            int fromIndex = (pageNum - 1) * pageSize;
            int toIndex = Math.min(fromIndex + pageSize, total);

            // 确保索引不越界
            if (fromIndex < total) {
                list = list.subList(fromIndex, toIndex);
            } else {
                list = new ArrayList<>(); // 返回空列表
            }
        }



        list.add(sumTotal); // 将合计行添加到列表末尾

        // 构造返回结果
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(list);
        rspData.setTotal(total);
        return rspData;
    }
}
