package com.cpop.oam.business.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.cpop.oam.business.entity.WxOpenMini;
import com.cpop.oam.business.mapper.WxOpenMiniMapper;
import com.cpop.oam.business.service.WxOpenMiniService;
import com.cpop.oam.business.vo.WxOpenMiniVo;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import me.chanjar.weixin.open.bean.result.WxOpenAuthorizerInfoResult;
import me.chanjar.weixin.open.bean.result.WxOpenAuthorizerListResult;
import org.springframework.stereotype.Service;

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

import static com.cpop.oam.business.entity.table.WxOpenMiniTableDef.WX_OPEN_MINI;

/**
 * Oam-微信开放平台-小程序 服务层实现。
 *
 * @author DB
 * @since 2023-10-11
 */
@Service("wxOpenMiniService")
public class WxOpenMiniServiceImpl extends ServiceImpl<WxOpenMiniMapper, WxOpenMini> implements WxOpenMiniService {

    /**
     * @descriptions 获取授权小程序列表
     * @author DB
     * @date 2023/10/11 12:52
     * @param authorizerList 微信拉取信息列表
     * @return: java.util.List<com.cpop.oam.business.vo.WxOpenMiniVo>
     */
    @Override
    public List<WxOpenMiniVo> getAuthorizerList(WxOpenAuthorizerListResult authorizerList) {
        List<WxOpenMiniVo> wxOpenMiniVos = JSONArray.parseArray(JSON.toJSONString(authorizerList.getList()), WxOpenMiniVo.class);
        if (!wxOpenMiniVos.isEmpty()){
            Map<String, String> appletMap = this.list(QueryWrapper.create().where(WX_OPEN_MINI.APPID.in(wxOpenMiniVos.stream().map(WxOpenMiniVo::getAuthorizerAppid).collect(Collectors.toSet()))))
                    .stream().collect(Collectors.toMap(WxOpenMini::getAppid, WxOpenMini::getNickName));
            wxOpenMiniVos.forEach(item->{
                item.setNickName(appletMap.get(item.getAuthorizerAppid()));
            });
        }
        return wxOpenMiniVos;
    }

    /**
     * @descriptions 数据同步
     * @author DB
     * @date 2023/10/11 13:41
     * @param authorizerInfo 授权小程序信息
     * @return: void
     */
    @Override
    public void dataSync(WxOpenAuthorizerInfoResult authorizerInfo) {
        WxOpenMini wxOpenMini = this.getOne(QueryWrapper.create().where(WX_OPEN_MINI.APPID.eq(authorizerInfo.getAuthorizationInfo().getAuthorizerAppid())));
        if (null == wxOpenMini) {
            wxOpenMini = new WxOpenMini();
            wxOpenMini.setAppid(authorizerInfo.getAuthorizationInfo().getAuthorizerAppid());
        }
        wxOpenMini.setNickName(authorizerInfo.getAuthorizerInfo().getNickName());
        this.saveOrUpdate(wxOpenMini);
    }
}
