package com.huiju.estateagents.third.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.huiju.estateagents.base.ResponseBean;
import com.huiju.estateagents.common.CommConstant;
import com.huiju.estateagents.third.entity.TaMpInfo;
import com.huiju.estateagents.third.service.ITaMpInfoService;
import com.huiju.estateagents.third.service.ITaThirdPartyMiniappConfigService;
import lombok.AllArgsConstructor;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Edward
 */
@AllArgsConstructor
@RestController
@RequestMapping("/api")
public class WxRedpackController {

    @Autowired
    public ITaThirdPartyMiniappConfigService iTaThirdPartyMiniappConfigService;

    @Autowired
    public ITaMpInfoService iTaMpInfoService;

    /**
     * 换取openid接口并插入公众号人员表
     *
     * @param mpAppid
     * @param code
     * @param request
     * @return
     */
    @GetMapping("/third/redirect/{mpAppid}/greet")
    public ResponseBean greetUser(@PathVariable String mpAppid, @RequestParam String code, @RequestParam String personId, @RequestParam(required = false) String sponsorPersonId, @RequestParam String drainageId, HttpServletRequest request) {
        WxMpService wxService = getWxMpService();
        if (!wxService.switchover(mpAppid)) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", mpAppid));
        }
        Map<String, Object> map = new HashMap<>();
        try {
            //换取openid
            WxMpOAuth2AccessToken accessToken = wxService.oauth2getAccessToken(code);
            //插入公众号人员信息并插入表
            map = iTaThirdPartyMiniappConfigService.newMpPerson(accessToken, mpAppid, drainageId, sponsorPersonId, personId);
        } catch (WxErrorException e) {
//            e.printStackTrace();
            return ResponseBean.error(e.getMessage(), ResponseBean.ERROR_UNAVAILABLE);
        }
        return ResponseBean.success(map);
    }

    private WxMpService getWxMpService() {
        //从数据库读取公众号信息
        QueryWrapper<TaMpInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", CommConstant.STATUS_NORMAL);
        queryWrapper.eq("org_id", 0);
        List<TaMpInfo> mplist = iTaMpInfoService.list(queryWrapper);

        WxMpService service = new WxMpServiceImpl();
        service.setMultiConfigStorages(mplist
                .stream().map(a -> {
                    WxMpDefaultConfigImpl configStorage = new WxMpDefaultConfigImpl();
                    configStorage.setAppId(a.getAppid());
                    configStorage.setSecret(a.getSecret());
                    configStorage.setToken(a.getToken());
                    configStorage.setAesKey(a.getAesKey());
                    return configStorage;
                }).collect(Collectors.toMap(WxMpDefaultConfigImpl::getAppId, a -> a, (o, n) -> o)));
        return service;
    }

    /**
     * 根据personid查询这个人需要的信息
     *
     * @param mpAppid
     * @param request
     * @return
     */
    @GetMapping("/third/activity/{mpAppid}/personInfo")
    public ResponseBean getPersonInfo(@PathVariable String mpAppid, @RequestParam String personId, @RequestParam String drainageId, HttpServletRequest request) {
        WxMpService wxService = getWxMpService();
        if (!wxService.switchover(mpAppid)) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", mpAppid));
        }
        Map<String, Object> map = new HashMap<>();
        try {
            //插入公众号人员信息并插入表
            map = iTaThirdPartyMiniappConfigService.getPersonInfo(mpAppid, drainageId, personId);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseBean.error(e.getMessage(), ResponseBean.ERROR_UNAVAILABLE);
        }
        return ResponseBean.success(map);
    }

    /**
     * 我要参加 活动接口
     *
     * @param mpAppid
     * @param personId
     * @param request
     * @return
     */
    @PostMapping("/third/activity/{mpAppid}/participate")
    public ResponseBean participateActivity(@PathVariable String mpAppid, @RequestParam String personId, @RequestParam String drainageId, HttpServletRequest request) {
        WxMpService wxService = getWxMpService();
        if (!wxService.switchover(mpAppid)) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", mpAppid));
        }
        try {
            ResponseBean res = iTaThirdPartyMiniappConfigService.participateActivity(mpAppid, personId, drainageId);
            return res;
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseBean.error("程序出错请联系运营人员", ResponseBean.ERROR_ILLEGAL_PARAMS);
        }
    }

    /**
     * 帮他助力 接口
     *
     * @param mpAppid
     * @param personId
     * @param request
     * @return
     */
    @PostMapping("/third/activity/{mpAppid}/help")
    public ResponseBean helpActivity(@PathVariable String mpAppid, @RequestParam String personId, @RequestParam String sponsorPersonId, @RequestParam String drainageId, HttpServletRequest request) {
        WxMpService wxService = getWxMpService();
        if (!wxService.switchover(mpAppid)) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", mpAppid));
        }
        if (personId.equals(sponsorPersonId)) {
            return ResponseBean.error("自己不能助力自己", ResponseBean.ERROR_UNAVAILABLE);
        }

        try {
            ResponseBean res = iTaThirdPartyMiniappConfigService.helpActivity(mpAppid, personId, sponsorPersonId, drainageId);
            return res;
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseBean.error("程序出错请联系运营人员", ResponseBean.ERROR_ILLEGAL_PARAMS);
        }
    }

    /**
     * 获取此活动的排行榜
     *
     * @param drainageId
     * @param request
     * @return
     */
    @GetMapping("/third/activity/ranking")
    public ResponseBean getRanking(@RequestParam String drainageId, HttpServletRequest request) {
        try {
            //获取活动的排行榜
            return iTaThirdPartyMiniappConfigService.getRanking(drainageId);
        } catch (Exception e) {
//            e.printStackTrace();
            return ResponseBean.error(e.getMessage(), ResponseBean.ERROR_UNAVAILABLE);
        }
    }
}
