package com.zsElectric.boot.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zsElectric.boot.business.mapper.FirmAccountLogMapper;
import com.zsElectric.boot.business.model.entity.FirmAccountLog;
import com.zsElectric.boot.business.model.entity.FirmInfo;
import com.zsElectric.boot.business.model.query.FirmAccountLogQuery;
import com.zsElectric.boot.business.model.vo.FirmAccountLogVO;
import com.zsElectric.boot.business.service.FirmAccountLogService;
import com.zsElectric.boot.business.service.FirmInfoService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import cn.hutool.core.util.StrUtil;
import com.zsElectric.boot.security.util.SecurityUtils;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 企业资金流水服务实现类
 *
 * @author zsElectric
 * @since 2025-12-26
 */
@Service
@RequiredArgsConstructor
public class FirmAccountLogServiceImpl extends ServiceImpl<FirmAccountLogMapper, FirmAccountLog> implements FirmAccountLogService {

    /**
     * 三方用户角色编码
     */
    private static final String ROLE_SFUSER = "SFUSER";

    private final FirmInfoService firmInfoService;

    @Override
    public IPage<FirmAccountLogVO> getFirmAccountLogPage(FirmAccountLogQuery queryParams) {
        // 判断当前用户是否为三方用户，如果是则只查询自己所属公司的数据
        Set<String> roles = SecurityUtils.getRoles();
        if (roles != null && roles.contains(ROLE_SFUSER)) {
            // 三方用户只能查询自己所属部门关联的企业数据
            Long deptId = SecurityUtils.getDeptId();
            Long firmId = firmInfoService.getFirmIdByDeptId(deptId);
            queryParams.setFirmId(firmId);
        }
        Page<FirmAccountLog> page = new Page<>(queryParams.getPageNum(), queryParams.getPageSize());

        LambdaQueryWrapper<FirmAccountLog> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(queryParams.getFirmId() != null, FirmAccountLog::getFirmId, queryParams.getFirmId())
                .eq(queryParams.getFirmType() != null, FirmAccountLog::getFirmType, queryParams.getFirmType())
                .eq(queryParams.getIncomeType() != null, FirmAccountLog::getIncomeType, queryParams.getIncomeType())
                .eq(queryParams.getChangeType() != null, FirmAccountLog::getChangeType, queryParams.getChangeType())
                .like(StrUtil.isNotBlank(queryParams.getSerialNo()), FirmAccountLog::getSerialNo, queryParams.getSerialNo())
                .like(StrUtil.isNotBlank(queryParams.getName()), FirmAccountLog::getName, queryParams.getName())
                .orderByDesc(FirmAccountLog::getCreateTime);

        IPage<FirmAccountLog> entityPage = this.page(page, queryWrapper);

        // 转换为VO
        IPage<FirmAccountLogVO> voPage = entityPage.convert(entity -> {
            FirmAccountLogVO vo = new FirmAccountLogVO();
            vo.setId(entity.getId());
            vo.setFirmId(entity.getFirmId());
            vo.setProjectName(entity.getProjectName());
            vo.setName(entity.getName());
            vo.setSerialNo(entity.getSerialNo());
            vo.setIncomeType(entity.getIncomeType());
            vo.setBeforeChange(entity.getBeforeChange());
            vo.setAfterChange(entity.getAfterChange());
            vo.setMoneyChange(entity.getMoneyChange());
            vo.setChangeType(entity.getChangeType());
            vo.setChildId(entity.getChildId());
            vo.setRemark(entity.getRemark());
            vo.setCreateTime(entity.getCreateTime());
            return vo;
        });

        // 填充企业名称和类型
        List<Long> firmIds = voPage.getRecords().stream()
                .map(FirmAccountLogVO::getFirmId)
                .distinct()
                .collect(Collectors.toList());

        if (!firmIds.isEmpty()) {
            Map<Long, FirmInfo> firmInfoMap = firmInfoService.listByIds(firmIds).stream()
                    .collect(Collectors.toMap(FirmInfo::getId, firm -> firm));
            voPage.getRecords().forEach(vo -> {
                FirmInfo firmInfo = firmInfoMap.get(vo.getFirmId());
                if (firmInfo != null) {
                    vo.setFirmName(firmInfo.getName());
                    vo.setFirmType(firmInfo.getFirmType() != null ? firmInfo.getFirmType() : 1);
                }
            });
        }

        return voPage;
    }

    @Override
    public boolean deleteFirmAccountLogs(String ids) {
        List<Long> idList = Arrays.stream(ids.split(","))
                .map(Long::valueOf)
                .collect(Collectors.toList());
        return this.removeByIds(idList);
    }
}
