package com.happy.action;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baidubce.model.User;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.happy.Model.*;
import com.happy.Model.weixin.Users;
import com.happy.Until.*;
import com.happy.Until.Enum.DataType;
import com.happy.common.controller.BaseController;
import com.happy.common.http.HttpsClient;
import com.happy.constant.ConstDefault;
import com.happy.constant.ResultStatusCode;
import com.happy.dto.ArticleCommentDto;
import com.happy.dto.ArticleTweetDto;
import com.happy.dto.IPage;
import com.happy.service.*;
import com.happy.vo.*;
import com.opensymphony.xwork2.ModelDriven;
import lombok.SneakyThrows;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.apache.struts2.ServletActionContext;
import org.aspectj.weaver.ast.Var;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

import static com.happy.common.http.HttpsClient.httpsRequestReturnString;

public class articleTweetAction extends BaseController implements ModelDriven<ArticleTweetDto> {

    private final ArticleTweetDto articleTweetDto = new ArticleTweetDto();

    @Override
    public ArticleTweetDto getModel() {
        return articleTweetDto;
    }

    @Resource
    public ArticleTweetService articleTweetService;
    @Resource
    public HousePriceService housePriceService;
    @Resource
    public HotelDictService hotelDictService;
    @Resource
    public WorkflowService workflowService;
    @Resource
    public HouseService houseService;
    @Resource
    public UserService userService;
    @Resource
    public AdminManagerService adminManagerService;

    public String key;
    public String startTime;
    public String endTime;
    public String keyWord;
    public String userName;

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public String getStartTime() {
        return startTime;
    }

    public void setStartTime(String startTime) {
        this.startTime = startTime;
    }

    public String getEndTime() {
        return endTime;
    }

    public void setEndTime(String endTime) {
        this.endTime = endTime;
    }

    public String getKeyWord() {
        return keyWord;
    }

    public void setKeyWord(String keyWord) {
        this.keyWord = keyWord;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    /**
     * 推文发布
     */
    public String insertArticleTweet() throws ParseException {
        Gson gson = new Gson();
        JSONObject jsonObject = new JSONObject();
        com.alibaba.fastjson.JSONObject json = GetHttpParam.getHttpParam(request);
        ArticleTweetDto articleTweetDto = gson.fromJson(json.toString(), new TypeToken<ArticleTweetDto>() {
        }.getType());
        //图片和视频判断
        if (articleTweetDto.getImages() == null && articleTweetDto.getVideo() == null) {
            jsonObject.put("code", 500);
            jsonObject.put("message", "请上传图片或视频");
            jsonObject.put("data", null);
            ResponseUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
            return null;
        }
        //图片最多上传九张
        if (articleTweetDto.getImages() != null && articleTweetDto.getImages().size() > 9) {
            jsonObject.put("code", 500);
            jsonObject.put("message", "最多上传9张图片");
            jsonObject.put("data", null);
            ResponseUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
            return null;
        }
        //标题、内容、地点、关联民宿不能为空
        if (Func.checkNull(articleTweetDto.getTitle()) || Func.checkNull(articleTweetDto.getContent())
                || Func.checkNull(articleTweetDto.getTownId()) || articleTweetDto.getHotelIds() == null
                || articleTweetDto.getCreateId() == null) {
            jsonObject.put("code", 500);
            jsonObject.put("message", "参数不能为空");
            jsonObject.put("data", null);
            ResponseUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
            return null;
        }
        //推文发布参数
        System.out.println("推文发布参数：" + JSON.toJSON(articleTweetDto));
        //查询当前用户
        Users user = userService.queryByUserId(String.valueOf(articleTweetDto.getCreateId()));
        if (user == null) {
            jsonObject.put("code", 500);
            jsonObject.put("message", "用户信息已失效，查看详情失败");
            jsonObject.put("data", null);
            ResponseUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
            return null;
        }
        Date now = DateUtil.formateDate(DateUtil.getCurrentDate(), DateUtil.Time_Formatter_Second);
        try {
            //添加推文
            ArticleTweet data = new ArticleTweet();
            data.setUserId(articleTweetDto.getCreateId());
            data.setTitle(articleTweetDto.getTitle());
            data.setContent(articleTweetDto.getContent());
            data.setLocationId(articleTweetDto.getTownId());
            data.setHotelId(StringUtils.join(articleTweetDto.getHotelIds(), ","));
            data.setCreateId(articleTweetDto.getCreateId());
            data.setCreateDate(now);
            data.setApprove(1);//正在审批
            data.setStatus(1);
            data.setPublishWay("小程序");
            data.setIsTop(0);
            data.setUserName(user.getUser_name());
            data.setUserPhoto(user.getHeadPhoto() == null ? ConstDefault.DefaultHeadPhoto : user.getHeadPhoto());
            int aId = articleTweetService.insert(data);
            if (aId <= 0) {
                ResUtil.writeJson(ServletActionContext.getResponse(), new JSONObject() {{
                    put("message", "推文发布失败");
                    put("code", 500);
                }}.toString());

                return null;
            }
            //添加附件
            List<String> fileStr = new ArrayList<>();
            if (articleTweetDto.getImages() != null && articleTweetDto.getImages().size() > 0) {
                fileStr = articleTweetDto.getImages();
            } else {
                fileStr.add(articleTweetDto.getVideo());
            }
            List<ArticleFileInfo> afis = new ArrayList<>();
            for (String f : fileStr) {
                String[] split = f.split("/");
                String fileName = split[split.length - 1];
                ArticleFileInfo afi = new ArticleFileInfo();
                afi.setLinkId(aId);
                afi.setName(fileName);
                afi.setType(1);
                afi.setUrl(f);
                afi.setCreateDate(now);
                afis.add(afi);
            }
            int length = articleTweetService.insertArticleFileBatch(afis);
            if (length <= 0) {
                ResUtil.writeJson(ServletActionContext.getResponse(), new JSONObject() {{
                    put("message", "推文附件新增失败");
                    put("code", 500);
                }}.toString());
                return null;
            }
            //添加流程
            Workflow workflow = new Workflow();
            String id = String.valueOf(UUID.randomUUID());
            workflow.setLinkId(String.valueOf(aId));//存推文的ID
            workflow.setCreateId(String.valueOf(articleTweetDto.getCreateId()));
            workflow.setTitle(articleTweetDto.getTitle());
            workflow.setRemark(articleTweetDto.getContent());
            workflow.setId(id);
            workflow.setStatus(1);//1是正在审批
            workflow.setType(3);//3是推文
            workflow.setCoverImg(articleTweetDto.getImages() != null && articleTweetDto.getImages().size() > 0 ? articleTweetDto.getImages().get(0) : articleTweetDto.getVideo());
            int i = workflowService.insert(workflow);
            if (i <= 0) {
                ResUtil.writeJson(ServletActionContext.getResponse(), new JSONObject() {{
                    put("message", "推文流程发布失败");
                    put("code", 500);
                }}.toString());
                return null;
            }
        } catch (Exception e) {
            System.out.println("推文发布异常：" + e.getMessage());
            ResUtil.writeJson(ServletActionContext.getResponse(), new JSONObject() {{
                put("message", "推文发布异常");
                put("code", 500);
            }}.toString());
            return null;
        }
        ResUtil.writeJson(ServletActionContext.getResponse(), new JSONObject() {{
            put("message", "推文发布成功");
            put("code", 200);
        }}.toString());
        return null;
    }

    /**
     * 管理端推文发布
     */
    public String insertArticleTweetMana() throws ParseException {
        Gson gson = new Gson();
        JSONObject jsonObject = new JSONObject();
        com.alibaba.fastjson.JSONObject json = GetHttpParam.getHttpParam(request);
        ArticleTweetDto articleTweetDto = gson.fromJson(json.toString(), new TypeToken<ArticleTweetDto>() {
        }.getType());
        //图片和视频判断
        if (articleTweetDto.getImages() == null && articleTweetDto.getVideo() == null) {
            jsonObject.put("code", 500);
            jsonObject.put("message", "请上传图片或视频");
            jsonObject.put("data", null);
            ResponseUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
            return null;
        }
        //图片最多上传九张
        if (articleTweetDto.getImages() != null && articleTweetDto.getImages().size() > 9) {
            jsonObject.put("code", 500);
            jsonObject.put("message", "最多上传9张图片");
            jsonObject.put("data", null);
            ResponseUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
            return null;
        }
        //标题、内容、地点、关联民宿不能为空
        if (Func.checkNull(articleTweetDto.getTitle()) || Func.checkNull(articleTweetDto.getContent())
                || Func.checkNull(articleTweetDto.getTownId()) || articleTweetDto.getHotelIds() == null
                || articleTweetDto.getCreateId() == null) {
            jsonObject.put("code", 500);
            jsonObject.put("message", "参数不能为空");
            jsonObject.put("data", null);
            ResponseUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
            return null;
        }
        //推文发布参数
        System.out.println("推文发布参数：" + JSON.toJSON(articleTweetDto));

        //查询当前用户
        Users user = userService.queryByUserId(String.valueOf(articleTweetDto.getCreateId()));
        if (user == null) {
            jsonObject.put("code", 500);
            jsonObject.put("message", "用户信息已失效，查看详情失败");
            jsonObject.put("data", null);
            ResponseUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
            return null;
        }
        List<ArticleTweet> articleTweets = articleTweetService.queryTops();
        if (articleTweets!=null && articleTweets.size()>=3 && articleTweetDto.getIsTop()==1){
            jsonObject.put("code", 500);
            jsonObject.put("message", "置顶攻略不可超过3个");
            jsonObject.put("data", null);
            ResponseUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
            return null;
        }
        Date now = DateUtil.formateDate(DateUtil.getCurrentDate(), DateUtil.Time_Formatter_Second);
        try {
            //添加推文
            ArticleTweet data = new ArticleTweet();
            data.setUserId(articleTweetDto.getCreateId());
            data.setTitle(articleTweetDto.getTitle());
            data.setContent(articleTweetDto.getContent());
            data.setLocationId(articleTweetDto.getTownId());
            data.setHotelId(StringUtils.join(articleTweetDto.getHotelIds(), ","));
            data.setCreateId(articleTweetDto.getCreateId());
            data.setCreateDate(now);
            data.setApprove(2);//正在审批
            data.setStatus(1);
            data.setPublishWay("管理端");
            data.setIsTop(articleTweetDto.getIsTop());
            data.setUserName(user.getUser_name());
            data.setUserPhoto(user.getHeadPhoto() == null ? ConstDefault.DefaultHeadPhoto : user.getHeadPhoto());
            int aId = articleTweetService.insert(data);
            if (aId <= 0) {
                ResUtil.writeJson(ServletActionContext.getResponse(), new JSONObject() {{
                    put("message", "推文发布失败");
                    put("code", 500);
                }}.toString());

                return null;
            }
            //添加附件
            List<String> fileStr = new ArrayList<>();
            if (articleTweetDto.getImages() != null && articleTweetDto.getImages().size() > 0) {
                fileStr = articleTweetDto.getImages();
            } else {
                fileStr.add(articleTweetDto.getVideo());
            }
            List<ArticleFileInfo> afis = new ArrayList<>();
            for (String f : fileStr) {
                String[] split = f.split("/");
                String fileName = split[split.length - 1];
                ArticleFileInfo afi = new ArticleFileInfo();
                afi.setLinkId(aId);
                afi.setName(fileName);
                afi.setType(1);
                afi.setUrl(f);
                afi.setCreateDate(now);
                afis.add(afi);
            }
            int length = articleTweetService.insertArticleFileBatch(afis);
            if (length <= 0) {
                ResUtil.writeJson(ServletActionContext.getResponse(), new JSONObject() {{
                    put("message", "推文附件新增失败");
                    put("code", 500);
                }}.toString());
                return null;
            }
            //添加流程
            Workflow workflow = new Workflow();
            String id = String.valueOf(UUID.randomUUID());
            workflow.setLinkId(String.valueOf(aId));//存推文的ID
            workflow.setCreateId(String.valueOf(articleTweetDto.getCreateId()));
            workflow.setTitle(articleTweetDto.getTitle());
            workflow.setRemark(articleTweetDto.getContent());
            workflow.setId(id);
            workflow.setStatus(2);//1是正在审批
            workflow.setType(3);//3是推文
            workflow.setCoverImg(articleTweetDto.getImages() != null && articleTweetDto.getImages().size() > 0 ? articleTweetDto.getImages().get(0) : articleTweetDto.getVideo());
            int i = workflowService.insert(workflow);
            if (i <= 0) {
                ResUtil.writeJson(ServletActionContext.getResponse(), new JSONObject() {{
                    put("message", "推文流程发布失败");
                    put("code", 500);
                }}.toString());
                return null;
            }
        } catch (Exception e) {
            System.out.println("推文发布异常：" + e.getMessage());
            ResUtil.writeJson(ServletActionContext.getResponse(), new JSONObject() {{
                put("message", "推文发布异常");
                put("code", 500);
            }}.toString());
            return null;
        }
        ResUtil.writeJson(ServletActionContext.getResponse(), new JSONObject() {{
            put("message", "推文发布成功");
            put("code", 200);
        }}.toString());

        return null;
    }

    /**
     * 管理端修改推文
     */
    public String updateArticleTweetMana() throws ParseException {
        Gson gson = new Gson();
        JSONObject jsonObject = new JSONObject();
        com.alibaba.fastjson.JSONObject json = GetHttpParam.getHttpParam(request);
        ArticleTweetDto articleTweetDto = gson.fromJson(json.toString(), new TypeToken<ArticleTweetDto>() {
        }.getType());
        //图片和视频判断
        if (articleTweetDto.getImages() == null && articleTweetDto.getVideo() == null) {
            jsonObject.put("code", 500);
            jsonObject.put("message", "请上传图片或视频");
            jsonObject.put("data", null);
            ResponseUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
            return null;
        }
        //图片最多上传九张
        if (articleTweetDto.getImages() != null && articleTweetDto.getImages().size() > 9) {
            jsonObject.put("code", 500);
            jsonObject.put("message", "最多上传9张图片");
            jsonObject.put("data", null);
            ResponseUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
            return null;
        }
        //标题、内容、地点、关联民宿不能为空
        if (Func.checkNull(articleTweetDto.getTitle()) || Func.checkNull(articleTweetDto.getContent())
                || Func.checkNull(articleTweetDto.getTownId()) || articleTweetDto.getHotelIds() == null
                || articleTweetDto.getCreateId() == null || articleTweetDto.getId()==null) {
            jsonObject.put("code", 500);
            jsonObject.put("message", "参数不能为空");
            jsonObject.put("data", null);
            ResponseUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
            return null;
        }
        //推文发布参数
        System.out.println("推文发布参数：" + JSON.toJSON(articleTweetDto));

        //查询当前用户
        Users user = userService.queryByUserId(String.valueOf(articleTweetDto.getCreateId()));
        if (user == null) {
            jsonObject.put("code", 500);
            jsonObject.put("message", "用户信息已失效，查看详情失败");
            jsonObject.put("data", null);
            ResponseUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
            return null;
        }
        List<ArticleTweet> articleTweets = articleTweetService.queryTops();
        if (articleTweets!=null && articleTweets.size()>=3 && articleTweetDto.getIsTop()==1){
            List<Integer> ids = articleTweets.stream().map(ArticleTweet::getId).collect(Collectors.toList());
            if (!ids.contains(articleTweetDto.getId())){
                jsonObject.put("code", 500);
                jsonObject.put("message", "置顶攻略不可超过3个");
                jsonObject.put("data", null);
                ResponseUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
                return null;
            }
        }
        Date now = DateUtil.formateDate(DateUtil.getCurrentDate(), DateUtil.Time_Formatter_Second);
        try {
            //添加推文
            ArticleTweet data = new ArticleTweet();
            data.setId(articleTweetDto.getId());
            data.setUserId(articleTweetDto.getCreateId());
            data.setTitle(articleTweetDto.getTitle());
            data.setContent(articleTweetDto.getContent());
            data.setLocationId(articleTweetDto.getTownId());
            data.setHotelId(StringUtils.join(articleTweetDto.getHotelIds(), ","));
            data.setCreateId(articleTweetDto.getCreateId());
            data.setCreateDate(now);
            data.setApprove(2);//1正在审批
            data.setStatus(1);
            data.setPublishWay("管理端");
            data.setIsTop(articleTweetDto.getIsTop());
            data.setUserName(user.getUser_name());
            data.setUserPhoto(user.getHeadPhoto() == null ? ConstDefault.DefaultHeadPhoto : user.getHeadPhoto());
            int aId = articleTweetService.update(data);
            if (aId <= 0) {
                ResUtil.writeJson(ServletActionContext.getResponse(), new JSONObject() {{
                    put("message", "推文发布失败");
                    put("code", 500);
                }}.toString());

                return null;
            }
        } catch (Exception e) {
            System.out.println("推文发布异常：" + e.getMessage());
            ResUtil.writeJson(ServletActionContext.getResponse(), new JSONObject() {{
                put("message", "推文发布异常");
                put("code", 500);
            }}.toString());
            return null;
        }
        ResUtil.writeJson(ServletActionContext.getResponse(), new JSONObject() {{
            put("message", "推文发布成功");
            put("code", 200);
        }}.toString());

        return null;
    }

    // 操作推文-删除文件
    public String delFile(){
        JSONObject jsonObject = new JSONObject();
        com.alibaba.fastjson.JSONObject json = GetHttpParam.getHttpParam(request);
        Integer id = json.getInteger("id");
        int m = articleTweetService.delArticleFileBatch(id);
        if (m>0){
            jsonObject.put("code", 200);
            jsonObject.put("message", "删除成功");
            ResponseUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
            return null;
        }
        jsonObject.put("code", 500);
        jsonObject.put("message", "删除失败");
        ResponseUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
        return null;
    }

    // 操作推文-增加文件
    public String addFile() throws ParseException {
        JSONObject jsonObject = new JSONObject();
        com.alibaba.fastjson.JSONObject json = GetHttpParam.getHttpParam(request);
        Integer id = json.getInteger("id");
        String images = json.getString("images");
        String video = json.getString("video");
        //图片和视频判断
        if (images.equals("") && video.equals("")) {
            jsonObject.put("code", 500);
            jsonObject.put("message", "请上传图片或视频");
            jsonObject.put("data", null);
            ResponseUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
            return null;
        }
        String fileStr = "";
        if (!images.equals("")) {
            fileStr=images;
        } else {
            fileStr=video;
        }

        Date now = DateUtil.formateDate(DateUtil.getCurrentDate(), DateUtil.Time_Formatter_Second);
        String[] split = fileStr.split("/");
        String fileName = split[split.length - 1];
        ArticleFileInfo afi = new ArticleFileInfo();
        afi.setLinkId(id);
        afi.setName(fileName);
        afi.setType(1);
        afi.setUrl(fileStr);
        afi.setCreateDate(now);
        int length = articleTweetService.insertArticleFile(afi);
        if (length <= 0) {
            ResUtil.writeJson(ServletActionContext.getResponse(), new JSONObject() {{
                put("message", "新增失败");
                put("code", 500);
                put("data", null);
            }}.toString());
            return null;
        }
        ResUtil.writeJson(ServletActionContext.getResponse(), new JSONObject() {{
            put("message", "新增成功");
            put("code", 200);
            put("data", length);
        }}.toString());
        return null;
    }

    // 删除推文
    public String delArticle(){
        JSONObject jsonObject = new JSONObject();
        com.alibaba.fastjson.JSONObject json = GetHttpParam.getHttpParam(request);
        Integer id = json.getInteger("id");
        int m = articleTweetService.delArticle(id);
        int n = articleTweetService.delArticleFile(id);
        if (m>0 && n>0){
            jsonObject.put("code", 200);
            jsonObject.put("message", "删除成功");
            ResponseUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
            return null;
        }
        jsonObject.put("code", 500);
        jsonObject.put("message", "删除失败");
        ResponseUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
        return null;
    }

    // 置顶推文
    public String topArticle(){
        Gson gson = new Gson();
        JSONObject jsonObject = new JSONObject();
        com.alibaba.fastjson.JSONObject json = GetHttpParam.getHttpParam(request);
        ArticleTweetDto articleTweetDto = gson.fromJson(json.toString(), new TypeToken<ArticleTweetDto>() {}.getType());
        List<ArticleTweet> articleTweets = articleTweetService.queryTops();
        if (articleTweets!=null && articleTweets.size()>=3 && articleTweetDto.getIsTop()==1){
            List<Integer> ids = articleTweets.stream().map(ArticleTweet::getId).collect(Collectors.toList());
            if (!ids.contains(articleTweetDto.getId())){
                jsonObject.put("code", 500);
                jsonObject.put("message", "置顶攻略不可超过3个");
                jsonObject.put("data", null);
                ResponseUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
                return null;
            }
        }
        int m = articleTweetService.updateArticleTop(articleTweetDto);
        if (m>0){
            jsonObject.put("code", 200);
            jsonObject.put("message", "修改成功");
            jsonObject.put("data", null);
            ResponseUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
            return null;
        }
        jsonObject.put("code", 500);
        jsonObject.put("message", "修改失败");
        jsonObject.put("data", null);
        ResponseUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
        return null;
    }

    public String queryManageArticlePage() {
        JSONObject jsonObject = new JSONObject();
        IPage<ArticleListVo> result = articleTweetService.queryManageArticlesPage(articleTweetDto.getKeyWord(), null, page, rows);
        if (result.getPageList().size() > 0) {
            String articleIds = StringUtils.join(result.getPageList().stream().map(ArticleListVo::getId).collect(Collectors.toList()), ",");
            List<FileInfo> fileInfos = articleTweetService.queryList("and link_id in (" + articleIds + ")");

            for (ArticleListVo data : result.getPageList()) {
                if (fileInfos != null) {
                    List<FileInfo> fileInfoList = fileInfos.stream().filter(e -> e.getLinkId().equals(data.getId().toString())).collect(Collectors.toList());
                    if (fileInfoList != null) {
                        if (fileInfoList.size() > 1) {
                            data.setImage(fileInfoList.get(0).getUrl());
                        } else if (fileInfoList.size() == 1) {
                            String url = fileInfoList.get(0).getUrl();
                            if (!url.endsWith("jpg") && !url.endsWith("png")) {
                                data.setVideo(fileInfoList.get(0).getUrl());
                            } else {
                                data.setImage(url);
                            }
                        }
                    }
                }
            }
        }

        jsonObject.put("code", ResultStatusCode.OK.getStatus());
        jsonObject.put("message", "请求成功");
        jsonObject.put("data", result);
        ResponseUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());

        return null;
    }


    /**
     * 根据推文数据ID查询推文详情数据
     *
     * @return
     */
    public String queryDetail() {
        JSONObject jsonObject = new JSONObject();
        //图片和视频判断
        if (articleTweetDto.getId() == null || articleTweetDto.getUserId() == null) {
            jsonObject.put("code", 500);
            jsonObject.put("message", "推文ID或用户ID不能为空");
            jsonObject.put("data", null);
            ResponseUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
            return null;
        }

        //查询当前用户
        Users user = userService.queryByUserId(String.valueOf(articleTweetDto.getUserId()));
        if (user == null) {
            jsonObject.put("code", 500);
            jsonObject.put("message", "用户信息已失效，查看详情失败");
            jsonObject.put("data", null);
            ResponseUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
            return null;
        }

        //查询推文数据
        ArticleTweet data = articleTweetService.queryArticleById(String.valueOf(articleTweetDto.getId()), articleTweetDto.getUserId());
        if (data == null) {
            jsonObject.put("code", 500);
            jsonObject.put("message", "推文数据已失效，查看详情失败");
            jsonObject.put("data", null);
            ResponseUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
            return null;
        }

        ArticleDetailVo result = new ArticleDetailVo();
        result.setIsCollect(data.getIsCollect());
        result.setId(data.getId());
        List<FileInfo> fileInfoList = articleTweetService.queryList("and link_id = '" + articleTweetDto.getId() + "'");
        if (fileInfoList != null) {
            if (fileInfoList.size() > 1) {
                result.setImages(fileInfoList.stream().map(FileInfo::getUrl).collect(Collectors.toList()));
            } else if (fileInfoList.size() == 1) {
                String url = fileInfoList.get(0).getUrl();
                if (!url.endsWith("jpg") && !url.endsWith("png")) {
                    result.setVideo(fileInfoList.get(0).getUrl());
                } else {
                    List<String> images = new ArrayList<>();
                    images.add(url);
                    result.setImages(images);
                }
            }
        }

        result.setUserId(data.getUserId());
        result.setUserName(data.getUserName());
        result.setUserPhoto(data.getUserPhoto() == null ? ConstDefault.DefaultHeadPhoto : data.getUserPhoto());
        //region 关注
        if (articleTweetDto.getUserId().equals(data.getUserId())) {
            result.setIsFollow(2);//自己的推文
        } else {
            //是否关注
            UserCollect uc = articleTweetService.queryUserCollect(data.getUserId(), articleTweetDto.getUserId());
            result.setIsFollow(uc == null ? 0 : 1);//已关注给0；未关注给1
        }
        //endregion
        result.setTitle(data.getTitle());
        result.setContent(data.getContent());
        result.setDateStr(TimeExchange.DateToString(data.getCreateDate(), "yyyy-MM-dd"));
        result.setTownId(data.getLocationId());
        result.setTownName(data.getLocationName());

        //region 民宿列表
        //根据乡镇ID获取
        List<String> hotelIds = user.getCollect_hotel() == null ? new ArrayList<>() : Arrays.asList(user.getCollect_hotel().split(","));
        String sql = "id in (" + data.getHotelId() + ")";
        List<HotelVo> hotels = articleTweetService.queryHotels(sql);
        List<HotelListVo> hotelDatas = new ArrayList<>();

        //region 最低价
        List<Integer> managerIds = hotels.stream().map(HotelVo::getManagerId).collect(Collectors.toList());
        List<HotelPriceDataVo> prices = housePriceService.queryHotelPriceDatas(StringUtils.join(managerIds, ","), TimeExchange.getDateStr());

        List<HotelPriceOneDataVo> oneDatas = new ArrayList<>();
        //获取当天的
        for (HotelPriceDataVo hp : prices) {
            HotelPriceOneDataVo oneData = new HotelPriceOneDataVo();
            oneData.setSetDate(TimeExchange.getDateStr());
            oneData.setCreateDate(hp.getCreateDate());
            oneData.setPrice(hp.getPrice());
            oneData.setManagerId(hp.getManagerId());
            oneDatas.add(oneData);
        }

        /**
         * 根据房型ID处理重复的数据
         */
        List<HotelPriceOneDataVo> newOneDatas = new ArrayList<>();
        if (oneDatas.size() > 0) {
            for (Integer managerId : managerIds) {
                Optional<HotelPriceOneDataVo> one = oneDatas.stream().filter(e -> e.getManagerId().equals(managerId)).sorted(Comparator.comparing(HotelPriceOneDataVo::getCreateDate, Comparator.reverseOrder())).findFirst();
                if (one != null && one.isPresent()) {
                    HotelPriceOneDataVo oneData = new HotelPriceOneDataVo();
                    oneData.setSetDate(one.get().getSetDate());
                    oneData.setCreateDate(one.get().getCreateDate());
                    oneData.setPrice(one.get().getPrice());
                    oneData.setManagerId(one.get().getManagerId());
                    newOneDatas.add(oneData);
                }
            }
        }

        /**
         * 获取商家集合中最低房型价格
         */
        List<PriceHotelDataVo> mins = houseService.gethotelMinPrice(StringUtils.join(managerIds, ","));
        DecimalFormat decimalFormat = new DecimalFormat("#####.##");
        //endregion

        for (HotelVo hotel : hotels) {
            HotelListVo hotelData = new HotelListVo();
            hotelData.setId(hotel.getId());
            hotelData.setName(hotel.getName());
            hotelData.setScore(hotel.getScore());
            hotelData.setCoverImg(hotel.getCoverImg());
            hotelData.setComment(hotel.getComment());
            //是否收藏
            Optional<String> hotelId = hotelIds.stream().filter(e -> e.equals(hotel.getId().toString())).findFirst();
            if (hotelId != null && hotelId.isPresent()) {
                hotelData.setIsCollect(1);
            } else {
                hotelData.setIsCollect(0);
            }
            hotelData.setType(hotel.getType());
            //价格
            Optional<HotelPriceOneDataVo> one = newOneDatas.stream().filter(e -> e.getManagerId().equals(hotel.getManagerId())).findFirst();
            Optional<PriceHotelDataVo> min = mins.stream().filter(e -> e.getManagerId().equals(hotel.getManagerId())).findFirst();
            if (one != null && one.isPresent() && min != null && min.isPresent()) {
                if (one.get().getPrice() > min.get().getPrice()) {
                    hotelData.setPrice(decimalFormat.format(min.get().getPrice()));
                } else {
                    hotelData.setPrice(decimalFormat.format(one.get().getPrice()));
                }
            } else {
                if (min != null && min.isPresent()) {
                    hotelData.setPrice(decimalFormat.format(min.get().getPrice()));
                }
            }
            hotelDatas.add(hotelData);
        }
        result.setHotels(hotelDatas);
        //endregion

        List<LikeListVo> likes = articleTweetService.queryArticleLikes(articleTweetDto.getId());

        if (likes != null && likes.size() > 0) {
            Optional<LikeListVo> ownerLikes = likes.stream().filter(e -> e.getId().equals(articleTweetDto.getUserId())).findFirst();
            if (ownerLikes != null && ownerLikes.isPresent()) {
                result.setIsLike(1);
            } else {
                result.setIsLike(0);
            }
        } else {
            result.setIsLike(0);
        }

        result.setLikes(likes == null ? new ArrayList<>() : likes.stream().map(LikeListVo::getImage).limit(10).collect(Collectors.toList()));
        result.setLikeNum(likes == null ? 0 : likes.size());

        List<ArticleCommentVo> comments = articleTweetService.queryArticleComment(articleTweetDto.getId());
        result.setComments(comments);
        int total = articleTweetService.queryArticleCommentTotal(articleTweetDto.getId());
        result.setCommentNum(total);

        result.setCollectNum(data.getCollectNum());

        jsonObject.put("code", ResultStatusCode.OK.getStatus());
        jsonObject.put("message", "请求成功");
        jsonObject.put("data", result);
        ResponseUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());

        return null;
    }

    /**
     * 点赞集合列表
     *
     * @return
     */
    public String queryLikes() {

        JSONObject jsonObject = new JSONObject();

        if (articleTweetDto.getId() == null) {
            jsonObject.put("code", 500);
            jsonObject.put("message", "推文ID不能为空");
            jsonObject.put("data", null);
            ResponseUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
            return null;
        }

        IPage<LikeListVo> result = articleTweetService.queryLikesPage(articleTweetDto.getId(), page, rows);

        jsonObject.put("code", ResultStatusCode.OK.getStatus());
        jsonObject.put("message", "请求成功");
        jsonObject.put("data", result);
        ResponseUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());

        return null;
    }


    /**
     * 获取推文详情中民宿分页列表
     */
    public String queryHotelList() {
        JSONObject jsonObject = new JSONObject();
        if (articleTweetDto.getId() == null || articleTweetDto.getUserId() == null) {
            jsonObject.put("code", 500);
            jsonObject.put("message", "推文ID或用户ID不能为空");
            jsonObject.put("data", null);
            ResponseUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
            return null;
        }

        //查询当前用户
        Users user = userService.queryByUserId(String.valueOf(articleTweetDto.getUserId()));
        if (user == null) {
            jsonObject.put("code", 500);
            jsonObject.put("message", "用户信息已失效，查看详情失败");
            jsonObject.put("data", null);
            ResponseUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
            return null;
        }

        //查询推文数据
        ArticleTweet data = articleTweetService.queryArticleById(String.valueOf(articleTweetDto.getId()), articleTweetDto.getUserId());
        if (data == null) {
            jsonObject.put("code", 500);
            jsonObject.put("message", "推文数据已失效，查看详情失败");
            jsonObject.put("data", null);
            ResponseUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
            return null;
        }

        //region 民宿列表
        //根据乡镇ID获取
        List<String> hotelIds = user.getCollect_hotel() == null ? new ArrayList<>() : Arrays.asList(user.getCollect_hotel().split(","));
        String sql = "id in (" + data.getHotelId() + ")";
        IPage<HotelVo> hotels = articleTweetService.queryHotelPageByHotleId(sql, page, rows);
        List<HotelListVo> hotelDatas = new ArrayList<>();

        //region 最低价
        List<Integer> managerIds = hotels.getPageList().stream().map(HotelVo::getManagerId).collect(Collectors.toList());
        List<HotelPriceDataVo> prices = housePriceService.queryHotelPriceDatas(StringUtils.join(managerIds, ","), TimeExchange.getDateStr());

        List<HotelPriceOneDataVo> oneDatas = new ArrayList<>();
        //获取当天的
        for (HotelPriceDataVo hp : prices) {
            HotelPriceOneDataVo oneData = new HotelPriceOneDataVo();
            oneData.setSetDate(TimeExchange.getDateStr());
            oneData.setCreateDate(hp.getCreateDate());
            oneData.setPrice(hp.getPrice());
            oneData.setManagerId(hp.getManagerId());
            oneDatas.add(oneData);
        }

        /**
         * 根据房型ID处理重复的数据
         */
        List<HotelPriceOneDataVo> newOneDatas = new ArrayList<>();
        if (oneDatas.size() > 0) {
            for (Integer managerId : managerIds) {
                Optional<HotelPriceOneDataVo> one = oneDatas.stream().filter(e -> e.getManagerId().equals(managerId)).sorted(Comparator.comparing(HotelPriceOneDataVo::getCreateDate, Comparator.reverseOrder())).findFirst();
                if (one != null && one.isPresent()) {
                    HotelPriceOneDataVo oneData = new HotelPriceOneDataVo();
                    oneData.setSetDate(one.get().getSetDate());
                    oneData.setCreateDate(one.get().getCreateDate());
                    oneData.setPrice(one.get().getPrice());
                    oneData.setManagerId(one.get().getManagerId());
                    newOneDatas.add(oneData);
                }
            }
        }

        /**
         * 获取商家集合中最低房型价格
         */
        List<PriceHotelDataVo> mins = houseService.gethotelMinPrice(StringUtils.join(managerIds, ","));
        DecimalFormat decimalFormat = new DecimalFormat("#####.##");
        //endregion

        for (HotelVo hotel : hotels.getPageList()) {
            HotelListVo hotelData = new HotelListVo();
            hotelData.setId(hotel.getId());
            hotelData.setName(hotel.getName());
            hotelData.setScore(hotel.getScore());
            hotelData.setCoverImg(hotel.getCoverImg());
            hotelData.setComment(hotel.getComment());
            //是否收藏
            Optional<String> hotelId = hotelIds.stream().filter(e -> e.equals(hotel.getId().toString())).findFirst();
            if (hotelId != null && hotelId.isPresent()) {
                hotelData.setIsCollect(1);
            } else {
                hotelData.setIsCollect(0);
            }
            hotelData.setType(hotel.getType());
            //价格
            Optional<HotelPriceOneDataVo> one = newOneDatas.stream().filter(e -> e.getManagerId().equals(hotel.getManagerId())).findFirst();
            Optional<PriceHotelDataVo> min = mins.stream().filter(e -> e.getManagerId().equals(hotel.getManagerId())).findFirst();
            if (one != null && one.isPresent() && min != null && min.isPresent()) {
                if (one.get().getPrice() > min.get().getPrice()) {
                    hotelData.setPrice(decimalFormat.format(min.get().getPrice()));
                } else {
                    hotelData.setPrice(decimalFormat.format(one.get().getPrice()));
                }
            } else {
                if (min != null && min.isPresent()) {
                    hotelData.setPrice(decimalFormat.format(min.get().getPrice()));
                }
            }
            hotelDatas.add(hotelData);
        }
        //endregion

        IPage<HotelListVo> result = new IPage<>();
        result.setPage(hotels.getPage());
        result.setRows(hotels.getRows());
        result.setPageList(hotelDatas);
        result.setTotal(hotels.getTotal());
        result.setTotalPage(hotels.getTotalPage());

        jsonObject.put("code", ResultStatusCode.OK.getStatus());
        jsonObject.put("message", "请求成功");
        jsonObject.put("data", result);
        ResponseUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());

        return null;
    }


    /**
     * 获取推文详情中评论分页列表
     * 先获取一级评论 再区获取对应子级
     */
    public String queryCommentList() {
        JSONObject jsonObject = new JSONObject();
        //推文ID判断
        if (articleTweetDto.getId() == null) {
            jsonObject.put("code", 500);
            jsonObject.put("message", "推文ID不能为空");
            jsonObject.put("data", null);
            ResponseUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
            return null;
        }

        //一级分页数据
        IPage<ArticleCommentVo> result = articleTweetService.queryCommentPageByArticle(articleTweetDto.getId(), page, rows);

        //子级评论数据
        List<ArticleCommentVo> childs = articleTweetService.queryCommentsByArticle(articleTweetDto.getId());

        if (childs != null && childs.size() > 0) {
            for (ArticleCommentVo data : result.getPageList()) {
                List<ArticleCommentVo> comments = QueryTreeDatas(data.getId(), data.getUserName(), childs);
                data.setChildrens(comments);
            }
        }

        jsonObject.put("code", ResultStatusCode.OK.getStatus());
        jsonObject.put("message", "请求成功");
        jsonObject.put("data", result);
        ResponseUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());

        return null;
    }

    //region 循环递归获取子级

    /**
     * 根据父类ID获取树形菜单数据
     *
     * @param parentID 父级ID
     * @param lists    数据集合
     * @return
     */
    private List<ArticleCommentVo> QueryTreeDatas(Integer parentID, String parentName, List<ArticleCommentVo> lists) {
        List<ArticleCommentVo> newTrees = new ArrayList<>();

        List<ArticleCommentVo> datas = lists.stream().filter(e -> e.getParentId().equals(parentID)).collect(Collectors.toList());

        for (ArticleCommentVo data : datas) {
            data.setParentName(parentName);
            List<ArticleCommentVo> news = QueryTreeDatas(data.getId(), data.getUserName(), lists);
            if (news == null || news.size() == 0) {
                newTrees.add(data);
                continue;
            } else {
                data.setChildrens(news);
                newTrees.add(data);
            }
        }

        return newTrees;
    }
    //endregion


    /**
     * 根据用户ID获取个人主页相关信息
     */
    public String queryUserInfo() {
        JSONObject jsonObject = new JSONObject();
        //用户ID判断
        if (articleTweetDto.getUserId() == null) {
            jsonObject.put("code", 500);
            jsonObject.put("message", "用户ID不能为空");
            jsonObject.put("data", null);
            ResponseUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
            return null;
        }

        articleUserVo result = articleTweetService.queryUserInfo(articleTweetDto.getUserId());

        //region 关注
        if (articleTweetDto.getUserId().equals(result.getId())) {
            result.setIsFollow(2);//自己的推文
        } else {
            //是否关注
            UserCollect uc = articleTweetService.queryUserCollect(result.getId(), articleTweetDto.getUserId());
            result.setIsFollow(uc == null ? 0 : 1);//已关注给0；未关注给1
        }
        //endregion

        if (result != null) {
            String descript = "点击这里，填写简介";
            result.setDescript(result.getDescript() == null ? descript : result.getDescript());
        }

        jsonObject.put("code", ResultStatusCode.OK.getStatus());
        jsonObject.put("message", "请求成功");
        jsonObject.put("data", result);
        ResponseUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
        return null;
    }

    /**
     * 根据用户ID获取用户主页推文列表分页数据
     */
    public String queryOwnerArticlePage() {
        JSONObject jsonObject = new JSONObject();
        //用户ID判断
        if (articleTweetDto.getUserId() == null || articleTweetDto.getType() == null) {
            jsonObject.put("code", 500);
            jsonObject.put("message", "用户ID或类型ID不能为空");
            jsonObject.put("data", null);
            ResponseUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
            return null;
        }

        String sqlWhere = "";//全部推文
        if (articleTweetDto.getType().intValue() == 1) {
            sqlWhere = "and at.approve = 1 ";//审核中
        } else if (articleTweetDto.getType().intValue() == 2) {
            sqlWhere = "and at.approve = 3 ";//驳回
        }
        IPage<OwnerArticleVo> result = articleTweetService.queryOwnerArticlePage(articleTweetDto.getUserId(), sqlWhere, page, rows);

        if (result.getPageList().size() > 0) {
            String articleIds = StringUtils.join(result.getPageList().stream().map(OwnerArticleVo::getId).collect(Collectors.toList()), ",");
            List<FileInfo> fileInfos = articleTweetService.queryList("and link_id in (" + articleIds + ")");

            for (OwnerArticleVo data : result.getPageList()) {
                List<FileInfo> fileInfoList = fileInfos == null ? null : fileInfos.stream().filter(e -> e.getLinkId().equals(data.getId().toString())).collect(Collectors.toList());
                if (fileInfoList != null) {
                    if (fileInfoList.size() > 1) {
                        data.setImages(fileInfoList.stream().map(FileInfo::getUrl).collect(Collectors.toList()));
                    } else if (fileInfoList.size() == 1) {
                        String url = fileInfoList.get(0).getUrl();
                        if (!url.endsWith("jpg") && !url.endsWith("png")) {
                            data.setVideo(fileInfoList.get(0).getUrl());
                        } else {
                            List<String> images = new ArrayList<>();
                            images.add(url);
                            data.setImages(images);
                        }
                    }
                }
            }
        }

        jsonObject.put("code", ResultStatusCode.OK.getStatus());
        jsonObject.put("message", "请求成功");
        jsonObject.put("data", result);
        ResponseUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());

        return null;
    }

    public void getUserContactList() {
        StringBuilder querySql = new StringBuilder("");
        if (!Func.checkNull(articleTweetDto.getUserName())) {
            querySql.append(" and user_name like '%").append(articleTweetDto.getUserName()).append("%' ");
        }
        querySql.append(" and data_type = '").append(DataType.关联数据.toString()).append("' ");
        IPage listPage = userService.queryUserPage(querySql.toString(), page, rows); // 查询分页
        ResponseUtil.writeJsonIPage(ServletActionContext.getResponse(), listPage);
    }

    /**
     * 社区首页推文列表
     */
    public String queryArticlePage() {
        JSONObject jsonObject = new JSONObject();

        if (articleTweetDto.getType() == null) {
            jsonObject.put("code", 500);
            jsonObject.put("message", "推文列表类型不能为空");
            jsonObject.put("data", null);
            ResponseUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
            return null;
        }

        if (articleTweetDto.getUserId() == null) {
            jsonObject.put("code", 500);
            jsonObject.put("message", "用户ID不能为空");
            jsonObject.put("data", null);
            ResponseUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
            return null;
        }

        IPage<ArticleListVo> result = articleTweetService.queryArticlesPage(articleTweetDto.getKeyWord(), articleTweetDto.getTownId().equals("") ? null : articleTweetDto.getTownId(), articleTweetDto.getUserId(), articleTweetDto.getType(), page, rows);
        if (result.getPageList().size() > 0) {
            String articleIds = StringUtils.join(result.getPageList().stream().map(ArticleListVo::getId).collect(Collectors.toList()), ",");
            List<FileInfo> fileInfos = articleTweetService.queryList("and link_id in (" + articleIds + ")");

            for (ArticleListVo data : result.getPageList()) {
                if (fileInfos != null) {
                    List<FileInfo> fileInfoList = fileInfos.stream().filter(e -> e.getLinkId().equals(data.getId().toString())).collect(Collectors.toList());
                    if (fileInfoList != null) {
                        if (fileInfoList.size() > 1) {
                            data.setImage(fileInfoList.get(0).getUrl());
                        } else if (fileInfoList.size() == 1) {
                            String url = fileInfoList.get(0).getUrl();
                            if (!url.endsWith("jpg") && !url.endsWith("png")) {
                                data.setVideo(fileInfoList.get(0).getUrl());
                            } else {
                                data.setImage(url);
                            }
                        }
                    }
                }
            }
        }

        jsonObject.put("code", ResultStatusCode.OK.getStatus());
        jsonObject.put("message", "请求成功");
        jsonObject.put("data", result);
        ResponseUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());

        return null;
    }


    /**
     * 点赞数最高的推文
     */
    public String queryMaxArticleLike() {
        JSONObject jsonObject = new JSONObject();
        ArticleLikeMaxVo result = articleTweetService.queryMaxArticleLike();
        if (result != null) {
            List<FileInfo> fileInfos = articleTweetService.queryList("and link_id = " + result.getId() + "");
            if (fileInfos != null) {
                if (fileInfos.size() > 1) {
                    result.setImage(fileInfos.get(0).getUrl());
                } else if (fileInfos.size() == 1) {
                    String url = fileInfos.get(0).getUrl();
                    if (!url.endsWith("jpg") && !url.endsWith("png")) {
                        result.setVideo(fileInfos.get(0).getUrl());
                    } else {
                        result.setImage(url);
                    }
                }
            }
        }

        jsonObject.put("code", ResultStatusCode.OK.getStatus());
        jsonObject.put("message", "请求成功");
        jsonObject.put("data", result);
        ResponseUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
        return null;
    }


    /**
     * 相关推文
     */
    public String relatedTweets() {
        JSONObject jsonObject = new JSONObject();

        if (articleTweetDto.getId() == null || articleTweetDto.getTownId() == null || articleTweetDto.getUserId() == null) {
            jsonObject.put("code", 500);
            jsonObject.put("message", "乡镇ID或推文ID或用户ID不能为空");
            jsonObject.put("data", null);
            ResponseUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
            return null;
        }

        IPage<ArticleListVo> result = articleTweetService.relatedTweetPage(articleTweetDto.getUserId(), articleTweetDto.getTownId(), articleTweetDto.getId(), page, rows);
        if (result.getPageList().size() > 0) {
            String articleIds = StringUtils.join(result.getPageList().stream().map(ArticleListVo::getId).collect(Collectors.toList()), ",");
            List<FileInfo> fileInfos = articleTweetService.queryList("and link_id in (" + articleIds + ")");

            for (ArticleListVo data : result.getPageList()) {
                List<FileInfo> fileInfoList = fileInfos.stream().filter(e -> e.getLinkId().equals(data.getId().toString())).collect(Collectors.toList());
                if (fileInfoList != null) {
                    if (fileInfoList.size() > 1) {
                        data.setImage(fileInfoList.get(0).getUrl());
                    } else if (fileInfoList.size() == 1) {
                        String url = fileInfoList.get(0).getUrl();
                        if (!url.endsWith("jpg") && !url.endsWith("png")) {
                            data.setVideo(fileInfoList.get(0).getUrl());
                        } else {
                            data.setImage(url);
                        }
                    }
                }
            }
        }

        jsonObject.put("code", ResultStatusCode.OK.getStatus());
        jsonObject.put("message", "请求成功");
        jsonObject.put("data", result);
        ResponseUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());

        return null;
    }
    //select * from article_tweet where location_id = '' and user_id != 1 and approve = 2


    /**
     * 收藏文章
     */
    public String collectArticle() throws ParseException {
        JSONObject jsonObject = new JSONObject();

        if (articleTweetDto.getId() == null || articleTweetDto.getUserId() == null) {
            jsonObject.put("code", 500);
            jsonObject.put("message", "用户ID或推文ID不能为空");
            jsonObject.put("data", null);
            ResponseUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
            return null;
        }

        //查询当前操作人是否已经收藏过这篇文章
        ArticleCollect data = articleTweetService.queryArticleCollect(articleTweetDto.getId(), articleTweetDto.getUserId());

        String actionStr = "收藏";
        if (data != null) {
            if (data.getIsLose().intValue() == 0) {//说明原来是未失效，现在要取消
                actionStr = "取消收藏";
                data.setIsLose(1);
            } else {
                data.setIsLose(0);
            }
        } else {
            Date now = DateUtil.formateDate(DateUtil.getCurrentDate(), DateUtil.Time_Formatter_Second);
            data = new ArticleCollect();
            data.setArticleId(articleTweetDto.getId());
            data.setUserId(articleTweetDto.getUserId());
            data.setIsLose(0);
            data.setCreateId(articleTweetDto.getUserId());
            data.setCreateDate(now);
            data.setStatus(1);
        }

        int m = articleTweetService.updateArticleCollect(data);
        if (m <= 0) {
            String message = actionStr + "失败";
            ResUtil.writeJson(ServletActionContext.getResponse(), new JSONObject() {{
                put("message", message);
                put("code", 500);
            }}.toString());

            return null;
        }

        String successMessage = actionStr + "成功";
        ResUtil.writeJson(ServletActionContext.getResponse(), new JSONObject() {{
            put("message", successMessage);
            put("code", 200);
        }}.toString());

        return null;
    }


    /**
     * 评论文章
     */
    public String commentArticle() throws ParseException {
        Gson gson = new Gson();
        JSONObject jsonObject = new JSONObject();
        com.alibaba.fastjson.JSONObject json = GetHttpParam.getHttpParam(request);
        ArticleCommentDto articleCommentDto = gson.fromJson(json.toString(), new TypeToken<ArticleCommentDto>() {
        }.getType());

        if (articleCommentDto.getArticleId() == null || Func.checkNull(articleCommentDto.getContent())
                || articleCommentDto.getParentId() == null || articleCommentDto.getUserId() == null) {
            jsonObject.put("code", 500);
            jsonObject.put("message", "参数不能为空");
            jsonObject.put("data", null);
            ResponseUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
            return null;
        }

        //查询操作人身份
        Users user = userService.queryByUserId(String.valueOf(articleCommentDto.getUserId()));
        if (user == null) {
            jsonObject.put("code", 500);
            jsonObject.put("message", "用户信息已失效，评论失败");
            jsonObject.put("data", null);
            ResponseUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
            return null;
        }

        Date now = DateUtil.formateDate(DateUtil.getCurrentDate(), DateUtil.Time_Formatter_Second);
        ArticleComment articleComment = new ArticleComment();
        articleComment.setArticleId(articleCommentDto.getArticleId());
        articleComment.setCommentParentId(articleCommentDto.getParentId());
        articleComment.setCommentId(articleCommentDto.getUserId());
        articleComment.setCommentName(user.getUser_name());
        articleComment.setCommentImage(user.getHeadPhoto() == null ? ConstDefault.DefaultHeadPhoto : user.getHeadPhoto());
        articleComment.setContent(articleCommentDto.getContent());
        articleComment.setCreateId(articleCommentDto.getUserId());
        articleComment.setCreateDate(now);
        articleComment.setStatus(1);

        int num = articleTweetService.insertArticleComment(articleComment);
        if (num <= 0) {
            ResUtil.writeJson(ServletActionContext.getResponse(), new JSONObject() {{
                put("message", "评论失败");
                put("code", 500);
            }}.toString());
            return null;
        }

        ResUtil.writeJson(ServletActionContext.getResponse(), new JSONObject() {{
            put("message", "评论成功");
            put("code", 200);
        }}.toString());

        return null;
    }


    /**
     * 关注作者
     */
    public String followAuthor() throws ParseException {
        JSONObject jsonObject = new JSONObject();
        if (articleTweetDto.getAuthorId() == null || articleTweetDto.getUserId() == null) {
            jsonObject.put("code", 500);
            jsonObject.put("message", "作者ID或用户ID不能为空");
            jsonObject.put("data", null);
            ResponseUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
            return null;
        }

        //查询当前操作人是否已经关注过作者
        UserCollect data = articleTweetService.queryUserCollectNoLose(articleTweetDto.getAuthorId(), articleTweetDto.getUserId());
        String actionStr = "关注";
        if (data != null) {
            if (data.getIsLose().intValue() == 0) {//说明原来是未失效，现在要取消
                actionStr = "取消关注";
                data.setIsLose(1);
            } else {
                data.setIsLose(0);
            }
        } else {
            Date now = DateUtil.formateDate(DateUtil.getCurrentDate(), DateUtil.Time_Formatter_Second);
            data = new UserCollect();
            data.setParentUserid(articleTweetDto.getAuthorId());
            data.setUserId(articleTweetDto.getUserId());
            data.setIsLose(0);
            data.setCreateId(articleTweetDto.getUserId());
            data.setCreateDate(now);
            data.setStatus(1);
        }

        int m = articleTweetService.updateUserCollect(data);
        if (m <= 0) {
            String message = actionStr + "失败";
            ResUtil.writeJson(ServletActionContext.getResponse(), new JSONObject() {{
                put("message", message);
                put("code", 500);
            }}.toString());

            return null;
        }

        String successMessage = actionStr + "成功";
        ResUtil.writeJson(ServletActionContext.getResponse(), new JSONObject() {{
            put("message", successMessage);
            put("code", 200);
        }}.toString());

        return null;
    }

    /**
     * 点赞文章
     */
    public String likeArticle() throws ParseException {
        JSONObject jsonObject = new JSONObject();

        if (articleTweetDto.getId() == null || articleTweetDto.getUserId() == null) {
            jsonObject.put("code", 500);
            jsonObject.put("message", "用户ID或推文ID不能为空");
            jsonObject.put("data", null);
            ResponseUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
            return null;
        }

        //查询操作人身份
        Users user = userService.queryByUserId(String.valueOf(articleTweetDto.getUserId()));
        if (user == null) {
            jsonObject.put("code", 500);
            jsonObject.put("message", "用户信息已失效，评论失败");
            jsonObject.put("data", null);
            ResponseUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
            return null;
        }

        //查询当前操作人是否已经收藏过这篇文章
        ArticleLikes data = articleTweetService.queryArticleLike(articleTweetDto.getId(), articleTweetDto.getUserId());

        String actionStr = "点赞";
        if (data != null) {
            if (data.getIsLose().intValue() == 0) {//说明原来是未失效，现在要取消
                actionStr = "取消点赞";
                data.setIsLose(1);
            } else {
                data.setIsLose(0);
            }
        } else {
            Date now = DateUtil.formateDate(DateUtil.getCurrentDate(), DateUtil.Time_Formatter_Second);
            data = new ArticleLikes();
            data.setArticleId(articleTweetDto.getId());
            data.setLikeId(articleTweetDto.getUserId());
            data.setLikeName(user.getUser_name());
            data.setLikeImage(user.getHeadPhoto() == null ? ConstDefault.DefaultHeadPhoto : user.getHeadPhoto());
            data.setIsLose(0);
            data.setCreateId(articleTweetDto.getUserId());
            data.setCreateDate(now);
            data.setStatus(1);
        }

        int m = articleTweetService.updateArticleLike(data);
        if (m <= 0) {
            String message = actionStr + "失败";
            ResUtil.writeJson(ServletActionContext.getResponse(), new JSONObject() {{
                put("message", message);
                put("code", 500);
            }}.toString());

            return null;
        }

        String successMessage = actionStr + "成功";
        ResUtil.writeJson(ServletActionContext.getResponse(), new JSONObject() {{
            put("message", successMessage);
            put("code", 200);
        }}.toString());

        return null;
    }

    /**
     * 获取乡镇列表
     */
    public String townShips() {
        List<HotelDict> hotelDicts = hotelDictService.queryList("and code = 10");
        List<TownshipVo> result = new ArrayList<>();
        for (HotelDict hotelDict : hotelDicts) {
            TownshipVo data = new TownshipVo();
            data.setId(hotelDict.getId());
            data.setName(hotelDict.getName());
            result.add(data);
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", ResultStatusCode.OK.getStatus());
        jsonObject.put("message", "请求成功");
        jsonObject.put("data", result);
        ResponseUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());

        return null;
    }


    /**
     * 根据乡镇ID获取民宿列表
     */
    public String hotelByid() {
        JSONObject jsonObject = new JSONObject();
        if (Func.checkNull(articleTweetDto.getTownId())) {
            jsonObject.put("code", ResultStatusCode.BAD_REQUEST.getStatus());
            jsonObject.put("message", ResultStatusCode.BAD_REQUEST.getMsg());
            jsonObject.put("data", null);
            ResponseUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
            return null;
        }

        String sql = "hotel_township = '" + articleTweetDto.getTownId() + "'";

        IPage<HotelVo> houseIPage = articleTweetService.queryHotelPage(sql, page, rows);

        jsonObject.put("message", "查询分页成功");
        jsonObject.put("code", 200);
        jsonObject.put("data", houseIPage);
        ResUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
        return null;
    }

    /**
     * 修改用户简介
     */
    public String updateDescript() {
        JSONObject jsonObject = new JSONObject();

        if (articleTweetDto.getAuthorId() == null || articleTweetDto.getUserId() == null || Func.checkNull(articleTweetDto.getDescript())) {
            jsonObject.put("code", 500);
            jsonObject.put("message", "操作用户ID或主页用户ID或简介不能为空");
            jsonObject.put("data", null);
            ResponseUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
            return null;
        }

        if (!articleTweetDto.getAuthorId().equals(articleTweetDto.getUserId())) {
            jsonObject.put("code", 500);
            jsonObject.put("message", "当前用户无法修改其他人的简介信息");
            jsonObject.put("data", null);
            ResponseUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
            return null;
        }

        int num = articleTweetService.updateDescript(articleTweetDto.getAuthorId(), articleTweetDto.getDescript());

        jsonObject.put("message", "修改成功");
        jsonObject.put("code", 200);
        ResUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
        return null;
    }

    /**
     * 攻略分页
     *
     * @return
     */
    public String walkthroughPage() {
        JSONObject jsonObject = new JSONObject();

        StringBuilder strSql = new StringBuilder(" and at.status=1 "); // 推文没删除才显示
        if (!Func.checkNull(key)) {
            strSql.append(" and (at.user_name like '%").append(key).append("%' or at.title like '%").append(key).append("%') ");
        }
        if (!Func.checkNull(startTime) && !Func.checkNull(endTime)) {
            strSql.append(" and at.create_date >= '").append(startTime).append("' ");
            strSql.append(" and at.create_date <= '").append(endTime).append("' ");
        }

        IPage<WalkthroughVo> walkthroughPage = articleTweetService.walkthroughPage(strSql.toString(), page, rows);

        jsonObject.put("message", "查询分页成功");
        jsonObject.put("code", 200);
        jsonObject.put("data", walkthroughPage);
        ResUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
        return null;
    }

    /**
     * 商品页面
     */
    public String productPage() throws Exception {

        JSONObject jsonObject = new JSONObject();
//        JSONObject jsonBody = new JSONObject();
//        jsonBody.put("username", "admin");
//        jsonBody.put("password", "123456");
//
//        String url = "https://www.jinganrenjiams.com/cloud-mall/admin/open/login";
//
        // 构建http请求客户端
//        HttpClient httpclient = HttpClientBuilder.create().useSystemProperties().build();
//        // 构建post请求
//        HttpPost postMethod = new HttpPost(url);
//        // 设置请求头
//        postMethod.addHeader("Content-Type", "application/json");
//        // 设置请求体
//        postMethod.setEntity(new StringEntity(jsonBody.toString()));
//
//        // 发送请求
//        HttpResponse response = httpclient.execute(postMethod);
//
//        String s = EntityUtils.toString(response.getEntity());
//
//        JSONObject postJson = JSONObject.parseObject(s);
//
//        JSONObject data = postJson.getJSONObject("data");
//
//        String token = data.getString("token");

        // 构建http请求客户端
        HttpClient httpclient = HttpClientBuilder.create().useSystemProperties().build();
        String getUrl = "";

        if (!Func.checkNull(key)) {
                getUrl = "https://www.jinganrenjiams.com/cloud-mall/goods/open/page?state=1&curPage="+page+"&pageSize="+rows+"&goodsName=" + key;
        } else {
            getUrl = "https://www.jinganrenjiams.com/cloud-mall/goods/open/page?state=1&curPage="+page+"&pageSize="+rows;
        }

        HttpGet httpGet = new HttpGet(getUrl);
        // 设置请求头
        httpGet.addHeader("Content-Type", "application/json");
//        httpGet.addHeader("Mall-Token", token);
        // 发送请求
        HttpResponse execute = httpclient.execute(httpGet);
        String s1 = EntityUtils.toString(execute.getEntity());
        JSONObject getJson = JSONObject.parseObject(s1);
        JSONObject data1 = getJson.getJSONObject("data");


        jsonObject.put("message", "查询分页成功");
        jsonObject.put("code", 200);
        jsonObject.put("data", data1);
        ResUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());

        return null;
    }

    /**
     * 点赞数前三的推文
     */
    public String queryTop3ArticleLike() {
        JSONObject jsonObject = new JSONObject();
        List<ArticleLikeMaxVo> result = articleTweetService.queryTop3ArticleLike();
        if (result != null) {
            for (int i = 0; i < result.size(); i++) {
                List<FileInfo> fileInfos = articleTweetService.queryList("and link_id = " + result.get(i).getId() + "");
                if (fileInfos != null) {
                    if (fileInfos.size() > 1) {
                        result.get(i).setImage(fileInfos.get(0).getUrl());
                    } else if (fileInfos.size() == 1) {
                        String url = fileInfos.get(0).getUrl();
                        if (!url.endsWith("jpg") && !url.endsWith("png")) {
                            result.get(i).setVideo(fileInfos.get(0).getUrl());
                        } else {
                            result.get(i).setImage(url);
                        }
                    }
                }
            }
        }
        jsonObject.put("code", ResultStatusCode.OK.getStatus());
        jsonObject.put("message", "请求成功");
        jsonObject.put("data", result);
        ResponseUtil.writeJson(ServletActionContext.getResponse(), jsonObject.toString());
        return null;
    }

}
