package com.bweb.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
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.ResponseMsgUtil;
import com.bweb.config.SysConfig;
import com.hai.entity.CmsContent;
import com.hai.entity.CmsPatch;
import com.hai.model.CmsContentModel;
import com.hai.model.ResponseData;
import com.hai.model.UserInfoModel;
import com.hai.service.CmsContentService;
import com.hai.service.CmsPatchService;
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.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

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

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

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

    @Resource
    private SysConfig sysConfig;

    @Resource
    private UserCenter userCenter;

    @Resource
    private CmsContentService cmsContentService;
    @Resource
    private CmsPatchService cmsPatchService;

    @RequestMapping(value = "/addContent", method = RequestMethod.POST)
    @ApiOperation(value = "创建内容")
    @ResponseBody
    public ResponseData addContent(@RequestBody JSONObject jsonObject, HttpServletRequest request) {
        try {
            CmsContent cmsContent = jsonObject.getObject("cmsContent", CmsContent.class);
            Long moduleId = jsonObject.getLong("moduleId");
            JSONArray jsonArray = jsonObject.getJSONArray("patches");
            List<CmsPatch> patchList = new ArrayList<>();
            if (jsonArray != null) {
                patchList = JSONObject.parseArray(jsonArray.toJSONString(), CmsPatch.class);
            }

            if (cmsContent == null
                    || StringUtils.isBlank(cmsContent.getTitle())
                    || cmsContent.getCategoryId() == null
                    || cmsContent.getStatus() == null
                    || (cmsContent.getStatus() != 1 && cmsContent.getStatus() != 2)
            ) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            // 获取操作者
            SessionObject sessionObject = userCenter.getSessionObject(request);
            if(sessionObject == null){
                throw ErrorHelp.genException(SysCode.System, ErrorCode.SEC_USER_EXPIRED, "");
            }
            UserInfoModel userInfoModel = (UserInfoModel) sessionObject.getObject();

            Map<String, String> paramsMap = new HashMap<>();
            if (moduleId != null) {
                paramsMap.put("moduleId", moduleId.toString());
            }

            cmsContent.setCreateTime(new Date());
            cmsContent.setVisitCount(0);
            cmsContent.setUpdateTime(cmsContent.getCreateTime());
            cmsContent.setCompanyId(userInfoModel.getBsCompany().getId());
            cmsContent.setOpId(userInfoModel.getSecUser().getId());
            if (cmsContentService.addContent(cmsContent, patchList, paramsMap,sysConfig.getFileUrl()) > 0) {
                return ResponseMsgUtil.success("添加成功");
            } else {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.ADD_DATA_ERROR, "");
            }
        } catch (Exception e) {
            log.error("CmsContentController --> addContent() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/updateContent", method = RequestMethod.POST)
    @ApiOperation(value = "修改内容")
    @ResponseBody
    public ResponseData updateContent(@RequestBody CmsContent cmsContent) {
        try {
            if (cmsContent == null
                    || cmsContent.getId() == null
                    || StringUtils.isBlank(cmsContent.getTitle())
                    || cmsContent.getCategoryId() == null
            ) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            CmsContent content = cmsContentService.getContentById(cmsContent.getId());
            if (content == null || content.getStatus() == 0) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.CMS_CONTENT_NOT_FOUND, "");
            } else if (content.getStatus() != 1 && content.getStatus() != 3) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.STATUS_ERROR, "");
            }

            cmsContent.setCreateTime(content.getCreateTime());
            cmsContent.setStatus(content.getStatus());
            cmsContent.setVisitCount(content.getVisitCount());
            cmsContent.setJumpUrl(content.getJumpUrl());
            cmsContent.setUpdateTime(new Date());
            cmsContent.setCompanyId(content.getCompanyId());
            cmsContent.setOpId(content.getOpId());
            if (cmsContentService.updateContent(cmsContent, "updateContent", null,sysConfig.getFileUrl()) > 0) {
                return ResponseMsgUtil.success("修改成功");
            } else {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.UPDATE_DATA_ERROR, "");
            }
        } catch (Exception e) {
            log.error("CmsContentController --> updateContent() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/delContent", method = RequestMethod.GET)
    @ApiOperation(value = "删除 内容")
    @ResponseBody
    public ResponseData delContent(@RequestParam(value = "id", required = true) Long id) {
        try {
            if (cmsContentService.delContent(id,sysConfig.getFileUrl()) > 0) {
                return ResponseMsgUtil.success("删除成功");
            } else {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.DELETE_DATA_ERROR, "");
            }
        } catch (Exception e) {
            log.error("CmsContentController --> delContent() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/getContentById", method = RequestMethod.GET)
    @ApiOperation(value = "根据id 查询内容基础信息")
    @ResponseBody
    public ResponseData getContentById(@RequestParam(value = "id", required = true) Long id) {
        try {
            return ResponseMsgUtil.success(cmsContentService.getContentDetail(id, null));
        } catch (Exception e) {
            log.error("CmsContentController --> getContentDetail() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/getContentDetail", method = RequestMethod.GET)
    @ApiOperation(value = "根据id 查询内容详情(包括附件列表)")
    @ResponseBody
    public ResponseData getContentDetail(@RequestParam(value = "id", required = true) Long id) {
        try {
            return ResponseMsgUtil.success(cmsContentService.getContentDetail(id, "queryWithPatches"));
        } catch (Exception e) {
            log.error("CmsContentController --> getContentDetail() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/getListContent", method = RequestMethod.GET)
    @ApiOperation(value = "查询内容列表（不包括附件）")
    @ResponseBody
    public ResponseData getListContent(@RequestParam(value = "title", required = false) String title,
                                       @RequestParam(value = "category", required = false) Long category,
                                       @RequestParam(value = "categoryCode", required = false) String categoryCode,
                                       @RequestParam(value = "tag", required = false) String tag,
                                       @RequestParam(value = "status", required = false) Integer status,
                                       @RequestParam(value = "companyId", required = false) Long companyId,
                                       @RequestParam(name = "pageNum", required = true) Integer pageNum,
                                       @RequestParam(name = "pageSize", required = true) Integer pageSize) {
        try {
            Map<String, String> paramsMap = new HashMap<>();
            if (StringUtils.isNotBlank(title)) {
                paramsMap.put("title", title);
            }
            if (category != null) {
                paramsMap.put("category", category.toString());
            }
            if (categoryCode != null) {
                paramsMap.put("categoryCode", categoryCode);
            }
            if (StringUtils.isNotBlank(tag)) {
                paramsMap.put("tag", tag);
            }
            if (status != null) {
                paramsMap.put("status", status.toString());
            }
            if (companyId != null) {
                paramsMap.put("companyId", companyId.toString());
            }

            PageHelper.startPage(pageNum, pageSize);
            return ResponseMsgUtil.success(new PageInfo<>(cmsContentService.getListContent(paramsMap)));
        } catch (Exception e) {
            log.error("CmsContentController --> getListContent() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }



    @RequestMapping(value = "/updateStatusOfContent", method = RequestMethod.POST)
    @ApiOperation(value = "更新 内容发布状态")
    @ResponseBody
    public ResponseData updateStatusOfContent(@RequestBody JSONObject jsonObject) {
        try {
            Long id = jsonObject.getLong("id");
            Integer status = jsonObject.getInteger("status");
            Long moduleId = jsonObject.getLong("moduleId");

            if (id == null
                    || status == null
                    || (status != 1 && status != 2 && status != 3)
            ) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            CmsContent content = cmsContentService.getContentById(id);
            if (content == null || content.getStatus() == 0) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.CMS_CONTENT_NOT_FOUND, "");
            }

            Map<String, String> paramsMap = new HashMap<>();
            if (moduleId != null) {
                paramsMap.put("moduleId", moduleId.toString());
            }

            content.setStatus(status);
            if (cmsContentService.updateContent(content, "updateStatusOfContent", paramsMap,sysConfig.getFileUrl()) > 0) {
                return ResponseMsgUtil.success("修改成功");
            } else {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.UPDATE_DATA_ERROR, "");
            }
        } catch (Exception e) {
            log.error("CmsContentController --> updateStatusOfContent() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/updateContentQuantity", method = RequestMethod.GET)
    @ApiOperation(value = "内容访问量+1")
    @ResponseBody
    public ResponseData updateContentQuantity(@RequestParam(value = "id", required = true) Long id) {
        try {
            CmsContent content = cmsContentService.getContentById(id);
            if (content == null || content.getStatus() == 0) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.CMS_CONTENT_NOT_FOUND, "");
            }

            if (content.getVisitCount() != null) {
                content.setVisitCount(content.getVisitCount() + 1);
            } else {
                content.setVisitCount(1);
            }
            if (cmsContentService.updateContent(content, "updateContent", null,null) > 0) {
                return ResponseMsgUtil.success("修改成功");
            } else {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.UPDATE_DATA_ERROR, "");
            }
        } catch (Exception e) {
            log.error("CmsContentController --> updateContentQuantity() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/getListPatches", method = RequestMethod.GET)
    @ApiOperation(value = "查询内容附件列表")
    @ResponseBody
    public ResponseData getListPatches(@RequestParam(value = "contentId", required = true) Long contentId,
                                       @RequestParam(value = "patchType", required = false) Integer patchType,
                                       @RequestParam(name = "pageNum", required = true) Integer pageNum,
                                       @RequestParam(name = "pageSize", required = true) Integer pageSize) {
        try {
            Map<String, String> paramsMap = new HashMap<>();
            if (contentId != null) {
                paramsMap.put("contentId", contentId.toString());
            }
            if (patchType != null) {
                paramsMap.put("patchType", patchType.toString());
            }

            PageHelper.startPage(pageNum, pageSize);
            return ResponseMsgUtil.success(new PageInfo<>(cmsPatchService.getListPatch(paramsMap)));
        } catch (Exception e) {
            log.error("CmsContentController --> getListContent() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/getCompleteContentList", method = RequestMethod.GET)
    @ApiOperation(value = "查询内容列表（包括附件）")
    @ResponseBody
    public ResponseData getCompleteContentList(@RequestParam(value = "title", required = false) String title,
                                       @RequestParam(value = "category", required = false) Long category,
                                       @RequestParam(value = "categoryCode", required = false) String categoryCode,
                                       @RequestParam(value = "tag", required = false) String tag,
                                       @RequestParam(value = "status", required = false) Integer status,
                                       @RequestParam(value = "companyId", required = false) Long companyId,
                                       @RequestParam(name = "pageNum", required = true) Integer pageNum,
                                       @RequestParam(name = "pageSize", required = true) Integer pageSize) {
        try {
            Map<String, String> paramsMap = new HashMap<>();
            if (StringUtils.isNotBlank(title)) {
                paramsMap.put("title", title);
            }
            if (category != null) {
                paramsMap.put("category", category.toString());
            }
            if (categoryCode != null) {
                paramsMap.put("categoryCode", categoryCode);
            }
            if (StringUtils.isNotBlank(tag)) {
                paramsMap.put("tag", tag);
            }
            if (status != null) {
                paramsMap.put("status", status.toString());
            }
            if (companyId != null) {
                paramsMap.put("companyId", companyId.toString());
            }
            PageHelper.startPage(pageNum, pageSize);
            List<CmsContentModel> result = cmsContentService.getListContent(paramsMap);

            // 查询附件列表
            Map<String, String> params = new HashMap<>();
            List<CmsPatch> patchList = cmsPatchService.getListPatch(params);
            // 将附件按类型挂到对应的内容
            for (CmsContentModel item : result) {
                item.setPictures(new ArrayList<>());
                item.setMusics(new ArrayList<>());
                item.setVideos(new ArrayList<>());
                item.setDocuments(new ArrayList<>());
                item.setOthers(new ArrayList<>());

                patchList.stream().filter(patch -> item.getId().equals(patch.getContentId()))
                        .forEach(patch -> {
                            switch (patch.getPatchType()){
                                case 1:
                                    item.getPictures().add(patch);
                                    break;
                                case 2:
                                    item.getMusics().add(patch);
                                    break;
                                case 3:
                                    item.getVideos().add(patch);
                                    break;
                                case 4:
                                    item.getDocuments().add(patch);
                                    break;
                                case 5:
                                    item.getOthers().add(patch);
                                    break;
                            }
                        });
            }

            return ResponseMsgUtil.success(new PageInfo<>(result));
        } catch (Exception e) {
            log.error("CmsContentController --> getListContent() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/getCorporateAdvertising", method = RequestMethod.GET)
    @ApiOperation(value = "查询首页轮播图")
    @ResponseBody
    public ResponseData getCorporateAdvertising() {
        try {
            return ResponseMsgUtil.success(cmsContentService.getCorporateAdvertising());
        } catch (Exception e) {
            log.error("CmsContentController --> getCorporateAdvertising() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }
}
