package com.yida.data.common.core.utils;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.yida.data.common.core.entity.constant.YidaAppConstant;
import com.yida.data.common.core.entity.notice.app.AppNotice;
import com.yida.data.common.core.entity.program.YiDaSmallProgramVO;
import com.yida.data.common.core.entity.school.EduSchoolHomeMicroCol;
import com.yida.data.common.core.entity.school.EduSchoolManuscript;
import com.yida.data.common.core.entity.school.EduYidaAppAccount;
import com.yida.data.common.core.entity.system.EduYidaApp;
import com.yida.data.common.core.exception.FebsException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;

import java.io.File;
import java.util.List;
import java.util.Map;

/**
 * app工具类
 */
@Slf4j
public class AppUtil {

    /**
     * 两微一端接口返回的status状态码json字段名称
     */
    public static final String STATUS_NAME = "status";

    /**
     * 两微一端接口返回的data数据json字段名称
     */
    private static final String DATA_NAME = "data";

    //------------------栏目--------------------

    /**
     * 新增修改栏目
     */
    public static String colSave(String id, String name, EduYidaApp yidaApp) {
        StringBuilder url = new StringBuilder();
        url.append(yidaApp.getAppUrl())
            .append(YidaAppConstant.COL_SAVE);
        JSONObject body = new JSONObject() {{
            set("name", name);
            set("type", 1);
            set("show4", 1);
            set("mannerId", 909);
            set("isCarousel", 1);
            set("areaId", yidaApp.getAppAreaId());
        }};
        if (StrUtil.isNotBlank(id)) {
            body.set("id", id);
        }
        String res = HttpUtil.post(url.toString(), body);
        JSONObject resJson = JSONUtil.parseObj(res);
        log.info("添加栏目,res:[{}],params:[{}]", resJson, body);
        if (resJson.getInt("status") == 200) {
            JSONObject colIdJson = JSONUtil.parseObj(resJson.get("data"));
            return colIdJson.getStr("dataId");
        }
        return null;
    }

    // -----------------订阅号-------------------

    /**
     * 新增、修改订阅号
     *
     * @param subscribe
     * @param app
     */
    public static String subscribeSave(EduYidaAppAccount subscribe, EduYidaApp app) {
        StringBuilder url = new StringBuilder();
        url.append(app.getAppUrl())
            .append(YidaAppConstant.SUBSCRIBE_SAVE);
        JSONObject body = new JSONObject() {{
            set("accountName", subscribe.getYidaAppAccountName());
            set("showInMsg", subscribe.getType() == 0 ? 1 : 0);
        }};
        if (StrUtil.isNotBlank(subscribe.getYidaAppAccountId())) {
            body.set("id", subscribe.getYidaAppAccountId());
        }
        if (StrUtil.isNotBlank(subscribe.getLogo())) {
            body.set("imgUrl", subscribe.getLogo());
        }
        String res = HttpUtil.post(url.toString(), body);
        JSONObject resJson = JSONUtil.parseObj(res);
        if (resJson.getInt("status") == 200) {
            return resJson.get("data").toString();
        }
        return null;
    }

    /**
     * 关注订阅号
     */
    public static void subscribeFollow(String subscribeId, String userId, EduYidaApp app) {
        StringBuilder url = new StringBuilder();
        url.append(app.getAppUrl())
            .append(YidaAppConstant.SUBSCRIBE_FOLLOW);
        JSONObject body = new JSONObject() {{
            set("userId", userId);
            set("accountId", subscribeId);
        }};
        String res = HttpUtil.get(url.toString(), body);
        log.info("关注订阅号,res:[{}],params:[{}]", res, body);
    }

    /**
     * 取消关注订阅号
     */
    public static void subscribeUnFollow(String subscribeId, String userId, EduYidaApp app) {
        StringBuilder url = new StringBuilder();
        url.append(app.getAppUrl())
            .append(YidaAppConstant.SUBSCRIBE_UN_FOLLOW);
        JSONObject body = new JSONObject() {{
            set("userId", userId);
            set("accountId", subscribeId);
        }};
        String res = HttpUtil.get(url.toString(), body);
        log.info("取消关注订阅号,res:[{}],params:[{}]", res, body);
    }

    /**
     * 删除订阅号
     */
    public static void subscribeDelete(String[] ids, EduYidaApp app) {
        StringBuilder url = new StringBuilder();
        url.append(app.getAppUrl())
            .append(YidaAppConstant.SUBSCRIBE_DELETE);
        JSONObject param = new JSONObject() {{
            set("id", ArrayUtil.join(ids, ","));
        }};
        String res = HttpUtil.get(url.toString(), param);
        log.info("删除订阅号,res:[{}],params:[{}]", res, param);
    }

    /**
     * 发送订阅号消息
     */
    public static void sendMsg(AppNotice appNotice, EduYidaApp app) {
        StringBuilder url = new StringBuilder();
        url.append(app.getAppUrl()).append(YidaAppConstant.SUBSCRIBE_SEND_MSG);
        String body = JSONUtil.toJsonStr(appNotice);
        String res = HttpUtil.post(url.toString(), body);
        sendNoticeMsg(appNotice, app);
        log.info("发送订阅号消息,res:[{}],params:[{}]", res, body);
    }

    /**
     * 极光推送消息
     */
    public static void sendNoticeMsg(AppNotice appNotice, EduYidaApp app) {
        StringBuilder url = new StringBuilder();
        AppNotice appNotice1 = new AppNotice();
        BeanUtils.copyProperties(appNotice, appNotice1);
        appNotice1.setMsgList(null);
        appNotice1.getPushMessage().setContent("你有一条新消息");
        url.append(app.getAppUrl()).append(YidaAppConstant.JIGUANG_SEND_MSG);
//        url.append("http://10.143.132.192:8082/push/sendMulti").append(YidaAppConstant.JIGUANG_SEND_MSG);
        String body = JSONUtil.toJsonStr(appNotice1);
        // 1s后超时  不保证收到推送
        try {
            String res = HttpUtil.post(url.toString(), body, 1000);
            log.info("极光推送,res:[{}],params:[{}]", res, body);
        } catch (Exception e) {
            log.error("极光推送超时,url:[{}],params:[{}]", url, body);
        }
    }


    /**
     * 发送稿件
     */
    public static String publishManuscript(EduSchoolManuscript manuscript, EduYidaApp yidaApp, String columnId,
        String yidaUserId) {
        JSONObject body = new JSONObject() {{
            set("title", manuscript.getTitle());
            set("fileType", manuscript.getCoverType());
            set("type", 1);
            set("isPush", 1);
            set("isSub", 1);
            set("isPublish", 1);
            set("from", 2);
            set("isTop", 0);
            set("titleFilePath", manuscript.getCoverUrl());
            set("areaId", yidaApp.getAppAreaId());
            set("createById", yidaUserId);
        }};
        // 是否发布到栏目
        if (StrUtil.isNotBlank(columnId)) {
            body.set("columnId", columnId);
        }
        if (StrUtil.isNotBlank(manuscript.getContent())) {
            body.set("content", manuscript.getContent());
        }
        if (StrUtil.isNotBlank(manuscript.getContentUrl())) {
            body.set("contenUrl", manuscript.getContentUrl());
        }
        if (StrUtil.isNotBlank(manuscript.getYidaAppMunascriptId())) {
            body.set("id", manuscript.getYidaAppMunascriptId());
        }
        String res = HttpUtil.post(yidaApp.getAppUrl() + YidaAppConstant.MANUSCRIPT_SAVE, body);
        JSONObject resJson = JSONUtil.parseObj(res);
        log.info("易达发送稿件,res:[{}],params:[{}]", res, body);
        if (resJson.getInt("status") == 200) {
            return resJson.getJSONObject("data").getStr("contentId");
        }
        return null;
    }


    /**
     * 设置栏目下稿件的置顶
     *
     * @param manuscriptId 稿件id
     * @param columnId     栏目id
     * @param isTop        0-不置顶，1-置顶
     * @param yidaApp
     */
    public static void setTop(String manuscriptId, String columnId, Integer isTop, EduYidaApp yidaApp) {
        JSONObject body = new JSONObject() {{
            set("coreContentId", manuscriptId);
            set("columnId", columnId);
            set("isTop", isTop);
        }};
        HttpUtil.post(yidaApp.getAppUrl() + YidaAppConstant.MANUSCRIPT_TOP, body);
    }

    /**
     * @param manuscriptId
     * @param isTop        0-不置顶，1-置顶
     * @return
     */
    public static String topManuscript(String manuscriptId, EduYidaApp yidaApp, Integer isTop) {
        JSONObject body = new JSONObject() {{
            set("isTop", isTop);
            set("id", manuscriptId);
        }};
        String res = HttpUtil.post(yidaApp.getAppUrl() + YidaAppConstant.MANUSCRIPT_SAVE, body);
        JSONObject resJson = JSONUtil.parseObj(res);
        if (resJson.getInt("status") == 200) {
            return resJson.getJSONObject("data").getStr("contentId");
        }
        return null;
    }

    /**
     * 删除稿件
     */
    public static void manuscriptDel(List<String> ids, EduYidaApp yidaApp) {
        JSONObject body = new JSONObject() {{
            set("ids", CollUtil.join(ids, ","));
        }};
        HttpUtil.post(yidaApp.getAppUrl() + YidaAppConstant.MANUSCRIPT_DEL, body);
    }

    /**
     * 区域位配置
     */
    public static String regionUpdate(String regionId, String name, Integer sort, String columnIds,
        String type, JSONArray contentJson, EduYidaApp yidaApp) {
        JSONObject body = new JSONObject() {{
            set("name", name);
            set("contentType", 0);
            set("sortNum", sort);
            set("styleType", type);
            set("columnIds", columnIds);
            set("areaId", yidaApp.getAppAreaId());
            set("contentJson", contentJson.toString().replace("\\", ""));
        }};
        if (StrUtil.isNotBlank(regionId)) {
            body.set("id", regionId);
            body.set("oldColumnId", columnIds);
        }
        String res = HttpUtil.post(yidaApp.getAppUrl() + YidaAppConstant.REGION_SAVE, body);
        JSONObject resJson = JSONUtil.parseObj(res);
        log.info("保存易达区域位,res:[{}],params:[{}]", res, body.toString());
        if (resJson.getInt("status") == 200) {
            JSONObject colIdJson = JSONUtil.parseObj(resJson.get("data"));
            return colIdJson.getStr("dataId");
        }
        return null;
    }

    /**
     * 区域位添加内容
     */
    public static void regionSaveContent(String regionId, String contentId, Integer sortNum,
        String columnId, EduYidaApp yidaApp) {
        JSONObject body = new JSONObject() {{
            set("regionId", regionId);
            set("contentId", contentId);
            set("sortNum", sortNum);
            set("columnId", columnId);
        }};
        if (StrUtil.isNotBlank(regionId)) {
            body.set("id", regionId);
        }
        String res = HttpUtil.post(yidaApp.getAppUrl() + YidaAppConstant.REGION_SAVE_CONTENT, body);
        log.info("易达区域位添加内容,res:[{}],params:[{}]", res, body);
    }

    /**
     * 学校信息account_funcition保存
     */
    public static String functionSave(EduSchoolHomeMicroCol col, EduYidaApp yidaApp) {
        JSONObject body = new JSONObject() {{
            set("functionName", col.getName());
            set("htmlUrl", col.getUrl());
            set("imgUrl", col.getCoverUrl());
            set("sortNum", col.getSort());
            set("area_id", yidaApp.getAppAreaId());
        }};
        if (col.getYidaAppFunctionId() != null) {
            body.set("id", col.getYidaAppFunctionId());
        }
        // 2021.11.10 从post表单提交改成post fuck
        // 2021.11.11 从post改成post表单 fuck
        // 两微一端版本可能会导致请求数据方式不一样
        String res = HttpUtil.post(yidaApp.getAppUrl() + YidaAppConstant.FUNCTION_SAVE, body);
        JSONObject resJson = JSONUtil.parseObj(res);
        log.info("易达function保存,res:[{}],params:[{}]", res, body);
        if (resJson.getInt("status") == 200) {
            return resJson.get("data").toString();
        }
        return null;
    }

    /**
     * 修改banner
     */
    public static void bannerUpdate(String colId, List<String> url,
        List<Integer> sort, EduYidaApp yidaApp) {
        StringBuilder typeCarousel = new StringBuilder();
        for (int i = 0; i < url.size(); i++) {
            typeCarousel.append("2,");
        }
        JSONObject body = new JSONObject() {{
            set("id", colId);
            set("numCarousel", url.size());
            set("areaId", yidaApp.getAppAreaId());
            set("typeCarouselUrl", CollUtil.join(url, ","));
            set("typeCarousel", typeCarousel.substring(0, typeCarousel.length() - 1));
            set("sortNum", CollUtil.join(sort, ","));
        }};
        String res = HttpUtil.post(yidaApp.getAppUrl() + YidaAppConstant.BANNER_UPDATE, body);
        log.info("易达banner保存,res:[{}],params:[{}]", res, body);
    }

    /**
     * 创建用户
     */
    public static String userSave(String mobile, String nickname, EduYidaApp yidaApp) {
        String appUserId = null;
        JSONObject body = new JSONObject() {{
            set("mobile", mobile);
            set("nickname", nickname);
            set("systemId", "edu");
            set("areaId", yidaApp.getAppAreaId());
        }};
        String res = HttpUtil.get(yidaApp.getAppUrl() + YidaAppConstant.USER_SAVE, body);
        JSONObject resJson = JSONUtil.parseObj(res);
        log.info("易达app创建用户,res:[{}],params:[{}]", res, body);
        if (resJson.getInt("status") == 200) {
            // 用户
            appUserId = resJson.getJSONObject("data").getStr("id");
        }
        return appUserId;
    }

    public static String REGION_TYPE_NOTICE = "Notice";

    public static String REGION_TYPE_HOT = "HotSchool";

    public static String REGION_TYPE_INFO = "SchoolInfo";

    // =====================小程序=========================

    /**
     * 查询两微一端小程序类型数据
     *
     * @param areaId  区域id
     * @param yidaApp 两微一端后台具体参数
     * @author ZYJ
     * @date 2021/12/10 17:02
     */
    public static void smallProgramTypeList(String areaId, EduYidaApp yidaApp) {
        JSONObject paramMap = new JSONObject();
        paramMap.set("areaId", areaId);
        String res = HttpUtil.get(yidaApp.getAppUrl() + YidaAppConstant.SMALL_PROGRAM_TYPE_LIST, paramMap);
        JSONObject resJson = JSONUtil.parseObj(res);
        log.info("查询两微一端小程序类型数据, res:[{}], params:[{}]", res, paramMap);
        if (resJson.getInt(STATUS_NAME) != HttpStatus.HTTP_ACCEPTED) {
            throw new FebsException("保存小程序数据失败");
        }
    }


    /**
     * 保存两微一端小程序接口
     *
     * @param yiDaSmallProgramVO 保存的小程序数据
     * @param yidaApp            两微一端后台具体参数
     * @return java.lang.String
     * @author ZYJ
     * @date 2021/12/10 16:42
     */
    public static String smallProgramSave(YiDaSmallProgramVO yiDaSmallProgramVO, EduYidaApp yidaApp, String url) {
        Map<String, Object> paramMap = Convert.toMap(String.class, Object.class, yiDaSmallProgramVO);
        //小程序图标
        paramMap.put("file", new File(FileUtil.downloadToLocal(yiDaSmallProgramVO.getIconUrl())));
        paramMap.put("bigImgFile", new File(FileUtil.downloadToLocal(yiDaSmallProgramVO.getIconUrl())));

        if (ObjectUtil.isEmpty(url)) {
            paramMap.put("shareImgFile", new File(FileUtil.downloadToLocal(yiDaSmallProgramVO.getIconUrl())));
        } else {
            paramMap.put("shareImgFile", new File(FileUtil.downloadToLocal(url)));
        }
        String res = HttpUtil.post(yidaApp.getAppUrl() + YidaAppConstant.SMALL_PROGRAM_SAVE, paramMap);
        JSONObject resJson = JSONUtil.parseObj(res);
        log.info("易达两微一端保存小程序, res:[{}], params:[{}]", res, paramMap);
        if (!"成功".equals(resJson.get("message"))) {
            throw new FebsException("保存小程序数据失败");
        }
        return resJson.getJSONObject(DATA_NAME).getStr("id");
    }


    /**
     * 栏目小程序配置保存接口
     *
     * @param yidaApp  两微一端后台具体参数
     * @param columnId 栏目id
     * @author ZYJ
     * @date 2021/12/10 17:22
     */
    public static void columnSmallProgramSave(EduYidaApp yidaApp, String columnId, Map<String, Object> paramMap) {
        paramMap.put("columnId", columnId);
        String res = HttpUtil.post(yidaApp.getAppUrl() + YidaAppConstant.COLUMN_SMALL_PROGRAM_SAVE,
            JSONUtil.toJsonStr(paramMap));
        JSONObject resJson = JSONUtil.parseObj(res);
        log.info("易达两微一端栏目小程序配置保存接口, res:[{}], params:[{}]", res, paramMap);
        if (resJson.getInt(STATUS_NAME) != HttpStatus.HTTP_ACCEPTED) {
            throw new FebsException("保存栏目小程序配置失败");
        }
    }

    /**
     * 小程序跳转配置保存接口
     *
     * @param yidaApp        两微一端后台具体参数
     * @param smallProgramId 小程序id
     * @author ZYJ
     * @date 2021/12/10 17:25
     */
    public static void smallProgramLocationSave(EduYidaApp yidaApp, String smallProgramId) {
        JSONObject paramMap = new JSONObject();
        paramMap.set("id", smallProgramId);
        String res = HttpUtil.post(yidaApp.getAppUrl() + YidaAppConstant.SMALL_PROGRAM_LOCATION_SAVE, paramMap);
        JSONObject resJson = JSONUtil.parseObj(res);
        log.info("易达两微一端小程序跳转配置保存接口, res:[{}], params:[{}]", res, paramMap);
        if (resJson.getInt(STATUS_NAME) != HttpStatus.HTTP_ACCEPTED) {
            throw new FebsException("小程序配置跳转失败");
        }
    }

    /**
     * 小程序删除接口
     *
     * @param yidaApp        两微一端后台具体参数
     * @param smallProgramId 小程序id
     * @author ZYJ
     * @date 2021/12/10 17:36
     */
    public static void smallProgramDelete(EduYidaApp yidaApp, String smallProgramId) {
        JSONObject paramMap = new JSONObject();
        paramMap.set("id", smallProgramId);
        String res = HttpUtil.post(yidaApp.getAppUrl() + YidaAppConstant.SMALL_PROGRAM_DELETE, paramMap);
        log.info("易达两微一端小程序删除接口, res:[{}], params:[{}]", res, paramMap);
        if ("成功".equals(res)) {
            throw new FebsException("删除小程序失败");
        }
    }
}
