package com.ematou.wxservice.mp.menu;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ematou.wxservice.api.WeChatApi;
import com.ematou.wxservice.api.WeChatApiRestTemplate;
import com.ematou.wxservice.common.constant.WeChatAccount;
import com.ematou.wxservice.common.constant.WeChatConstant;
import com.ematou.wxservice.service.WeChatService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

/**
 * 菜单按钮管理类
 * @author lhm
 * @version 1.0
 * 2021-05-11 20:46
 */
@Component
public class MenuButtonManager {

    public static final Logger logger = LoggerFactory.getLogger(MenuButtonManager.class);

    @Autowired
    WeChatApiRestTemplate weChatApiRestTemplate;

    @Autowired
    WeChatService weChatService;

    @Value("${wechat}")
    String wechat;

    @PostConstruct
    public void init() {
        // TODO 初始化菜单按钮
        //ViewButton testBtn = new ViewButton("测试按钮", WeChatConstant.EventType.VIEW.toLowerCase(), "http://f3dhion.nat.ipyingshe.com/view/main");
        HashMap<String, List<Button>> map = new HashMap<>();
        if(WeChatAccount.E_MA_TO.getItem().equals(wechat)){
            ClickButton myCodeBtn = new ClickButton("我的取件码", WeChatConstant.EventType.CLICK.toLowerCase(), WeChatConstant.CustomEventKey.MY_TAKE_PARCEL_CODE);
            ClickButton scanPush = new ClickButton("扫码取件", WeChatConstant.EventType.SCANCODE_PUSH.toLowerCase(), WeChatConstant.CustomEventKey.SCANCODE_PUSH_BUTTON);
            MiniProgramButton miniProgramButton = new MiniProgramButton("小程序",WeChatConstant.EventType.MINIPROGRAM.toLowerCase(),"http://mp.weixin.qq.com","wx1f09731935da5dd7","/pages/index/index");

            //ClickButton myHistoryBtn = new ClickButton("取件历史", WeChatConstant.EventType.CLICK.toLowerCase(), WeChatConstant.CustomEventKey.MY_HISTORY_RECORD);
            //ViewButton addressEntryBtn = new ViewButton("收货地址管理", WeChatConstant.EventType.VIEW.toLowerCase(), "http://kmall-test.ds-bay.com:8080/qrcode/verification.html");
            MenuButton takeParcelMenuButton = new MenuButton("取件服务");
            takeParcelMenuButton.setSub_button(Arrays.asList(scanPush)); // myCodeBtn  我的取件码菜单屏蔽

            ViewButton companyState = new ViewButton("公司状态", WeChatConstant.EventType.VIEW.toLowerCase(), "http://mp.weixin.qq.com/mp/homepage?__biz=MzIwMTI2MTg1MA==&hid=3&sn=da0db13971baf7a27bf639f2f7eaebbe&scene=18#wechat_redirect");
            ViewButton companyInfo = new ViewButton("公司简介", WeChatConstant.EventType.VIEW.toLowerCase(), "http://mp.weixin.qq.com/s?__biz=MzIwMTI2MTg1MA==&mid=503159833&idx=1&sn=fbddc8c56f960d7912cee60c959c42e8&chksm=0ef9aa6c398e237a862143c4f4c7314c0159a77e87ad4fd39a89d22181bcb05aedc9a816c8b2&scene=18#wechat_redirect");
            ViewButton industryReport = new ViewButton("行业周报", WeChatConstant.EventType.VIEW.toLowerCase(), "http://mp.weixin.qq.com/mp/homepage?__biz=MzIwMTI2MTg1MA==&hid=1&sn=f7becf0ef818d4a57a4ca4acfde72613&scene=18#wechat_redirect");
            ClickButton policySupport = new ClickButton("政策支持", WeChatConstant.EventType.CLICK.toLowerCase(), WeChatConstant.CustomEventKey.POLICY_SUPPORT);
            ClickButton callCompanyBtn = new ClickButton("联系我们", WeChatConstant.EventType.CLICK.toLowerCase(), WeChatConstant.CustomEventKey.CALL_COMPANY);
            MenuButton companyMenuButton = new MenuButton("公司信息");
            companyMenuButton.setSub_button(Arrays.asList(companyState, companyInfo, policySupport, industryReport, callCompanyBtn));

            ViewButton supplier = new ViewButton("供应商拓展", WeChatConstant.EventType.VIEW.toLowerCase(), "http://mp.weixin.qq.com/mp/homepage?__biz=MzIwMTI2MTg1MA==&hid=2&sn=cd51f61ada3218168fe3af6c3318b6ca&scene=18#wechat_redirect");
            ViewButton showGoods = new ViewButton("货源展示区", WeChatConstant.EventType.VIEW.toLowerCase(), "https://mp.weixin.qq.com/bizmall/mallshelf?id=&t=mall/list&biz=MzIwMTI2MTg1MA==&shelf_id=5&showwxpaytitle=1#wechat_redirect");
            ViewButton showNews = new ViewButton("展会快讯", WeChatConstant.EventType.VIEW.toLowerCase(), "http://mp.weixin.qq.com/mp/homepage?__biz=MzIwMTI2MTg1MA==&hid=4&sn=89a19c85a4742d13eb3e4ceab2179ba8&scene=18#wechat_redirect");
            MenuButton goodsMenuButton = new MenuButton("货源展示");
            goodsMenuButton.setSub_button(Arrays.asList(supplier, showGoods, showNews));

            map.put("button", Arrays.asList(companyMenuButton, goodsMenuButton, takeParcelMenuButton));

        } else if (WeChatAccount.QH_E_MA_TO.getItem().equals(wechat)) {
            /*ClickButton myCodeBtn = new ClickButton("我的取件码", WeChatConstant.EventType.CLICK.toLowerCase(), WeChatConstant.CustomEventKey.MY_TAKE_PARCEL_CODE);
            ClickButton scanPush = new ClickButton("扫码取件", WeChatConstant.EventType.SCANCODE_PUSH.toLowerCase(), WeChatConstant.CustomEventKey.SCANCODE_PUSH_BUTTON);
            //ClickButton myHistoryBtn = new ClickButton("取件历史", WeChatConstant.EventType.CLICK.toLowerCase(), WeChatConstant.CustomEventKey.MY_HISTORY_RECORD);
            //ViewButton addressEntryBtn = new ViewButton("收货地址管理", WeChatConstant.EventType.VIEW.toLowerCase(), "http://kmall-test.ds-bay.com:8080/qrcode/verification.html");
            MiniProgramButton miniProgramButton = new MiniProgramButton("小程序",WeChatConstant.EventType.MINIPROGRAM.toLowerCase(),"http://mp.weixin.qq.com","wx1f09731935da5dd7","/pages/index/index");
            MenuButton takeParcelMenuButton = new MenuButton("取件服务");
            takeParcelMenuButton.setSub_button(Arrays.asList(scanPush,miniProgramButton)); // myCodeBtn  我的取件码菜单屏蔽

            ViewButton companyState = new ViewButton("公司状态", WeChatConstant.EventType.VIEW.toLowerCase(), "http://mp.weixin.qq.com/mp/homepage?__biz=MzIwMTI2MTg1MA==&hid=3&sn=da0db13971baf7a27bf639f2f7eaebbe&scene=18#wechat_redirect");
            ViewButton companyInfo = new ViewButton("公司简介", WeChatConstant.EventType.VIEW.toLowerCase(), "http://mp.weixin.qq.com/s?__biz=MzIwMTI2MTg1MA==&mid=503159833&idx=1&sn=fbddc8c56f960d7912cee60c959c42e8&chksm=0ef9aa6c398e237a862143c4f4c7314c0159a77e87ad4fd39a89d22181bcb05aedc9a816c8b2&scene=18#wechat_redirect");
            ViewButton industryReport = new ViewButton("行业周报", WeChatConstant.EventType.VIEW.toLowerCase(), "http://mp.weixin.qq.com/mp/homepage?__biz=MzIwMTI2MTg1MA==&hid=1&sn=f7becf0ef818d4a57a4ca4acfde72613&scene=18#wechat_redirect");
            ClickButton policySupport = new ClickButton("政策支持", WeChatConstant.EventType.CLICK.toLowerCase(), WeChatConstant.CustomEventKey.POLICY_SUPPORT);
            ClickButton callCompanyBtn = new ClickButton("联系我们", WeChatConstant.EventType.CLICK.toLowerCase(), WeChatConstant.CustomEventKey.CALL_COMPANY);
            MenuButton companyMenuButton = new MenuButton("公司信息");
            companyMenuButton.setSub_button(Arrays.asList(companyState, companyInfo, policySupport, industryReport, callCompanyBtn));

            ViewButton supplier = new ViewButton("供应商拓展", WeChatConstant.EventType.VIEW.toLowerCase(), "http://mp.weixin.qq.com/mp/homepage?__biz=MzIwMTI2MTg1MA==&hid=2&sn=cd51f61ada3218168fe3af6c3318b6ca&scene=18#wechat_redirect");
            ViewButton showGoods = new ViewButton("货源展示区", WeChatConstant.EventType.VIEW.toLowerCase(), "https://mp.weixin.qq.com/bizmall/mallshelf?id=&t=mall/list&biz=MzIwMTI2MTg1MA==&shelf_id=5&showwxpaytitle=1#wechat_redirect");
            ViewButton showNews = new ViewButton("展会快讯", WeChatConstant.EventType.VIEW.toLowerCase(), "http://mp.weixin.qq.com/mp/homepage?__biz=MzIwMTI2MTg1MA==&hid=4&sn=89a19c85a4742d13eb3e4ceab2179ba8&scene=18#wechat_redirect");
            MenuButton goodsMenuButton = new MenuButton("货源展示");
            goodsMenuButton.setSub_button(Arrays.asList(supplier, showGoods, showNews));


            map.put("button", Arrays.asList(companyMenuButton, goodsMenuButton, takeParcelMenuButton));*/
            //品牌信息、官方商城、扫码取件
            MenuButton brandMenuButton = new MenuButton("品牌信息");
            //品牌介绍、品牌动态、商务合作
            ViewButton brandInfoBtn = new ViewButton("品牌介绍", WeChatConstant.EventType.VIEW.toLowerCase(), "https://mp.weixin.qq.com/s/wydyGIDHneGS86uv2adfBA?scene=18#wechat_redirect");
            ViewButton brandDynamicBtn = new ViewButton("品牌动态", WeChatConstant.EventType.VIEW.toLowerCase(), "https://mp.weixin.qq.com/s/exx2UWlbdXGxhtZpA5ZujQ?scene=18#wechat_redirect");
            String businessMediaId = weChatService.mediaUpload(WeChatConstant.CustomEventKey.BUSINESS_COOPERATION);
            //String businessMediaId = "cvw1kfvywUWCq28CBDTqMoTYizso3Zg1eT7QS8ORRqMv5y_hs99WG8x-beJb4y0r";
            MediaButton businessBtn = new MediaButton("商务合作", WeChatConstant.EventType.MEDIA_ID.toLowerCase(), WeChatConstant.CustomEventKey.BUSINESS_COOPERATION, businessMediaId);
            brandMenuButton.setSub_button(Arrays.asList(brandInfoBtn, brandDynamicBtn, businessBtn));

            MenuButton mallMenuButton = new MenuButton("官方商城");
            //跨境e购、售后服务
            MiniProgramButton miniProgramButton = new MiniProgramButton("跨境e购",WeChatConstant.EventType.MINIPROGRAM.toLowerCase(),"http://mp.weixin.qq.com","wx1f09731935da5dd7","/pages/index/index");
            String afterServiceMediaId = weChatService.mediaUpload(WeChatConstant.CustomEventKey.AFTER_SALE_SERVICE);
            //String afterServiceMediaId = "cvw1kfvywUWCq28CBDTqMrMkllh2LYLVmneULJEOJGF6XNdjAsoX83F9jb4tP9pkr";
            MediaButton afterServiceBtn = new MediaButton("售后服务", WeChatConstant.EventType.MEDIA_ID.toLowerCase(), WeChatConstant.CustomEventKey.AFTER_SALE_SERVICE, afterServiceMediaId);
            mallMenuButton.setSub_button(Arrays.asList(miniProgramButton, afterServiceBtn));

            MenuButton scanMenuButton = new MenuButton("扫码取件");
            ClickButton scanPush = new ClickButton("扫码取件", WeChatConstant.EventType.SCANCODE_PUSH.toLowerCase(), WeChatConstant.CustomEventKey.SCANCODE_PUSH_BUTTON);
            scanMenuButton.setSub_button(Arrays.asList(scanPush)); // myCodeBtn  我的取件码菜单屏蔽

            map.put("button", Arrays.asList(brandMenuButton, mallMenuButton, scanMenuButton));

        }

        String menu = JSON.toJSONString(map);
        logger.info("初始化菜单信息：" + menu);


        CompletableFuture<Void> runAsync = CompletableFuture.runAsync(() -> {
            int retry = 0;
            while (retry < 3) {
                try {
                    String response = weChatApiRestTemplate.postForOther(String.format(WeChatApi.CREATE_MENU.getUrl(), weChatService.getAccessToken().getAccessToken()), menu);

                    if (!StringUtils.hasLength(response)) {
                        retry++;
                        logger.error("创建菜单失败，返回为空！等待5秒继续重试中。。");
                        if (retry == 3) {
                            logger.error("创建菜单已经失败，请检查微信公众号服务器配置是否开启，或检查服务器配置是否正确！");
                        }
                        TimeUnit.SECONDS.sleep(5);
                        continue;
                    }

                    JSONObject jsonObject = JSON.parseObject(response);
                    logger.info("创建菜单结果：" + response);
                    Integer errcode = jsonObject.getObject(WeChatConstant.RESPONSE_ERROR_CODE, Integer.class);
                    String errmsg = jsonObject.getObject(WeChatConstant.RESPONSE_ERROR_MSG, String.class);
                    if (errcode != 0 && !errmsg.equalsIgnoreCase(WeChatConstant.RESPONSE_OK)) {
                        retry++;
                        logger.error("创建菜单失败，error code：" + errcode + "，error message：" + errmsg);
                        TimeUnit.SECONDS.sleep(5);
                        continue;
                    }
                    break;
                } catch (Throwable e) {
                    retry++;
                }
            }
        });

        // 不阻塞主线程
//        try {
//            runAsync.get(20, TimeUnit.SECONDS);
//        } catch (ExecutionException | TimeoutException e) {
//            logger.error("等待创建菜单执行结果超时或执行出错：" + e.getMessage());
//        }

    }

}
