package org.dromara.elevator.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.config.WxMaConfig;
import com.google.common.base.Joiner;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
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.json.utils.JsonUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.common.satoken.utils.LoginHelper;
import org.springframework.stereotype.Service;
import org.dromara.elevator.domain.bo.EElevatorWechatUserBo;
import org.dromara.elevator.domain.vo.EElevatorWechatUserVo;
import org.dromara.elevator.domain.EElevatorWechatUser;
import org.dromara.elevator.mapper.EElevatorWechatUserMapper;
import org.dromara.elevator.service.IEElevatorWechatUserService;

import java.util.*;

/**
 * 电梯微信用户关联Service业务层处理
 *
 * @author ym
 * @date 2024-10-28
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class EElevatorWechatUserServiceImpl implements IEElevatorWechatUserService {

    private final EElevatorWechatUserMapper baseMapper;

    private final WxMaService wxMaService;

    /**
     * 查询电梯微信用户关联
     *
     * @param id 主键
     * @return 电梯微信用户关联
     */
    @Override
    public EElevatorWechatUserVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询电梯微信用户关联列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 电梯微信用户关联分页列表
     */
    @Override
    public TableDataInfo<EElevatorWechatUserVo> queryPageList(EElevatorWechatUserBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<EElevatorWechatUser> lqw = buildQueryWrapper(bo);
        Page<EElevatorWechatUserVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的电梯微信用户关联列表
     *
     * @param bo 查询条件
     * @return 电梯微信用户关联列表
     */
    @Override
    public List<EElevatorWechatUserVo> queryList(EElevatorWechatUserBo bo) {
        LambdaQueryWrapper<EElevatorWechatUser> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<EElevatorWechatUser> buildQueryWrapper(EElevatorWechatUserBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<EElevatorWechatUser> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getUserId() != null, EElevatorWechatUser::getUserId, bo.getUserId());
        lqw.eq(StringUtils.isNotBlank(bo.getMpOpenId()), EElevatorWechatUser::getMpOpenId, bo.getMpOpenId());
        lqw.eq(StringUtils.isNotBlank(bo.getUnionId()), EElevatorWechatUser::getUnionId, bo.getUnionId());
        lqw.eq(StringUtils.isNotBlank(bo.getMaOpenId()), EElevatorWechatUser::getMaOpenId, bo.getMaOpenId());
        return lqw;
    }

    /**
     * 新增电梯微信用户关联
     *
     * @param bo 电梯微信用户关联
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(EElevatorWechatUserBo bo) {
        EElevatorWechatUser add = MapstructUtils.convert(bo, EElevatorWechatUser.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改电梯微信用户关联
     *
     * @param bo 电梯微信用户关联
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(EElevatorWechatUserBo bo) {
        EElevatorWechatUser update = MapstructUtils.convert(bo, EElevatorWechatUser.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

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

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

    @Override
    public EElevatorWechatUser queryByUnionId(String unionId) {
        return baseMapper.selectOne(Wrappers.<EElevatorWechatUser>lambdaQuery()
            .eq(EElevatorWechatUser::getUnionId, unionId));
    }

    @Override
    public Boolean saveOrUpdate(EElevatorWechatUserBo bo) {
        return baseMapper.insertOrUpdate(MapstructUtils.convert(bo, EElevatorWechatUser.class));
    }

    @Override
    public Boolean bind(String code) {
        if (StringUtils.isBlank(code)) {
            return Boolean.FALSE;
        }
        if (!LoginHelper.isLogin()) {
            // 未登录
            return Boolean.FALSE;
        }
        // 该账号用户绑定是否优先已存在关注公众号校验
        List<EElevatorWechatUser> wechatUsers = baseMapper.selectList(Wrappers.<EElevatorWechatUser>lambdaQuery()
            .eq(EElevatorWechatUser::getUserId, LoginHelper.getUserId()));

        Optional<EElevatorWechatUser> first = wechatUsers.stream()
            .filter(item -> StringUtils.isNotBlank(item.getMpOpenId())
                && StringUtils.isNotBlank(item.getUnionId())
                && StringUtils.isNotBlank(item.getMaOpenId()))
            .findFirst();
        if (first.isPresent()) {
            // 存在已优先关注信息
            return Boolean.TRUE;
        }

        try {
            WxMaJscode2SessionResult sessionInfo = wxMaService.getUserService().getSessionInfo(code);
            EElevatorWechatUser wechatUser = queryByUnionId(sessionInfo.getUnionid());
            if (Objects.isNull(wechatUser)) {
                wechatUser = new EElevatorWechatUser();
                wechatUser.setUnionId(sessionInfo.getUnionid());
            }
            if (Objects.nonNull(wechatUser.getUserId())) {
                // 已存在记录
                return Boolean.TRUE;
            }
            wechatUser.setUserId(LoginHelper.getUserId());
            wechatUser.setMaOpenId(sessionInfo.getOpenid());
            wechatUser.setCreateDept(LoginHelper.getDeptId());
            if (Objects.isNull(wechatUser.getId())) {
                baseMapper.insert(wechatUser);
            } else {
                baseMapper.updateById(wechatUser);
            }
        } catch (WxErrorException e) {
            log.error("微信小程序查询用户信息异常:{}, {}", LoginHelper.getUserId(), code, e);
            return Boolean.FALSE;
        }
        return Boolean.TRUE;
    }

    @Override
    public Boolean deleteByMpOpenId(String mpOpenId) {
        return baseMapper.delete(Wrappers.<EElevatorWechatUser>lambdaQuery()
            .eq(EElevatorWechatUser::getMpOpenId, mpOpenId)) > 0;
    }
}
