package com.ruoyi.web.controller.wocom;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.CorpContextHolder;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.excel.wecom.domain.CustomerStatisticsDataV2;
import com.ruoyi.excel.wecom.domain.dto.TagTreeDTO;
import com.ruoyi.excel.wecom.service.ICustomerStatisticsDataV2Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * 客户统计数据V2 Controller
 * 支持标签级成本，行列转换存储
 */
@RestController
@RequestMapping("/wecom/customerStatisticsV2")
public class CustomerStatisticsDataV2Controller extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(CustomerStatisticsDataV2Controller.class);

    @Autowired
    private ICustomerStatisticsDataV2Service customerStatisticsDataV2Service;

    /**
     * 查询客户统计数据V2列表（支持按组、标签筛选，支持天/周/月维度）
     */
    @PreAuthorize("@ss.hasPermi('wecom:customerStatisticsV2:list')")
    @GetMapping("/list")
    public TableDataInfo list(
            @RequestParam(value = "dataType", required = false) String dataType,
            @RequestParam(value = "year", required = false) Integer year,
            @RequestParam(value = "week", required = false) Integer week,
            @RequestParam(value = "yearMonth", required = false) String yearMonth,
            @RequestParam(value = "startDate", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date startDate,
            @RequestParam(value = "endDate", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date endDate,
            @RequestParam(value = "groupName", required = false) String groupName,
            @RequestParam(value = "tagName", required = false) String tagName,
            @RequestParam(value = "onlyGroup", required = false) Boolean onlyGroup,
            @RequestParam(value = "onlyTag", required = false) Boolean onlyTag) {
        String corpId = CorpContextHolder.getCurrentCorpId();
        
        log.info("list接口被调用: dataType={}, year={}, week={}, yearMonth={}, groupName={}, tagName={}, onlyGroup={}, onlyTag={}", 
                dataType, year, week, yearMonth, groupName, tagName, onlyGroup, onlyTag);

        List<CustomerStatisticsDataV2> list;
        if ("week".equals(dataType)) {
            list = customerStatisticsDataV2Service.selectByWeekAggregation(corpId, year, week, groupName, tagName, onlyGroup, onlyTag);
            log.info("周聚合查询结果: {}条记录", list.size());
            return getDataTable(list);
        } else if ("month".equals(dataType)) {
            list = customerStatisticsDataV2Service.selectByMonthAggregation(corpId, yearMonth, groupName, tagName, onlyGroup, onlyTag);
            log.info("月聚合查询结果: {}条记录", list.size());
            return getDataTable(list);
        } else if ("all".equals(dataType)) {
            list = customerStatisticsDataV2Service.selectAllAggregation(corpId, groupName, tagName, onlyGroup, onlyTag);
            log.info("全部数据查询结果: {}条记录", list.size());
            return getDataTable(list);
        } else {
            startPage();
            list = customerStatisticsDataV2Service
                    .selectCustomerStatisticsDataV2List(corpId, startDate, endDate, groupName, tagName, onlyGroup, onlyTag);
            return getDataTable(list);
        }
    }

    /**
     * 查询标签树（只返回组-标签结构，不返回统计数据）
     * 用于前端左侧树状筛选面板
     */
    @PreAuthorize("@ss.hasPermi('wecom:customerStatisticsV2:tree')")
    @GetMapping("/tree")
    public AjaxResult tree(
            @RequestParam(value = "startDate", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date startDate,
            @RequestParam(value = "endDate", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date endDate) {
        String corpId = CorpContextHolder.getCurrentCorpId();
        List<TagTreeDTO> treeData = customerStatisticsDataV2Service
                .selectTagTree(corpId, startDate, endDate);
        return success(treeData);
    }

    /**
     * 导出客户统计数据V2列表
     */
    @PreAuthorize("@ss.hasPermi('wecom:customerStatisticsV2:export')")
    @Log(title = "客户统计数据V2", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response,
                       @RequestParam(value = "startDate", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date startDate,
                       @RequestParam(value = "endDate", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date endDate) {
        String corpId = CorpContextHolder.getCurrentCorpId();
        List<CustomerStatisticsDataV2> dataList = customerStatisticsDataV2Service
                .selectCustomerStatisticsDataV2List(corpId, startDate, endDate);
        ExcelUtil<CustomerStatisticsDataV2> util = new ExcelUtil<>(CustomerStatisticsDataV2.class);
        util.exportExcel(response, dataList, "流量看板数据V2");
    }

    /**
     * 获取客户统计数据V2详细信息
     */
    @PreAuthorize("@ss.hasPermi('wecom:customerStatisticsV2:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(customerStatisticsDataV2Service.selectCustomerStatisticsDataV2ById(id));
    }

    /**
     * 新增客户统计数据V2
     */
    @PreAuthorize("@ss.hasPermi('wecom:customerStatisticsV2:add')")
    @Log(title = "客户统计数据V2", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CustomerStatisticsDataV2 data) {
        return toAjax(customerStatisticsDataV2Service.insertCustomerStatisticsDataV2(data));
    }

    /**
     * 修改客户统计数据V2
     */
    @PreAuthorize("@ss.hasPermi('wecom:customerStatisticsV2:edit')")
    @Log(title = "客户统计数据V2", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CustomerStatisticsDataV2 data) {
        return toAjax(customerStatisticsDataV2Service.updateCustomerStatisticsDataV2(data));
    }

    /**
     * 删除客户统计数据V2
     */
    @PreAuthorize("@ss.hasPermi('wecom:customerStatisticsV2:remove')")
    @Log(title = "客户统计数据V2", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(customerStatisticsDataV2Service.deleteCustomerStatisticsDataV2ByIds(ids));
    }

    /**
     * 录入成本（支持组级和标签级）
     * @param date 日期
     * @param groupName 组名
     * @param tagName 标签名（为空表示组级）
     * @param costValue 成本值
     * @param inputType 录入类型：total-总成本，single-单条成本
     */
    @PreAuthorize("@ss.hasPermi('wecom:customerStatisticsV2:cost')")
    @Log(title = "客户统计数据V2-成本录入", businessType = BusinessType.UPDATE)
    @PostMapping("/cost")
    public AjaxResult inputCost(
            @RequestParam(value = "date") @DateTimeFormat(pattern = "yyyy-MM-dd") Date date,
            @RequestParam(value = "groupName") String groupName,
            @RequestParam(value = "tagName", required = false) String tagName,
            @RequestParam(value = "costValue") BigDecimal costValue,
            @RequestParam(value = "inputType") String inputType) {
        String corpId = CorpContextHolder.getCurrentCorpId();
        return toAjax(customerStatisticsDataV2Service.inputCost(
                corpId, date, groupName, tagName, costValue, inputType));
    }

    /**
     * 重新计算指定日期的统计数据
     */
    @PreAuthorize("@ss.hasPermi('wecom:customerStatisticsV2:recalculate')")
    @Log(title = "客户统计数据V2-重新计算", businessType = BusinessType.UPDATE)
    @PostMapping("/recalculate")
    public AjaxResult recalculate(
            @RequestParam(value = "date") @DateTimeFormat(pattern = "yyyy-MM-dd") Date date) {
        String corpId = CorpContextHolder.getCurrentCorpId();
        return toAjax(customerStatisticsDataV2Service.recalculateStatistics(corpId, date));
    }

    /**
     * 重新计算指定日期范围的统计数据
     */
    @PreAuthorize("@ss.hasPermi('wecom:customerStatisticsV2:recalculate')")
    @Log(title = "客户统计数据V2-重新计算", businessType = BusinessType.UPDATE)
    @PostMapping("/recalculateRange")
    public AjaxResult recalculateRange(
            @RequestParam(value = "startDate") @DateTimeFormat(pattern = "yyyy-MM-dd") Date startDate,
            @RequestParam(value = "endDate") @DateTimeFormat(pattern = "yyyy-MM-dd") Date endDate) {
        String corpId = CorpContextHolder.getCurrentCorpId();
        return toAjax(customerStatisticsDataV2Service.recalculateStatisticsRange(
                corpId, startDate, endDate));
    }
}
