package com.storlead.sales.controller.report;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.storlead.framework.common.constant.CommonConstant;
import com.storlead.framework.common.result.Result;
import com.storlead.framework.common.util.ConvertUtils;
import com.storlead.sales.pojo.dto.report.DashboardSketchDTO;
import com.storlead.sales.pojo.entity.report.DashboardSketchEntity;
import com.storlead.sales.pojo.vo.report.DashboardSketchDataVO;
import com.storlead.sales.pojo.vo.report.DashboardSketchPageVO;
import com.storlead.sales.pojo.vo.report.DashboardSketchVO;
import com.storlead.sales.service.DashboardSketchService;
import com.storlead.system.enums.OrganizationalTypeEnum;
import com.storlead.system.service.IUserRoleService;
import com.storlead.user.pojo.entity.DeptEntity;
import com.storlead.user.pojo.entity.SubCompanyEntity;
import com.storlead.user.pojo.entity.UserEntity;
import com.storlead.user.service.IDepartService;
import com.storlead.user.service.ISubCompanyService;
import com.storlead.user.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;

/**
 * @program: sp-sales-platform
 * @description:
 * @author: chenkq
 * @create: 2025-12-18 16:11
 */
@RestController
@RequestMapping("/dashboard/sketch")
@Api(tags = "报表: 数据播报")
public class DashboardSketchApiController {

    @Resource
    private IUserRoleService userRoleService;

    @Resource
    private DashboardSketchService dashboardSketchService;

    @Resource
    private IUserService userService;

    @Resource
    private IDepartService departService;

    @Resource
    private ISubCompanyService subCompanyService;

    @PostMapping(value = "/get_report")
    @ApiOperation(value = "获取报表: 数据播报-分页")
    public Result<IPage<DashboardSketchPageVO>> getReport(DashboardSketchDTO dto) {
        // 根据组织类型获取对应的数据权限范围
        OrganizationalTypeEnum scopeType = getDataScopeType(dto.getOrganizationType());
        Set<Long> dataScope = userRoleService.dataSelete(scopeType);

        // 处理数据权限筛选
        if (!CollectionUtils.isEmpty(dto.getOwnerByIds())) {
            if (!CollectionUtils.isEmpty(dataScope)) {
                dto.setOwnerByIds(ConvertUtils.retainByIds(dto.getOwnerByIds(), dataScope));
            }
        } else {
            dto.setOwnerByIds(List.copyOf(dataScope));
        }

        IPage<DashboardSketchPageVO> pageVO = new Page<>(dto.getPageIndex(), dto.getPageSize());
        IPage<DashboardSketchEntity> page = new Page<>(dto.getPageIndex(), dto.getPageSize());
        LambdaQueryWrapper<DashboardSketchEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DashboardSketchEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
        wrapper.eq(DashboardSketchEntity::getOrganizationType, dto.getOrganizationType());
        wrapper.in(!ObjectUtils.isEmpty(dto.getOrganizationIds()), DashboardSketchEntity::getOrganizationId, dto.getOrganizationIds());
        if(Integer.valueOf(40).equals(dto.getOrganizationType())) {
            if (!userRoleService.dataAllSelete(scopeType)) {
                return Result.result(pageVO);
            }
            wrapper.in(DashboardSketchEntity::getOrganizationId, 1);
        } else {
            if (CollectionUtils.isEmpty(dto.getOwnerByIds())) {
                return Result.result(pageVO);
            }
            wrapper.in(DashboardSketchEntity::getOrganizationId, dto.getOwnerByIds());
        }
        if (dto.getYear() != null){
            wrapper.eq(DashboardSketchEntity::getYear, dto.getYear());
        }
        if (dto.getMonth() != null){
            wrapper.eq(DashboardSketchEntity::getMonth, dto.getMonth());
        }
        if (dto.getCycle() != null){
            wrapper.eq(DashboardSketchEntity::getCycle, dto.getCycle());
        }
        if (dto.getSketchType() != null){
            wrapper.eq(DashboardSketchEntity::getSketchType, dto.getSketchType());
        }
        // 按 id 倒序展示
        wrapper.orderByDesc(DashboardSketchEntity::getId);
        IPage<DashboardSketchEntity> pageData = dashboardSketchService.page(page, wrapper);

        // 将数据复制到 pageVO 并补充上级组织名称
        List<DashboardSketchPageVO> voList = pageData.getRecords().stream().map(entity -> {
            DashboardSketchPageVO vo = new DashboardSketchPageVO();
            BeanUtils.copyProperties(entity, vo);

            // 根据 organizationType 补充上级组织名称
            if (entity.getOrganizationType() != null) {
                if (entity.getOrganizationType() == 10) {
                    // 个人类型：通过 organizationId 找到用户，获取部门和公司名称
                    UserEntity user = userService.getById(entity.getOrganizationId());
                    if (user != null && user.getDeptId() != null) {
                        DeptEntity dept = departService.getById(user.getDeptId());
                        if (dept != null) {
                            vo.setDeptName(dept.getName());
                            if (dept.getSubCompanyId() != null) {
                                SubCompanyEntity subCompany = subCompanyService.getById(dept.getSubCompanyId());
                                if (subCompany != null) {
                                    vo.setCompanyName(subCompany.getName());
                                }
                            }
                        }
                    }
                } else if (entity.getOrganizationType() == 20) {
                    // 部门类型：通过 organizationId 找到部门，获取公司名称
                    DeptEntity dept = departService.getById(entity.getOrganizationId());
                    if (dept != null && dept.getSubCompanyId() != null) {
                        SubCompanyEntity subCompany = subCompanyService.getById(dept.getSubCompanyId());
                        if (subCompany != null) {
                            vo.setCompanyName(subCompany.getName());
                        }
                    }
                }
            }

//            vo.setSketchDataJson(null);

            // 设置简报名称和周期名称
            vo.setSketchName(getSketchName(entity.getSketchType()));
            vo.setCycleName(getCycleName(entity.getYear(), entity.getMonth(), entity.getCycle(), entity.getSketchType()));

            return vo;
        }).collect(java.util.stream.Collectors.toList());

        pageVO.setRecords(voList);
        pageVO.setTotal(pageData.getTotal());
        pageVO.setPages(pageData.getPages());
        pageVO.setCurrent(pageData.getCurrent());
        pageVO.setSize(pageData.getSize());

        return Result.result(pageVO);
    }

    @PostMapping(value = "/get_report_total")
    @ApiOperation(value = "获取报表: 数据播报-数据总和")
    public Result<DashboardSketchVO> getReportTotal(DashboardSketchDTO dto) {
        // 根据组织类型获取对应的数据权限范围
        OrganizationalTypeEnum scopeType = getDataScopeType(dto.getOrganizationType());
        Set<Long> dataScope = userRoleService.dataSelete(scopeType);

        // 处理数据权限筛选
        if (!CollectionUtils.isEmpty(dto.getOwnerByIds())) {
            if (!CollectionUtils.isEmpty(dataScope)) {
                dto.setOwnerByIds(ConvertUtils.retainByIds(dto.getOwnerByIds(), dataScope));
            }
        } else {
            dto.setOwnerByIds(List.copyOf(dataScope));
        }
        LambdaQueryWrapper<DashboardSketchEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DashboardSketchEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
        wrapper.eq(DashboardSketchEntity::getOrganizationType, dto.getOrganizationType());
        wrapper.in(!ObjectUtils.isEmpty(dto.getOrganizationIds()), DashboardSketchEntity::getOrganizationId, dto.getOrganizationIds());
        wrapper.in(DashboardSketchEntity::getOrganizationId, dto.getOwnerByIds());
        if (dto.getYear() != null){
            wrapper.eq(DashboardSketchEntity::getYear, dto.getYear());
        }
        if (dto.getMonth() != null){
            wrapper.eq(DashboardSketchEntity::getMonth, dto.getMonth());
        }
        if (dto.getCycle() != null){
            wrapper.eq(DashboardSketchEntity::getCycle, dto.getCycle());
        }
        if (dto.getSketchType() != null){
            wrapper.eq(DashboardSketchEntity::getSketchType, dto.getSketchType());
        }
        if(Integer.valueOf(40).equals(dto.getOrganizationType())) {
            if (!userRoleService.dataAllSelete(scopeType)) {
                DashboardSketchVO vo = new DashboardSketchVO();
                return Result.result(vo);
            }
            wrapper.in(DashboardSketchEntity::getOrganizationId, 1);
        } else {
            if (CollectionUtils.isEmpty(dto.getOwnerByIds())) {
                DashboardSketchVO vo = new DashboardSketchVO();
                return Result.result(vo);
            }
            wrapper.in(DashboardSketchEntity::getOrganizationId, dto.getOwnerByIds());
        }
        List<DashboardSketchEntity> pageData = dashboardSketchService.list(wrapper);
        DashboardSketchVO vo = DashboardSketchVO.totalDataByListVo(pageData);
        return Result.result(vo);
    }

    @PostMapping(value = "/get_sketch_data")
    @ApiOperation(value = "按 id 获取 sketchDataJson 字段")
    public Result<DashboardSketchDataVO> getSketchData(DashboardSketchDTO dto) {
        // 根据组织类型获取对应的数据权限范围
        OrganizationalTypeEnum scopeType = getDataScopeType(dto.getOrganizationType());
        Set<Long> dataScope = userRoleService.dataSelete(scopeType);

        // 处理数据权限筛选
        if (!CollectionUtils.isEmpty(dto.getOwnerByIds())) {
            if (!CollectionUtils.isEmpty(dataScope)) {
                dto.setOwnerByIds(ConvertUtils.retainByIds(dto.getOwnerByIds(), dataScope));
            }
        } else {
            dto.setOwnerByIds(List.copyOf(dataScope));
        }
        if (dto == null || ObjectUtils.isEmpty(dto.getId())) {
            return Result.error(null, "id不能为空");
        }
        DashboardSketchEntity entity = dashboardSketchService.getById(dto.getId());
        // 查询上一个（按 id 倒序列表中的上一条：id 大于当前 id 中最接近的那条）
        LambdaQueryWrapper<DashboardSketchEntity> prevWrapper = new LambdaQueryWrapper<>();
        prevWrapper.eq(DashboardSketchEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
        prevWrapper.eq(DashboardSketchEntity::getOrganizationType, entity.getOrganizationType());
        if (dto.getYear() != null) {
            prevWrapper.eq(DashboardSketchEntity::getYear, dto.getYear());
        }
        if (dto.getMonth() != null) {
            prevWrapper.eq(DashboardSketchEntity::getMonth, entity.getMonth());
        }
        if (dto.getCycle() != null) {
            prevWrapper.eq(DashboardSketchEntity::getCycle, entity.getCycle());
        }
        if(Integer.valueOf(40).equals(dto.getOrganizationType())) {
            if (!userRoleService.dataAllSelete(scopeType)) {
                DashboardSketchDataVO vo = new DashboardSketchDataVO();
                return Result.result(vo);
            }
            prevWrapper.in(DashboardSketchEntity::getOrganizationId, 1);
        } else {
            if (CollectionUtils.isEmpty(dto.getOwnerByIds())) {
                DashboardSketchDataVO vo = new DashboardSketchDataVO();
                return Result.result(vo);
            }
            prevWrapper.in(DashboardSketchEntity::getOrganizationId, dto.getOwnerByIds());
        }

        if (!ObjectUtils.isEmpty(dto.getOrganizationIds())) {
            prevWrapper.in(DashboardSketchEntity::getOrganizationId, dto.getOrganizationIds());
        }
        if (dto.getSketchType() != null) {
            prevWrapper.eq(DashboardSketchEntity::getSketchType, dto.getSketchType());
        }
        // 获取 id 大于当前 id 的最小值（在 id 倒序中位于当前之前）
        prevWrapper.gt(DashboardSketchEntity::getId, entity.getId());
        prevWrapper.orderByAsc(DashboardSketchEntity::getId);
        prevWrapper.in(DashboardSketchEntity::getOrganizationId, dto.getOwnerByIds());
        prevWrapper.last("LIMIT 1");
        List<DashboardSketchEntity> prevList = dashboardSketchService.list(prevWrapper);
        Long prevId = (prevList == null || prevList.isEmpty()) ? null : prevList.get(0).getId();

        // 查询下一个（在 id 倒序中位于当前之后：id 小于当前 id 的最大值）
        LambdaQueryWrapper<DashboardSketchEntity> nextWrapper = new LambdaQueryWrapper<>();
        nextWrapper.eq(DashboardSketchEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
        nextWrapper.eq(DashboardSketchEntity::getOrganizationType, entity.getOrganizationType());
        if (dto.getYear() != null) {
            nextWrapper.eq(DashboardSketchEntity::getYear, dto.getYear());
        }
        if (dto.getMonth() != null)
            nextWrapper.eq(DashboardSketchEntity::getMonth, entity.getMonth());
        if (dto.getCycle() != null) {
            nextWrapper.eq(DashboardSketchEntity::getCycle, entity.getCycle());
        }

        if(Integer.valueOf(40).equals(dto.getOrganizationType())) {
            if (!userRoleService.dataAllSelete(scopeType)) {
                DashboardSketchDataVO vo = new DashboardSketchDataVO();
                return Result.result(vo);
            }
            nextWrapper.in(DashboardSketchEntity::getOrganizationId, 1);
        } else {
            if (CollectionUtils.isEmpty(dto.getOwnerByIds())) {
                DashboardSketchDataVO vo = new DashboardSketchDataVO();
                return Result.result(vo);
            }
            nextWrapper.in(DashboardSketchEntity::getOrganizationId, dto.getOwnerByIds());
        }
        if (!ObjectUtils.isEmpty(dto.getOrganizationIds())){
            nextWrapper.in(DashboardSketchEntity::getOrganizationId, dto.getOrganizationIds());
        }
        nextWrapper.lt(DashboardSketchEntity::getId, entity.getId());
        if (dto.getSketchType() != null){
            nextWrapper.eq(DashboardSketchEntity::getSketchType, dto.getSketchType());
        }
        nextWrapper.orderByDesc(DashboardSketchEntity::getId);
        nextWrapper.in(DashboardSketchEntity::getOrganizationId, dto.getOwnerByIds());
        nextWrapper.last("LIMIT 1");
        List<DashboardSketchEntity> nextList = dashboardSketchService.list(nextWrapper);
        Long nextId = (nextList == null || nextList.isEmpty()) ? null : nextList.get(0).getId();

        DashboardSketchDataVO vo = new DashboardSketchDataVO();
        vo.setSketchDataJson(entity.getSketchDataJson());
        vo.setPrevId(prevId);
        vo.setNextId(nextId);
        return Result.result(vo);
    }

    /**
     * 根据组织类型获取对应的数据权限范围类型
     * @param organizationType 组织类型
     * @return 数据权限范围类型
     */
    private OrganizationalTypeEnum getDataScopeType(Integer organizationType) {
        if (organizationType == null) {
            return OrganizationalTypeEnum.USER_GROUP; // 默认使用用户组权限
        }

        switch (organizationType) {
            case 10: // 个人类型
                return OrganizationalTypeEnum.USER_GROUP;
            case 20: // 部门类型
                return OrganizationalTypeEnum.DEPT_GROUP;
            case 30: // 分公司类型
                return OrganizationalTypeEnum.SUB_COMPANY_GROUP;
            default:
                return OrganizationalTypeEnum.USER_GROUP; // 默认使用用户组权限
        }
    }

    /**
     * 根据简报类型获取简报名称
     * @param sketchType 简报类型
     * @return 简报名称
     */
    private String getSketchName(Integer sketchType) {
        if (sketchType == null) {
            return "";
        }

        switch (sketchType) {
            case 10:
                return "周报";
            case 20:
                return "月报";
            case 30:
                return "季度";
            case 40:
                return "半年度";
            case 50:
                return "年度";
            default:
                return "";
        }
    }

    /**
     * 根据年月周期和简报类型生成周期名称
     * @param year 年
     * @param month 月
     * @param cycle 周期
     * @param sketchType 简报类型
     * @return 周期名称
     */
    private String getCycleName(Integer year, Integer month, Integer cycle, Integer sketchType) {
        if (sketchType == null || year == null) {
            return "";
        }

        switch (sketchType) {
            case 10: // 周报：year年month月第cycle周
                if (month != null && cycle != null) {
                    return year + "年" + month + "月第" + cycle + "周";
                }
                return year + "年";
            case 20: // 月报：year年month月
                if (month != null) {
                    return year + "年" + month + "月";
                }
                return year + "年";
            case 30: // 季度：year年cycle季度
                if (cycle != null) {
                    return year + "年" + cycle + "季度";
                }
                return year + "年";
            case 40: // 半年度：year年上半年/下半年
                if (cycle != null) {
                    if (cycle == 1) {
                        return year + "年上半年";
                    } else if (cycle == 2) {
                        return year + "年下半年";
                    }
                }
                return year + "年";
            case 50: // 年度：year年
                return year + "年";
            default:
                return "";
        }
    }

}
