package com.gxwebsoft.cms.controller;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gxwebsoft.cms.service.MpMenuService;
import com.gxwebsoft.cms.service.NavigationService;
import com.gxwebsoft.common.core.utils.RedisUtil;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.cms.service.MpOfficialMenuService;
import com.gxwebsoft.cms.entity.MpOfficialMenu;
import com.gxwebsoft.cms.param.MpOfficialMenuParam;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.core.web.BatchParam;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import static com.gxwebsoft.common.core.constants.PlatformConstants.MP_OFFICIAL;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 微信公众号菜单控制器
 *
 * @author 科技小王子
 * @since 2024-09-15 13:12:38
 */
@Api(tags = "微信公众号")
@RestController
@RequestMapping("/api/cms/mp-official-menu")
public class MpOfficialMenuController extends BaseController {
    // 创建公众号菜单
    private static final String MENU_CREATE_URL = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=";
    // 公众号AppID
    private static final String appid = "wxa67c676fc445590e";
    // 秘钥
    private static final String secret = "a450297b5ca8e081080148799d4e6b25";

    @Resource
    private RedisUtil redisUtil;
    @Resource
    private MpOfficialMenuService mpOfficialMenuService;
    @Resource
    private MpMenuService mpMenuService;
    @Resource
    private NavigationService navigationService;

    @ApiOperation("分页查询微信公众号菜单")
    @GetMapping("/page")
    public ApiResult<PageResult<MpOfficialMenu>> page(MpOfficialMenuParam param) {
        // 使用关联查询
        return success(mpOfficialMenuService.pageRel(param));
    }

    @ApiOperation("查询全部微信公众号菜单")
    @GetMapping()
    public ApiResult<List<MpOfficialMenu>> list(MpOfficialMenuParam param) {
        // 使用关联查询
        return success(mpOfficialMenuService.listRel(param));
    }

    @PreAuthorize("hasAuthority('cms:mpOfficialMenu:list')")
    @ApiOperation("根据id查询微信公众号菜单")
    @GetMapping("/{id}")
    public ApiResult<MpOfficialMenu> get(@PathVariable("id") Integer id) {
        // 使用关联查询
        return success(mpOfficialMenuService.getByIdRel(id));
    }

    @ApiOperation("添加微信公众号菜单")
    @PostMapping()
    public ApiResult<?> save(@RequestBody MpOfficialMenu mpOfficialMenu) {
        if (mpOfficialMenuService.save(mpOfficialMenu)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @ApiOperation("修改微信公众号菜单")
    @PutMapping()
    public ApiResult<?> update(@RequestBody MpOfficialMenu mpOfficialMenu) {
        if (mpOfficialMenuService.updateById(mpOfficialMenu)) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @ApiOperation("删除微信公众号菜单")
    @DeleteMapping("/{id}")
    public ApiResult<?> remove(@PathVariable("id") Integer id) {
        if (mpOfficialMenuService.removeById(id)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    @ApiOperation("批量添加微信公众号菜单")
    @PostMapping("/batch")
    public ApiResult<?> saveBatch(@RequestBody List<MpOfficialMenu> list) {
        if (mpOfficialMenuService.saveBatch(list)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @ApiOperation("批量修改微信公众号菜单")
    @PutMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody BatchParam<MpOfficialMenu> batchParam) {
        if (batchParam.update(mpOfficialMenuService, "id")) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @ApiOperation("批量删除微信公众号菜单")
    @DeleteMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
        if (mpOfficialMenuService.removeByIds(ids)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }


    // 调用接口凭证
    private String getAccessToken() {
        String key = MP_OFFICIAL.concat(":access_token:").concat(getTenantId().toString());
        // 从缓存获取access_token
        String value = redisUtil.get(key);
        if (value != null) {
            // 解析access_token
            JSONObject response = JSON.parseObject(value);
            return response.getString("access_token");
        }
        // 微信获取凭证接口https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
        String apiUrl = "https://api.weixin.qq.com/cgi-bin/token";
        // 组装url参数
        String url = apiUrl.concat("?grant_type=client_credential").concat("&appid=").concat(appid).concat("&secret=").concat(secret);
        // 执行get请求
        String result = HttpUtil.get(url);
        // 解析access_token
        JSONObject response = JSON.parseObject(result);
        if (response.getString("access_token") != null) {
            // 存入缓存
            redisUtil.set(key, result,7000L, TimeUnit.SECONDS);
            return response.getString("access_token");
        }
        return null;
    }

    @ApiOperation("创建公众号菜单接口")
    @GetMapping("/createMenu")
    public ApiResult<?> createMenu() {
        System.out.println("AccessToken = " + getAccessToken());
        String url = MENU_CREATE_URL.concat(Objects.requireNonNull(getAccessToken()));
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        final HashMap<String, Object> menu = new HashMap<>();
        final MpOfficialMenu officialMenu = new MpOfficialMenu();
        officialMenu.setName("官方服务");
        officialMenu.setType("view");
        officialMenu.setUrl("https://websoft.top");
        menu.put("button",officialMenu);
        officialMenu.setName("产品演示");
        officialMenu.setType("view");
        officialMenu.setUrl("https://websoft.top/product/website");
        menu.put("button",officialMenu);
        officialMenu.setName("我的");
        officialMenu.setType("view");
        officialMenu.setUrl("https://websoft.top/user");
        menu.put("button",officialMenu);
        httpPost.setEntity(new StringEntity(JSON.toJSONString(menu), "UTF-8"));
        httpPost.setHeader("Content-type", "application/json");

        try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String result = EntityUtils.toString(entity, "UTF-8");
                System.out.println("result = " + result);
                return success("返回结果",entity);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return fail("创建失败",url);
    }


}
