package org.dromara.zjk.expert.expertRecommend.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.constant.UserConstants;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.zjk.domain.ZjkExpert;
import org.dromara.zjk.domain.vo.ZjkProductVo;
import org.dromara.zjk.enums.ZjkExpertTypeEnum;
import org.dromara.zjk.expert.expertRecommend.domain.ZjkExpertRecommend;
import org.dromara.zjk.expert.expertRecommend.domain.bo.ZjkExpertRecommendBo;
import org.dromara.zjk.expert.expertRecommend.domain.vo.ZjkExpertRecommendVo;
import org.dromara.zjk.expert.expertRecommend.mapper.ZjkExpertRecommendMapper;
import org.dromara.zjk.expert.expertRecommend.service.IZjkExpertRecommendService;
import org.dromara.zjk.mapper.ZjkExpertMapper;
import org.dromara.zjk.zwy.client.HmacClient;
import org.dromara.zjk.zwy.utils.ObjectHashGenerator;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * 专家推荐信息Service业务层处理
 *
 * @author zhangzhou
 * @date 2024-11-10
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class ZjkExpertRecommendServiceImpl implements IZjkExpertRecommendService {

    private final ZjkExpertRecommendMapper baseMapper;

    private final ZjkExpertMapper zjkExpertMapper;

    private final HmacClient hmacClient;

    /**
     * 查询专家推荐信息
     *
     * @param id 主键
     * @return 专家推荐信息
     */
    @Override
    public ZjkExpertRecommendVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询专家推荐信息列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 专家推荐信息分页列表
     */
    @Override
    public TableDataInfo<ZjkExpertRecommendVo> queryPageList(ZjkExpertRecommendBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ZjkExpertRecommend> lqw = buildQueryWrapper(bo);
        Page<ZjkExpertRecommendVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    @Override
    public TableDataInfo<ZjkExpertRecommendVo> queryExpertRecommendList(ZjkExpertRecommendBo bo, PageQuery pageQuery) {
        // 获取用户 Id专家 id
        if (bo.getExpertId() == null && bo.getUserId() == null) {
            bo.setUserId(LoginHelper.getUserId());
            ZjkExpert existingExpert = zjkExpertMapper.selectOne(
                new LambdaQueryWrapper<ZjkExpert>()
                    .eq(ZjkExpert::getUserId, LoginHelper.getUserId())
                    .eq(ZjkExpert::getDeleteFlag, UserConstants.DEL_FLAG_NORMAL)
            );
            if (existingExpert == null) {
                return TableDataInfo.build(new ArrayList<>());
            }
            bo.setExpertId(existingExpert.getExpertId());
        }
        LambdaQueryWrapper<ZjkExpertRecommend> lqw = buildQueryWrapper(bo);
        Page<ZjkExpertRecommendVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的专家推荐信息列表
     *
     * @param bo 查询条件
     * @return 专家推荐信息列表
     */
    @Override
    public List<ZjkExpertRecommendVo> queryList(ZjkExpertRecommendBo bo) {
        LambdaQueryWrapper<ZjkExpertRecommend> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ZjkExpertRecommend> buildQueryWrapper(ZjkExpertRecommendBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ZjkExpertRecommend> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getExpertId() != null, ZjkExpertRecommend::getExpertId, bo.getExpertId());
        lqw.eq(bo.getUserId() != null, ZjkExpertRecommend::getUserId, bo.getUserId());
        lqw.like(StringUtils.isNotBlank(bo.getExpertName()), ZjkExpertRecommend::getExpertName, bo.getExpertName());
        lqw.like(StringUtils.isNotBlank(bo.getExpertPhone()), ZjkExpertRecommend::getExpertPhone, bo.getExpertPhone());
        lqw.eq(StringUtils.isNotBlank(bo.getReason()), ZjkExpertRecommend::getReason, bo.getReason());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), ZjkExpertRecommend::getStatus, bo.getStatus());
        lqw.orderByDesc(ZjkExpertRecommend::getCreateTime);
        return lqw;
    }

    /**
     * 新增专家推荐信息
     *
     * @param bo 专家推荐信息
     * @return 是否新增成功
     */
    /*@Override
    public Boolean insertByBo(ZjkExpertRecommendBo bo) {
        ZjkExpertRecommend add = MapstructUtils.convert(bo, ZjkExpertRecommend.class);
        Long userId = LoginHelper.getUserId();
        ZjkExpert zjkExpert = zjkExpertMapper.selectOne(
            new LambdaQueryWrapper<ZjkExpert>()
                .eq(ZjkExpert::getUserId, userId)
                .eq(ZjkExpert::getDeleteFlag, UserConstants.DEL_FLAG_NORMAL)
        );
        if (zjkExpert == null) {
            throw new ServiceException("数据异常");
        }
        add.setUserId(userId);
        add.setExpertId(zjkExpert.getExpertId());
        add.setStatus(ZjkExpertTypeEnum.APPROVAL.getCodeAsString());
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }*/
    @Override
    public Boolean insertByBo(ZjkExpertRecommendBo bo) {
        ZjkExpertRecommend add = MapstructUtils.convert(bo, ZjkExpertRecommend.class);
        Long userId = LoginHelper.getUserId();
        ZjkExpert zjkExpert = zjkExpertMapper.selectOne(
            new LambdaQueryWrapper<ZjkExpert>()
                .eq(ZjkExpert::getUserId, userId)
                .eq(ZjkExpert::getDeleteFlag, UserConstants.DEL_FLAG_NORMAL)
        );
        if (zjkExpert == null) {
            throw new ServiceException("数据异常");
        }
        add.setUserId(userId);
        add.setExpertId(zjkExpert.getExpertId());
        add.setStatus(ZjkExpertTypeEnum.APPROVAL.getCodeAsString());
        validEntityBeforeSave(add);

        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());

            // === 生成 HMAC（可选） ===
            try {
                // 重新查出来，确保 ID 有值
                ZjkExpertRecommend fresh = baseMapper.selectById(add.getId());
                ZjkExpertRecommendVo entity = MapstructUtils.convert(fresh, ZjkExpertRecommendVo.class);
                String hash = ObjectHashGenerator.generateHash(entity);
                String base64 = Base64.getEncoder().encodeToString(hash.getBytes(StandardCharsets.UTF_8));

                // 调用 HMAC 接口生成签名
                 String hmac = hmacClient.calculateHmac(base64);
//                String hmac = base64;
                fresh.setHmac(hmac);
                baseMapper.updateById(fresh); // 更新 HMAC 字段
            } catch (Exception e) {
                log.error("生成 HMAC 失败，专家推荐ID: {}", add.getId(), e);
            }
        }

        return flag;
    }

    /**
     * 修改专家推荐信息
     *
     * @param bo 专家推荐信息
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(ZjkExpertRecommendBo bo) {
        ZjkExpertRecommend update = MapstructUtils.convert(bo, ZjkExpertRecommend.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ZjkExpertRecommend entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除专家推荐信息信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }
}
