package com.sundot.airport.web.controller.portrait;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.sundot.airport.common.core.controller.BaseController;
import com.sundot.airport.common.core.domain.AjaxResult;
import com.sundot.airport.common.core.domain.entity.SysDept;
import com.sundot.airport.common.core.domain.entity.SysUser;
import com.sundot.airport.common.domain.portrait.IndicatorCalculateParams;
import com.sundot.airport.common.domain.portrait.ModularIndicatorResult;
import com.sundot.airport.common.dto.UserInfo;
import com.sundot.airport.common.enums.DeptTypeEnum;
import com.sundot.airport.common.enums.RoleTypeEnum;
import com.sundot.airport.common.enums.portrait.UserType;
import com.sundot.airport.system.mapper.SysUserMapper;
import com.sundot.airport.system.service.ISysDeptService;
import com.sundot.airport.system.service.portrait.UserPortraitService;
import com.sundot.airport.web.core.cache.UserCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 用户画像基本信息
 */
@RestController
@RequestMapping("/user/basic/portrait")
public class UserBasicPortraitController extends BaseController {

    @Autowired
    private UserPortraitService userPortraitService;

    @Autowired
    private UserCache userCache;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private ISysDeptService sysDeptService;


    /**
     * 获取指定模块的指标值
     *
     * @param modules 指定的模块列表，用逗号分隔
     * @return 指定模块的指标值集合
     */
    @Cacheable(
            value = "base_module_info",
            keyGenerator = "statisticsKeyGenerator",
            unless = "!T(com.sundot.airport.common.cache.StatisticsCacheConditionUtil).isSuccess(#result) ||T(com.sundot.airport.common.cache.StatisticsCacheConditionUtil).isEmptyData(#result)"
    )
    @GetMapping("/module/info")
    public AjaxResult moduleInfo(IndicatorCalculateParams params,
                                 @RequestParam(required = false) String modules) {
        ModularIndicatorResult result = new ModularIndicatorResult();
        try {
            // 将字符串转换为枚举
            UserType userTypeEnum = UserType.fromString(params.getUserTypeStr());
            params.setUserType(userTypeEnum);

            // 设置默认时间范围
            java.util.Date endTime = Optional.ofNullable(params.getEndTime()).orElse(new java.util.Date());
            java.util.Date startTime = Optional.ofNullable(params.getStartTime())
                    .orElse(java.util.Date.from(endTime.toInstant().minusSeconds(7862400L)));
            params.setStartTime(startTime);
            params.setEndTime(endTime);
            if (!UserType.PERSONAL.equals(userTypeEnum)) {
                if (ObjectUtil.isNotEmpty(params.getUserId()) && ObjectUtil.isEmpty(params.getDeptId())) {
                    SysUser user = sysUserMapper.selectUserById(params.getUserId());
                    if (ObjectUtil.isEmpty(user)) {
                        return AjaxResult.success(result);
                    }
                    params.setDeptId(user.getDeptId());
                }
                // 根据这个人的部门id，获取这个人部门下的所有安检员和班组长
                List<SysUser> deptUsers = new ArrayList<>();
                if (params.getDeptId() != null) {
                    deptUsers = sysUserMapper.selectUserListByRoleKeyAndDeptId(
                            Arrays.asList(RoleTypeEnum.banzuzhang.getCode(), RoleTypeEnum.SecurityCheck.getCode()),
                            params.getDeptId());
                    if (CollectionUtil.isEmpty(deptUsers)) {
                        return AjaxResult.success(result);
                    }
                }
                if (CollectionUtil.isEmpty(deptUsers)) {
                    return AjaxResult.success(result);
                }
                List<Long> userIds = deptUsers.stream()
                        .map(SysUser::getUserId)
                        .collect(Collectors.toList());
                if (CollectionUtil.isEmpty(userIds)) {
                    return AjaxResult.success(result);
                }
                params.setUserIds(userIds);
            }


            if (modules != null && !modules.isEmpty()) {
                // 解析模块列表
                List<String> moduleList = Arrays.asList(modules.split(","));
                result = userPortraitService.getIndicators(params, moduleList);
            } else {
                // 获取所有模块的指标数据
                result = userPortraitService.getIndicators(params);
            }

            return AjaxResult.success(result);
        } catch (Exception e) {
            return AjaxResult.error("获取用户画像信息失败：" + e.getMessage());
        }
    }

}