package com.ruoyi.web.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecureSensitiveUtils;
import com.ruoyi.web.domain.dto.subsidyProjects.SubsidyProjectsAddRequest;
import com.ruoyi.web.domain.dto.subsidyProjects.SubsidyProjectsEditRequest;
import com.ruoyi.web.domain.dto.subsidyProjects.SubsidyProjectsQueryRequest;
import com.ruoyi.web.domain.entity.SubsidyProjects;
import com.ruoyi.web.domain.vo.SubsidyProjectsVO;
import com.ruoyi.web.mapper.SubsidyProjectsMapper;
import com.ruoyi.web.service.PersonInfoService;
import com.ruoyi.web.service.SubsidyProjectsService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 惠农补贴服务
 */
@Service
public class SubsidyProjectsServiceImpl extends ServiceImpl<SubsidyProjectsMapper, SubsidyProjects>
        implements SubsidyProjectsService {

    @Autowired
    private PersonInfoService personInfoService;

    /**
     * 添加
     *
     * @param subsidyProjectsAddRequest
     * @return
     */
    @Override
    public Long addSubsidyProjects(SubsidyProjectsAddRequest subsidyProjectsAddRequest) {
        if (subsidyProjectsAddRequest == null) {
            throw new ServiceException("请求参数为空");
        }
        try {
            // 转换为实体对象
            SubsidyProjects subsidyProjects = new SubsidyProjects();
            BeanUtil.copyProperties(subsidyProjectsAddRequest, subsidyProjects);
            //数据校验
            validSubsidyProjects(subsidyProjects, BusinessType.INSERT);

            // 保存到数据库
            this.save(subsidyProjects);
            return subsidyProjects.getId();
        } catch (Exception e) {
            log.error("添加惠农补贴项目失败", e);
            throw new ServiceException("添加惠农补贴项目失败");
        }
    }

    /**
     * 删除
     *
     * @param ids
     * @return
     */
    @Override
    public boolean deleteSubsidyProjects(String ids) {
        if (StrUtil.isBlank(ids)) {
            throw new ServiceException("id不能为空或id异常");
        }

        // 2. 分割ID字符串为List<Integer>
        List<Long> idList = Arrays.stream(ids.split(","))
                .map(String::trim)
                .filter(StrUtil::isNotBlank)
                .map(Long::parseLong)
                .collect(Collectors.toList());

        if (idList.isEmpty()) {
            throw new ServiceException("ID格式异常");
        }

        // 3. 构建删除条件
        QueryWrapper<SubsidyProjects> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", idList);

        // 4. 执行删除（返回是否删除成功）
        return remove(queryWrapper);

    }

    /**
     * 编辑
     *
     * @param subsidyProjectsEditRequest
     */
    @Override
    public void editSubsidyProjects(SubsidyProjectsEditRequest subsidyProjectsEditRequest) {
        // 判断是否存在
        Integer id = subsidyProjectsEditRequest.getId();
        SubsidyProjects oldSubsidyProjects = this.getById(id);
        if (oldSubsidyProjects == null) {
            throw new ServiceException("没有找到惠农补贴");
        }
        SubsidyProjects subsidyProjects = new SubsidyProjects();
        BeanUtil.copyProperties(subsidyProjectsEditRequest, subsidyProjects);
        subsidyProjects.setUpdateTime(new Date());
        // 对身份证 和 银行账户 进行加密
        //String idCard = subsidyProjects.getIdCard();
        String bankCard = subsidyProjects.getBankCard();
        //subsidyProjects.setIdCard(personInfoService.encryptIdCard(idCard));
        try {
            bankCard = SecureSensitiveUtils.encrypt(bankCard, SecureSensitiveUtils.generateAesKey());
        } catch (Exception e) {
            throw new ServiceException("银行账号加密失败");
        }
        subsidyProjects.setBankCard(bankCard);
        // 数据校验
        validSubsidyProjects(subsidyProjects, BusinessType.UPDATE);
        // 操作数据库
        boolean result = this.updateById(subsidyProjects);
        if (!result) {
            throw new ServiceException("修改补贴项目操作失败");
        }
    }

    /**
     * 校验惠农补贴
     *
     * @param subsidyProjects
     */
    public void validSubsidyProjects(SubsidyProjects subsidyProjects, BusinessType type) {
        if (ObjectUtil.isEmpty(subsidyProjects)) {
            throw new ServiceException("数据为空");
        }
        // 从对象中取值
        Long id = subsidyProjects.getId();
        String projectName = subsidyProjects.getProjectName();
        String category = subsidyProjects.getCategory();
        String name = subsidyProjects.getName();
        String idCard = subsidyProjects.getIdCard();
        BigDecimal money = subsidyProjects.getMoney();
        String bankCard = subsidyProjects.getBankCard();
        Date date = subsidyProjects.getDate();
        String status = subsidyProjects.getStatus();

        // 添加id无需校验，修改时，id 不能为空
        if (type != BusinessType.INSERT && ObjectUtil.isEmpty(id)) {
            throw new ServiceException("id不能为空");
        }
        if (StrUtil.isBlank(projectName)) {
            throw new ServiceException("项目名称不能为空");
        }
        if (StrUtil.isBlank(category)) {
            throw new ServiceException("补贴类别不能为空");
        }
        if (StrUtil.isBlank(name)) {
            throw new ServiceException("姓名不能为空");
        }
        if (StrUtil.isBlank(idCard)) {
            throw new ServiceException("身份证不能为空");
        }
        if (ObjectUtil.isEmpty(money)) {
            throw new ServiceException("实发金额不能为空");
        }
        if (StrUtil.isBlank(bankCard)) {
            throw new ServiceException("银行账号不能为空");
        }
        if (ObjectUtil.isEmpty(date)) {
            throw new ServiceException("兑换不能为空");
        }
        if (StrUtil.isBlank(status)) {
            throw new ServiceException("状态不能为空");
        }
    }


    /**
     * 根据id获取补贴项目
     *
     * @param id
     * @return
     */
    @Override
    public SubsidyProjectsVO getSubsidyProjectsById(int id) {
        if (id <= 0 || ObjectUtil.isEmpty(id)) {
            throw new ServiceException("id不能为空或id异常");
        }
        SubsidyProjects subsidyProjects = this.getById(id);
//        String bankCard = null;
//        String idCard = null;
//        // 解密
//        //idCard = personInfoService.decryptIdCard(subsidyProject.getIdCard());
//        idCard = subsidyProject.getIdCard();
//        try {
//            bankCard = SecureSensitiveUtils.decrypt(subsidyProject.getBankCard(), SecureSensitiveUtils.generateAesKey());
//        } catch (Exception e) {
//            log.error("银行号码解密异常" + e.getMessage());
//            throw new ServiceException("银行号码解密异常");
//        }
//        subsidyProject.setIdCard(idCard);
//        subsidyProject.setBankCard(bankCard);
        if (subsidyProjects==null){
            throw new ServiceException("未找到补贴");
        }
        SubsidyProjectsVO subsidyProjectsVO = new SubsidyProjectsVO();
        BeanUtil.copyProperties(subsidyProjects,subsidyProjectsVO);
        return subsidyProjectsVO;
    }

    /**
     * 分页获取补贴-项目列表
     *
     * @param subsidyProjectsQueryRequest
     * @return
     */
    @Override
    public Page<SubsidyProjectsVO> getListSubsidyProjectsByPage(SubsidyProjectsQueryRequest subsidyProjectsQueryRequest) {
        long current = subsidyProjectsQueryRequest.getPageNum();
        long size = subsidyProjectsQueryRequest.getPageSize();
        Page<SubsidyProjects> page = this.page(new Page<>(current, size),
                getQueryWrapper(subsidyProjectsQueryRequest));

        Page<SubsidyProjectsVO> voPage = new Page<>(current, size);
        voPage.setTotal(page.getTotal());


        // 处理每条记录
        if (page.getRecords() != null && !page.getRecords().isEmpty()) {
            List<SubsidyProjectsVO> voRecords = page.getRecords().stream()
                    .map(subsidyProjects -> {
                        SubsidyProjectsVO vo = new SubsidyProjectsVO();
                        BeanUtil.copyProperties(subsidyProjects, vo);
//                // 解密-> 身份证 & 银行号码
//                String bankCard = null;
//                String idCard = null;
//                try {
//                    // 解密
//                    //idCard = personInfoService.decryptIdCard(subsidyProjects.getIdCard());
//                    idCard = subsidyProjects.getIdCard();
//                    bankCard = SecureSensitiveUtils.decrypt(subsidyProjects.getBankCard(), SecureSensitiveUtils.generateAesKey());
//                    subsidyProjects.setIdCard(idCard);
//                    subsidyProjects.setBankCard(bankCard);
//                } catch (Exception e) {
//                    throw new RuntimeException(e.getMessage());
//                }
                return vo;
            }).collect(Collectors.toList());
            voPage.setRecords(voRecords);
        }
        return voPage;
    }

    /**
     * 获取查询条件
     *
     * @param subsidyProjectsQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<SubsidyProjects> getQueryWrapper(SubsidyProjectsQueryRequest subsidyProjectsQueryRequest) {
        QueryWrapper<SubsidyProjects> queryWrapper = new QueryWrapper<>();
        if (subsidyProjectsQueryRequest == null) {
            return queryWrapper;
        }

        // 从对象中取值
        Integer id = subsidyProjectsQueryRequest.getId();
        String category = subsidyProjectsQueryRequest.getCategory();
        String name = subsidyProjectsQueryRequest.getName();
        String idCard = subsidyProjectsQueryRequest.getIdCard();
        Date startTime = subsidyProjectsQueryRequest.getStartTime();
        Date endTime = subsidyProjectsQueryRequest.getEndTime();
        String status = subsidyProjectsQueryRequest.getStatus();
        String sortField = subsidyProjectsQueryRequest.getSortField();
        String sortOrder = subsidyProjectsQueryRequest.getSortOrder();


        // 项目名称、项目描述 项目进度
        queryWrapper.eq(ObjectUtil.isNotEmpty(id), "id", id);
        queryWrapper.eq(StrUtil.isNotBlank(category), "category", category);
        queryWrapper.like(StringUtils.isNotBlank(name), "name", name);
        queryWrapper.eq(StringUtils.isNotBlank(idCard), "idCard", idCard);
        // 日期范围查询（优先判断范围）
        if (startTime != null && endTime != null) {
            queryWrapper.between("date", startTime, endTime);
        } else if (startTime != null) {
            queryWrapper.ge("date", startTime); // >= 开始日期
        } else if (endTime != null) {
            queryWrapper.le("date", endTime);   // <= 结束日期
        }
        queryWrapper.eq(StringUtils.isNotBlank(status), "status", status);

        // 排序
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), "ascend".equals(sortOrder), sortField);
        return queryWrapper;
    }
}




