package vip.xiaonuo.weixin.gongzhong.listener;

import cn.hutool.json.JSONArray;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.stereotype.Component;
import vip.xiaonuo.common.listener.CommonDataChangeListener;
import vip.xiaonuo.dev.modular.config.entity.DevConfig;
import vip.xiaonuo.dev.modular.config.enums.ConfigDataType;
import vip.xiaonuo.weixin.gongzhong.service.WxMenuService;

import java.util.List;
import java.util.Optional;

@Slf4j
@Component
@RequiredArgsConstructor
public class ConfigChangeListener implements CommonDataChangeListener {

    private final WxMpService wxMpService;
    private final WxMenuService wxMenuService;

    @Override
    public void doAddWithDataIdList(String dataType, List<String> dataIdList) {

    }

    @Override
    public void doAddWithDataList(String dataType, JSONArray jsonArray) {

    }

    @Override
    public void doUpdateWithDataIdList(String dataType, List<String> dataIdList) {

    }

    @SneakyThrows
    @Override
    public void doUpdateWithDataList(String dataType, JSONArray jsonArray) {
        //配置更新
        if(dataType.equals(ConfigDataType.DEV_CONFIG)) {
            List<DevConfig> configList = jsonArray.toList(DevConfig.class);
            // 如果微信重定向地址更新，则更新微信菜单
            Optional<DevConfig> opt = configList.stream().filter(c -> c.getConfigKey().equals("SNOWY_THIRD_WECHAT_REDIRECT_URL")).findAny();
            if (opt.isPresent()) {
                wxMpService.getMenuService().menuCreate(wxMenuService.createMenu());
            }
        }
    }

    @Override
    public void doDeleteWithDataIdList(String dataType, List<String> dataIdList) {

    }
}
