package com.cweb.controller;

import com.alibaba.fastjson.JSONObject;
import com.hai.common.exception.ErrorCode;
import com.hai.common.exception.ErrorHelp;
import com.hai.common.exception.SysCode;
import com.hai.common.security.SessionObject;
import com.hai.common.security.UserCenter;
import com.hai.common.utils.DateUtil;
import com.hai.common.utils.RedisUtil;
import com.hai.common.utils.ResponseMsgUtil;
import com.hai.config.CmsContentConfig;
import com.hai.entity.*;
import com.hai.model.CmsContentModel;
import com.hai.model.HighUserModel;
import com.hai.model.ResponseData;
import com.hai.model.UserInfoModel;
import com.hai.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

@Controller
@Api(value = "内容管理 内容发布")
@RequestMapping(value = "/cmsContent")
public class    CmsContentController {

    private static Logger log = LoggerFactory.getLogger(CmsContentController.class);

    @Resource
    private CmsContentService cmsContentService;

    @Resource
    private CmsCategoryService cmsCategoryService;

    @Resource
    private CmsContentConfig cmsContentConfig;

    @Resource
    private BsMsgService bsMsgService;

    @Autowired
    private UserCenter userCenter;

    @RequestMapping(value = "/getCmsContent", method = RequestMethod.GET)
    @ApiOperation(value = "查询cms内容")
    @ResponseBody
    public ResponseData getCmsContent(@RequestParam(name = "companyId", required = true) Long companyId,
                                      @RequestParam(name = "platform", required = true) Integer platform,
                                      @RequestParam(name = "categoryCode", required = true) String categoryCode, HttpServletRequest request) {
        try {

            Boolean dataWhetherNull = true;

            List<CmsContent> cmsContent;

            SessionObject sessionObject = userCenter.getSessionObjectByCms(request);
            HighUserModel userInfoModel = new HighUserModel();

            System.out.println("sessionObject============" + sessionObject);

            if (sessionObject != null) {
                // 用户
                userInfoModel = (HighUserModel) sessionObject.getObject();
            }

            CmsCategory category = cmsCategoryService.getCategoryByCode(categoryCode);

            if (category == null) {
                log.error("CmsContentController --> getCmsContent() error!");
                throw ErrorHelp.genException(SysCode.System , ErrorCode.COMMON_ERROR , "未找到当前信息");
            }

            if (category.getParentId() == null) {
                List<CmsCategory> categoryList = cmsCategoryService.getCategoryByParentId(category.getId());

                List<JSONObject> objectList = new ArrayList<>();

                for (CmsCategory cmsCategory : categoryList) {
                    JSONObject object = new JSONObject();
                    //  1.小图一行四个 2.轮播图 3.消息通知 4.大图展示 5.一横图三小图 6.数据库数据 7.小图一行五个
                    if (cmsCategory.getType() == 1 || cmsCategory.getType() == 2 || cmsCategory.getType() == 4 || cmsCategory.getType() == 5|| cmsCategory.getType() == 7 || cmsCategory.getType() == 8 ) {
                        object.put("type" , cmsCategory.getType());
                        object.put("name" , cmsCategory.getName());
                        object.put("sort" , cmsCategory.getSort());
                        object.put("code" , cmsCategory.getCode());
                        cmsContent = cmsContentService.getListCmsContentByCategoryId(cmsCategory.getId() , companyId , platform);
                        if (cmsContent.size() > 0) {
                            dataWhetherNull = false;
                        }
                        object.put("childCategory" , cmsContent);
                    } else if(cmsCategory.getType() == 6 || cmsCategory.getType() == 9) {
                        object.put("type" , cmsCategory.getType());
                        object.put("name" , cmsCategory.getName());
                        object.put("sort" , cmsCategory.getSort());
                        object.put("code" , cmsCategory.getCode());
                        cmsContent = cmsContentService.getListCmsContentByCategoryId(cmsCategory.getId() , companyId , platform);
                        if (cmsContent.size() > 0) {
                            dataWhetherNull = false;
                            object.put("jumpType" , cmsContent.get(0).getJumpType());
                            object.put("jumpUrl" , cmsContent.get(0).getJumpUrl());
                            object.put("detailJumpUrl" , cmsContent.get(0).getExt1());
                        }
                        object.put("childDate" , cmsContentConfig.getCmsContentData(cmsCategory.getName(), companyId));
                    } else if(cmsCategory.getType() == 3) {
                        object.put("type" , cmsCategory.getType());
                        object.put("name" , cmsCategory.getName());
                        object.put("sort" , cmsCategory.getSort());
                        object.put("code" , cmsCategory.getCode());
                        cmsContent = cmsContentService.getListCmsContentByCategoryId(cmsCategory.getId() , companyId , platform);
                        if (cmsContent.size() > 0) {
                            dataWhetherNull = false;
                            object.put("jumpType" , cmsContent.get(0).getJumpType());
                            object.put("jumpUrl" , cmsContent.get(0).getJumpUrl());
                        }
                        List<BsMsg> list;
                        List<BsMsg> listUser = new ArrayList<>();
                        if (sessionObject != null) {
                            Map<String, Object> mapUser = new HashMap<>();

                            mapUser.put("whereCheck" , false);
                            mapUser.put("msgType" , 1);
                            mapUser.put("userId" , userInfoModel.getHighUser().getId());
                            listUser = bsMsgService.queryMsgByList(mapUser);

                        }

                        Map<String, Object> map = new HashMap<>();

                        map.put("companyId" , companyId);
                        map.put("msgType" , 2);
                        list = bsMsgService.queryMsgByList(map);

                        list.addAll(listUser);

                        list = list.stream().sorted(Comparator.comparing(BsMsg::getCreateTime).reversed())
                                .collect(Collectors.toList());
                        for (BsMsg bsMsg : list) {
                            bsMsg.setTimeData( DateUtil.timeDifference(bsMsg.getCreateTime(), new Date() ));
                        }
                        object.put("childDate" , list);
                    }

                    if (cmsCategory.getType() == 3 || cmsCategory.getType() == 6 || cmsCategory.getType() == 9) {
                        if (object.getJSONArray("childDate") != null && object.getJSONArray("childDate").size() >0 ) {
                            objectList.add(object);
                        }
                    } else {
                        if (object.getJSONArray("childCategory").size() >0 ) {
                            objectList.add(object);
                        }
                    }
                }

                return ResponseMsgUtil.success(dataWhetherNull ? null:objectList);
            } else {
                JSONObject object = new JSONObject();
                object.put("type" , category.getType());
                object.put("name" , category.getName());
                object.put("sort" , category.getSort());
                object.put("code" , category.getCode());
                object.put("childCategory" , cmsContentService.getListCmsContentByCategoryId(category.getId() , companyId , platform));
                return ResponseMsgUtil.success(object);
            }


        } catch (Exception e) {
            log.error("CmsContentController --> getCorporateAdvertising() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }
}
