package com.miaxis.wx.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.miaxis.common.core.domain.Response;
import com.miaxis.common.exception.CustomException;
import com.miaxis.common.sign.VerifyUtil;
import com.miaxis.feign.service.IWxSendService;
import com.miaxis.wx.domain.WxMenu;
import com.miaxis.wx.mapper.WxMenuMapper;
import com.miaxis.wx.service.IWxGzhService;
import com.miaxis.wx.service.IWxMenuService;
import com.miaxis.wx.vo.WxMenuVo;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

/**
 * 微信公众号菜单Service业务层处理
 * @author wwl
 * @version 1.0
 * @date 2021/11/3 9:24
 */
@Service
@AllArgsConstructor
@Slf4j
public class WxMenuServiceImpl extends ServiceImpl<WxMenuMapper, WxMenu> implements IWxMenuService {

    private final WxMenuMapper wxMenuMapper;

    private final IWxGzhService wxGzhService;

    private final IWxSendService wxSendService;

    /**
     * 查询微信公众号菜单列表
     *
     * @return 微信公众号菜单
     */
    @Override
    public Response<List<WxMenuVo>> selectWxMenuTreeList(){
        List<WxMenuVo> menuList = wxMenuMapper.selectWxMenuList();
        return Response.success(builTree(menuList));
    }

    //建立树形结构
    public List<WxMenuVo> builTree(List<WxMenuVo> menuList){
        List<WxMenuVo> infoVos =new ArrayList<>();
        //获取根节点
        List<WxMenuVo> rootMenuLists =new  ArrayList<>();
        for(WxMenuVo menuVo : menuList) {
            if(menuVo.getParentId().toString().equals("0")) {
                rootMenuLists.add(menuVo);
            }
        }
        for(WxMenuVo wxMenuVo : rootMenuLists) {
            wxMenuVo=getTree(wxMenuVo,menuList);
            infoVos.add(wxMenuVo);
        }
        return infoVos;
    }
    //递归，建立子树形结构
    private WxMenuVo getTree(WxMenuVo wxMenuVo,List<WxMenuVo> menuList){
        List<WxMenuVo> infoVos = new ArrayList<>();
        for (WxMenuVo menuVo : menuList) {
            if (menuVo.getParentId().toString().equals(wxMenuVo.getId().toString())){
                infoVos.add(getTree(menuVo,menuList));
            }
        }
        wxMenuVo.setChildren(infoVos);
        return wxMenuVo;
    }


    /**
     * 新增微信公众号菜单
     * @param wxMenu
     * @return
     */
    @Override
    public Response saveMenu(WxMenu wxMenu) {
        try {
            wxMenuMapper.insert(wxMenu);
            sendMenu();
            return Response.success();
        }catch (Exception e){
            throw new CustomException("系统异常");
        }
    }

    /**
     * 修改微信公众号菜单
     * @param wxMenu
     * @return
     */
    @Override
    public Response updateMenuById(WxMenu wxMenu) {
        try {
            wxMenuMapper.updateById(wxMenu);
            sendMenu();
            return Response.success();
        }catch (Exception e){
            throw new CustomException("系统异常");
        }
    }

    /**
     * 删除微信公众号菜单
     * @param ids
     * @return
     */
    @Override
    public Response removeMenuByIds(Long[] ids) {
        try {
            this.removeByIds(Arrays.asList(ids));
            sendMenu();
            return Response.success();
        }catch (Exception e){
            throw new CustomException("系统异常");
        }
    }

    /**
     * 一键发送数据库菜单
     * @return
     */
    @Override
    public Response sendMenuBySql() {
        sendMenu();
        return Response.success();
    }


    /**
     * 发送菜单至微信
     * @return
     */
    private String sendMenu(){
        JSONObject wxMenuJson = getWxMenuJson();
        String token = wxGzhService.getGzhToken();
        String result = wxSendService.createMenu(token,wxMenuJson);
        log.info("-----sendMenu-----"+ result);
        return result;
    }


    /**
     * 查询微信菜单数据
     * @return
     */
    private JSONObject getWxMenuJson() {

        JSONObject menuJson = new JSONObject();
        //获取父类
        List<WxMenu> menuList = wxMenuMapper.selectByMap(new HashMap<String,Object>(){{
            put("parent_id",0);
        }});
        JSONArray button=new JSONArray();
        for(WxMenu menu : menuList){
            if(!VerifyUtil.verifyString(menu.getType())){
                JSONObject childButton = new JSONObject();
                childButton.put("name", menu.getMenuName());
                //父类
                JSONArray sub_button = new JSONArray();
                List<WxMenu> childMenuList = wxMenuMapper.selectList(new QueryWrapper<WxMenu>().eq("parent_id", menu.getId()).orderByAsc("sort"));

                for (WxMenu childMenu : childMenuList) {
                    sub_button.add(getChildMenuJson(childMenu));
                }
                childButton.put("sub_button", sub_button);
                button.add(childButton);
            }else{
                button.add(getChildMenuJson(menu));
            }
        }

        menuJson.put("button", button);
        return menuJson;
    }


    private JSONObject getChildMenuJson(WxMenu menu){
        JSONObject menuJson = new JSONObject();
        menuJson.put("type", menu.getType());
        menuJson.put("name", menu.getMenuName());
        if(menu.getType().equals("view")){
            menuJson.put("url", menu.getUrl());
        }else if(menu.getType().equals("click")){
            menuJson.put("key", menu.getClickKey());
        }else if(menu.getType().equals("miniprogram")){
            menuJson.put("url", menu.getUrl());
            menuJson.put("key", menu.getClickKey());
            menuJson.put("appid", menu.getAppid());
            menuJson.put("pagepath", menu.getPagePath());
        }
        return menuJson;
    }


}
