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.DepartmentStatisticsData;
import com.ruoyi.excel.wecom.service.IDepartmentStatisticsDataService;
import com.ruoyi.excel.wecom.vo.DepartmentStatisticsDataVO;
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.math.RoundingMode;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 部门统计数据Controller
 */
@RestController
@RequestMapping("/wecom/departmentStatistics")
public class DepartmentStatisticsDataController extends BaseController {

    @Autowired
    private IDepartmentStatisticsDataService departmentStatisticsDataService;

    /**
     * 查询销售看板数据列表
     */
    @PreAuthorize("@ss.hasPermi('wecom:departmentStatistics:list')")
    @GetMapping("/list")
    public TableDataInfo list(
            @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 = "departmentPath", required = false) String departmentPath,
            @RequestParam(value = "dataType", required = false) String dataType,
            @RequestParam(value = "year", required = false) Integer year,
            @RequestParam(value = "week", required = false) Integer week,
            @RequestParam(value = "month", required = false) Integer month) {
        String corpId = CorpContextHolder.getCurrentCorpId();

        Date[] dateRange = calculateDateRange(dataType, year, week, month, startDate, endDate);
        startDate = dateRange[0];
        endDate = dateRange[1];

        startPage();
        List<DepartmentStatisticsData> list = departmentStatisticsDataService.selectDepartmentStatisticsDataList(corpId, startDate, endDate, departmentPath, dataType);
        return getDataTable(list);
    }

    /**
     * 导出销售看板数据列表
     */
    @PreAuthorize("@ss.hasPermi('wecom:departmentStatistics:export')")
    @Log(title = "销售看板数据", 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,
                       @RequestParam(value = "departmentPath", required = false) String departmentPath,
                       @RequestParam(value = "dataType", required = false) String dataType,
                       @RequestParam(value = "year", required = false) Integer year,
                       @RequestParam(value = "week", required = false) Integer week,
                       @RequestParam(value = "month", required = false) Integer month) {
        String corpId = CorpContextHolder.getCurrentCorpId();

        Date[] dateRange = calculateDateRange(dataType, year, week, month, startDate, endDate);
        startDate = dateRange[0];
        endDate = dateRange[1];

        List<DepartmentStatisticsDataVO> list = departmentStatisticsDataService.selectDepartmentStatisticsDataVOList(corpId, startDate, endDate, departmentPath, dataType);
        ExcelUtil<DepartmentStatisticsDataVO> util = new ExcelUtil<>(DepartmentStatisticsDataVO.class);
        util.exportExcel(response, list, "销售看板数据");
    }

    /**
     * 获取销售看板数据详细信息
     */
    @PreAuthorize("@ss.hasPermi('wecom:departmentStatistics:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(departmentStatisticsDataService.selectDepartmentStatisticsDataById(id));
    }


    /**
     * 查询销售看板数据列表
     */
    @PreAuthorize("@ss.hasPermi('wecom:departmentStatistics:list')")
    @GetMapping("/summary")
    public AjaxResult summary(
            @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 = "departmentPath", required = false) String departmentPath,
            @RequestParam(value = "dataType", required = false) String dataType,
            @RequestParam(value = "year", required = false) Integer year,
            @RequestParam(value = "week", required = false) Integer week,
            @RequestParam(value = "month", required = false) Integer month) {
        String corpId = CorpContextHolder.getCurrentCorpId();

        Date[] dateRange = calculateDateRange(dataType, year, week, month, startDate, endDate);
        startDate = dateRange[0];
        endDate = dateRange[1];
        Map<String, BigDecimal> map = departmentStatisticsDataService.getSummary(corpId, startDate, endDate, departmentPath, dataType);
        if(map == null) {
            return success(new HashMap<>());
        }
        BigDecimal totalOrders = map.get("totalOrders");
        BigDecimal totalIns = map.get("totalIns");
        if(totalOrders == null) {
            totalOrders = BigDecimal.ZERO;
        }
        if(totalIns == null) {
            totalIns = BigDecimal.ZERO;
        }
        if(totalIns.equals(BigDecimal.ZERO)) {
            map.put("penetrationRate",null);
        } else {
            map.put("penetrationRate",totalOrders.multiply(new BigDecimal(100))
                    .divide(totalIns,2, RoundingMode.HALF_UP)
                    .setScale(2, RoundingMode.HALF_UP));
        }
        return success(map);
    }

    /**
     * 根据数据类型计算日期范围
     * @param dataType 数据类型：week/month/all
     * @param year 年份
     * @param week 周数(1-53)
     * @param month 月份(1-12)
     * @param startDate 原始开始日期
     * @param endDate 原始结束日期
     * @return 日期数组[startDate, endDate]
     */
    private Date[] calculateDateRange(String dataType, Integer year, Integer week, Integer month, Date startDate, Date endDate) {
        if (dataType == null || dataType.isEmpty()) {
            return new Date[]{startDate, endDate};
        }
        
        if ("all".equals(dataType)) {
            return new Date[]{null, null};
        }
        
        Calendar cal = Calendar.getInstance();
        
        if ("week".equals(dataType) && year != null && week != null) {
            cal.set(Calendar.YEAR, year);
            cal.set(Calendar.WEEK_OF_YEAR, week);
            cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
            cal.set(Calendar.HOUR_OF_DAY, 0);
            cal.set(Calendar.MINUTE, 0);
            cal.set(Calendar.SECOND, 0);
            cal.set(Calendar.MILLISECOND, 0);
            startDate = cal.getTime();
            
            cal.add(Calendar.DAY_OF_MONTH, 6);
            endDate = cal.getTime();
            
            return new Date[]{startDate, endDate};
        }
        
        if ("month".equals(dataType) && year != null && month != null) {
            cal.set(Calendar.YEAR, year);
            cal.set(Calendar.MONTH, month - 1);
            cal.set(Calendar.DAY_OF_MONTH, 1);
            cal.set(Calendar.HOUR_OF_DAY, 0);
            cal.set(Calendar.MINUTE, 0);
            cal.set(Calendar.SECOND, 0);
            cal.set(Calendar.MILLISECOND, 0);
            startDate = cal.getTime();
            
            cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
            endDate = cal.getTime();
            
            return new Date[]{startDate, endDate};
        }
        
        return new Date[]{startDate, endDate};
    }
}
