package com.nbclass.activity.controller;

import java.text.Collator;
import java.util.*;
import java.util.stream.Collectors;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import com.nbclass.activity.model.*;
import com.nbclass.activity.service.DataDictService;
import com.nbclass.exception.ParameterException;
import com.nbclass.system.service.UserService;
import com.nbclass.util.JWTUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.nbclass.activity.model.enums.ContentType;
import com.nbclass.activity.service.ContentService;
import com.nbclass.system.controller.BaseController;
import com.nbclass.system.model.SysLog;
import com.nbclass.system.model.User;
import com.nbclass.system.model.enums.SysLogType;
import com.nbclass.system.service.SysLogService;
import com.nbclass.util.CommonUtils;
import com.nbclass.util.PageUtil;
import com.nbclass.util.ResultUtil;
import com.nbclass.vo.base.PageResultVo;
import com.nbclass.vo.base.Result;

/**
 * 案例内容
 * @author Leon
 * @datetime 2020年5月28日 下午4:43:17
 */
@Controller
@RequestMapping("/console/content")
public class ContentController extends BaseController {

    @Resource
    private ContentService service;

    @Resource
    private SysLogService sysLogService;

    @Resource
    private UserService userService;

    @Resource
    private DataDictService dataDictService;

    /**
     * 案例页面
     * @param model
     * @return
     */
    @GetMapping("/indexPage")
    public String indexPage(Model model){
        return "content/list2";
    }

    /**
     * 案例页面
     * @param model
     * @return
     */
    @GetMapping("/index-application")
    public String application(Model model){
        return "content/application";
    }

    /**
     * 案例统计列表
     * @param model
     * @return
     */
    @GetMapping("/index-census")
    public String census(Model model){
        return "content/census";
    }

    @GetMapping("/index-logger")
    public String logger(Model model){
        return "content-logger/list";
    }

    /**
     * i技术开发案例页面
     * @param model
     * @return
     */
    @GetMapping("/index-h5")
    public String h5Page(Model model){
    	model.addAttribute("caseType", ContentType.h5.key());
        return "content/list";
    }

    /**
     * i创意设计案例页面
     * @param model
     * @return
     */
    @GetMapping("/index-design")
    public String designPage(Model model){
    	model.addAttribute("caseType", ContentType.design.key());
    //	return "content/list";
        return "content-editor/list";
    }

    /**
     * i视频动画案例页面
     * @param model
     * @return
     */
    @GetMapping("/index-video")
    public String videoPage(Model model){
    	model.addAttribute("caseType", ContentType.video.key());
        return "content/list";
    }

    /**
     * i品牌全案 - 富文本编辑器形式
     * @param model
     * @return
     */
    @GetMapping("/index-ppqa")
    public String ppqaPage(Model model){
    	model.addAttribute("caseType", ContentType.ppqa.key());
        return "content-editor/list";
    }

    /**
     * i公关全案 - 富文本编辑器形式
     * @param model
     * @return
     */
    @GetMapping("/index-ggqa")
    public String ggqaPage(Model model){
    	model.addAttribute("caseType", ContentType.ggqa.key());
        return "content-editor/list";
    }

    /**
     * i落地活动 - 富文本编辑器形式
     * @param model
     * @return
     */
    @GetMapping("/index-ldhd")
    public String ldhdPage(Model model){
    	model.addAttribute("caseType", ContentType.ldhd.key());
        return "content-editor/list";
    }

    /**
     * i其他案例 - 富文本编辑器形式
     * @param model
     * @return
     */
    @GetMapping("/index-others")
    public String othersPage(Model model){
    	model.addAttribute("caseType", ContentType.others.key());
        return "content-editor/list";
    }

    /**
     * i编辑页面
     * @param model
     * @param id
     * @return
     */
    @GetMapping("/edit")
    public String editPage(Model model, String caseType, Long id){
    	Content entity = new Content();
    	if(id!=null && id>0)entity=service.findById(id);
    	JSONObject obj = (JSONObject) JSON.toJSON(entity);
    	model.addAllAttributes(obj);
    	model.addAttribute("caseType", caseType);
    	return "content/edit";
    }

    /**
     * i编辑页面
     * @param model
     * @param id
     * @return
     */
    @GetMapping("/edit2")
    public String editPage2(Model model, String caseType, Long id,Long applicationId,Integer count){
        Content entity = new Content();
        if(id!=null && id>0)entity=service.findById(id);
        if(count!=null) entity.setCount(count);
        if(applicationId!=null) entity.setApplicationId(applicationId);
        JSONObject obj = (JSONObject) JSON.toJSON(entity);
        model.addAllAttributes(obj);
        model.addAttribute("caseType", caseType);
        return "content/edit2";
    }

    /**
     * i富文本编辑器的编辑页面
     * @param model
     * @param caseType
     * @param id
     * @return
     */
    @GetMapping("/edit-editor")
    public String editEditorPage(Model model, String caseType, Long id){
    	Content entity = new Content();
    	if(id!=null && id>0)entity=service.findById(id);
    	JSONObject obj = (JSONObject) JSON.toJSON(entity);
    	model.addAllAttributes(obj);
    	model.addAttribute("caseType", caseType);
    	return "content-editor/edit";
    }

    /**
     * i查询数据列表
     * @param entity
     * @param limit
     * @param offset
     * @return
     */
    @PostMapping("/list")
    @ResponseBody
    public PageResultVo getList(Content entity, Integer limit, Integer offset){
        PageHelper.startPage(PageUtil.getPageNo(limit, offset),limit);
        List<Content> userList = service.getList(entity);
        PageInfo<Content> pages = new PageInfo<>(userList);
        return ResultUtil.table(userList,pages.getTotal());
    }

    /**
     * i查询数据列表
     * @param entity
     * @param limit
     * @param offset
     * @return
     */
    @PostMapping("/list2")
    @ResponseBody
    public PageResultVo getList2(Content entity, Integer limit, Integer offset,HttpServletRequest request){
        User loginUser = getLoginUser();
        User user = userService.selectByUsername(loginUser.getUsername());
        if(!user.getUsername().contains("admin")){
            entity.setUserId(Long.parseLong(user.getId().toString()));
        }
        List<String> list = Arrays.asList(entity.getTagLists());
        String[] strings = list.stream().filter(String -> !String.isEmpty()).toArray(String[]::new);
        if(strings.length == 0){
            entity.setTagLists(null);
        }else {
            entity.setTagLists(strings);
            entity.setCount(strings.length);
        }
        //查询用户的职位信息
        String roleId = userService.getUserRole(user.getUserId());
        entity.setRoleId(roleId);
        PageHelper.startPage(PageUtil.getPageNo(limit, offset),limit);
        List<Content> userList = service.getList2(entity);
        PageInfo<Content> pages = new PageInfo<>(userList);
        return ResultUtil.table(userList,pages.getTotal());
    }


    /**
     * i添加或修改数据
     * @param entity
     */
    @PostMapping("/merge")
    @ResponseBody
    public Result merge(Content entity){
        if(StringUtils.isNotBlank(entity.getImages())) {
        	// json数据去除多余的引号，否则存数据库报错
        	String imgList = entity.getImages();
        	imgList = imgList.replace("\"{", "{").replace("}\"", "}").replace("\\", "");
        	entity.setImages(imgList);
        }
        String type = "";
        if(entity.getTagLists().length != 0){
            for (String tagList : entity.getTagLists()) {
                if(tagList.equals("106") || tagList.equals("107")
                        || tagList.equals("108") || tagList.equals("109")
                        || tagList.equals("110") || tagList.equals("111")
                        || tagList.equals("112")){
                    type = ContentType.getNameByCode(tagList);
                }
            }
        }
        String desc = null;
    	if(entity.getId()!=null && entity.getId()>0){
            service.update(entity);
            if(entity.getApplicationId()!=null){
                //更新审核申请单状态
                service.updateApplicationStatus(entity.getId(),entity.getApplicationId());
            }
            desc="修改案例，案例类型："+type+"，案例ID："+entity.getId()+"，案例标题："+entity.getTitle();
        }else{
            User loginUser = getLoginUser();
            User user = userService.selectByUsername(loginUser.getUsername());
            entity.setUserId(Long.parseLong(user.getId().toString()));
            service.add(entity);
            //标签关联案例
            String[] tagList = entity.getTagLists();
            for (String s : tagList) {
                ContentTags contentTags = new ContentTags();
                contentTags.setCid(entity.getId());
                contentTags.setTid(Long.parseLong(s));
                service.addContentTags(contentTags);
            }
            desc="添加案例，案例类型："+type+"，案例ID："+entity.getId()+"，案例标题："+entity.getTitle();
        }
    	User user = getLoginUser();
        sysLogService.add(new SysLog(SysLogType.cases.key(), user.getUserId()+"（"+user.getUsername()+"）", getIpAddr(), desc));

        return Result.success();
    }

    /**删除用户*/
    @PostMapping("/delete")
    @ResponseBody
    public Result delete(String ids) {
        List<Long> IdList = CommonUtils.toLongList(ids);
        for (Long aLong : IdList) {
            //案例是否发布
            Content editContent = service.getEditContent(aLong);
            if(editContent.getStatus() != 5 && editContent.getStatus() !=3 || editContent.getStatus() == 2){
                throw new ParameterException("案例已上线或审核中，无法删除!");
            }
            if(editContent.getRelease() == 3){
                service.deleteApplication(editContent.getApplicationId());
            }
        }
        service.delete(IdList);
        //取消案例关联标签的关系
        service.deleteContentTags(IdList);
        User user = getLoginUser();
        sysLogService.add(new SysLog(SysLogType.cases.key(), user.getUserId()+"（"+user.getUsername()+"）", getIpAddr(), "删除案例，ids："+ids));
        return Result.success();
    }

    /**
     * 同步MySQL数据到ES
     * @param ids 如果有值，同步指定id，如果没有值，同步全部
     * @return
     */
    @PostMapping("/syncEsData")
    @ResponseBody
    public Result syncEsData(Content entity, @RequestParam(defaultValue="false")Boolean isReBuild) {
    	long total = service.syncEsData(entity, isReBuild);
    	User user = getLoginUser();
        sysLogService.add(new SysLog(SysLogType.cases.key(), user.getUserId()+"（"+user.getUsername()+"）", getIpAddr(),
        		"同步案例到ElasticSearch，是否重建："+isReBuild+"，受影响的记录数："+total));
        return Result.success(total);
    }

    /**
     * 查询案例标题、评论数和点赞数
     * @return
     */
    @GetMapping("/getCaseTitle")
    @ResponseBody
    public Result getCaseTitle(Integer page,Integer pageSize){
        PageInfo<Content> list = service.getCaseTitle(page,pageSize);
        return Result.success(list);
    }

    /**
     * 获取自定义标签列表
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/getOtherLabels")
    @ResponseBody
    public Result getOtherLabels(Integer page,Integer pageSize){
        PageHelper.startPage(page,pageSize);
        List<DataDictItem> list = service.getOtherLabels();
        return Result.success(new PageInfo<>(list));
    }

    /**
     * 添加案例评分
     * @param request
     * @return
     */
    @PostMapping("/saveScore")
    @ResponseBody
    public Result saveScore(HttpServletRequest request,Long contentId,Double score){
        String token = request.getHeader("token");
        String Id = JWTUtils.getUserId(token);
        Long userId = Long.parseLong(Id);
        //查看用户是否已经打过分
        int result = service.getScore(userId,contentId);
        if(result > 0 ) throw new ParameterException("请勿重复打分!");
        service.saveScore(userId,contentId,score);
        return Result.success();
    }

    /**
     * 根据案例id查询案例详情
     * @param contentId
     * @return
     */
    @GetMapping("/getEditContent")
    @ResponseBody
    public Result getEditContent(Long contentId){
        Content content = service.getEditContent(contentId);
        return Result.success(content);
    }

    /**
     * 提交审核申请单
     * @param application
     * @return
     */
    @PostMapping("/saveApplication")
    @ResponseBody
    public Result saveApplication(Application application){
        //查询案例是否已提交过审核
        int result = service.getApplicationCount(application.getContentId());
        if(result > 0 ) throw new ParameterException("请勿重复提交审核!");
        User loginUser = getLoginUser();
        User user = userService.selectByUsername(loginUser.getUsername());
        application.setUserId(Long.parseLong(user.getId().toString()));
        List<Check> checks;
        if(!loginUser.getUserId().equals("admin")){
            //根据userId获取微信用户信息
            WxUser wxUser = service.getQyWxUser(user.getUsername());
            //根据部门id获取用户领导
            checks = service.getUserLeader(wxUser.getDepartment());
        }else {
            checks = new ArrayList<>();
            Check check = new Check();
            check.setCheckId(1L);
            checks.add(check);
        }
        application.setChecks(checks);

        //添加审核申请单
        service.saveApplication(application);
        return Result.success();
    }

    /**
     * 撤回审核申请单
     * @return
     */
    @PostMapping("/deleteApplication")
    @ResponseBody
    public Result deleteApplication(Long applicationId){
        //删除案例审核申请
        service.deleteApplication(applicationId);
        return Result.success();
    }


    /**
     * 获取审核列表
     * @return
     */
    @PostMapping("/getContentApplication")
    @ResponseBody
    public PageResultVo getContentApplication(Content entity,Integer limit, Integer offset){
        User loginUser = getLoginUser();
        User user = userService.selectByUsername(loginUser.getUsername());
        entity.setUserId(Long.parseLong(user.getId().toString()));
        List<String> list = Arrays.asList(entity.getTagLists());
        String[] strings = list.stream().filter(String -> !String.isEmpty()).toArray(String[]::new);
        if(strings.length == 0){
            entity.setTagLists(null);
        }else {
            entity.setTagLists(strings);
            entity.setCount(strings.length);
        }
        PageHelper.startPage(limit,offset);
        List<Content> list2 = service.getContentApplication(entity);
        PageInfo<Content> pageInfo = new PageInfo<>(list2);
        return ResultUtil.table(list2,pageInfo.getTotal());
    }

    /**
     * 审核案例
     * @return
     */
    @PostMapping("/updateApplication")
    @ResponseBody
    public Result updateApplication(Check check){
        User loginUser = getLoginUser();
        User user = userService.selectByUsername(loginUser.getUsername());
        service.updateApplication(check,Long.parseLong(user.getId().toString()));
        return Result.success();
    }

    /**
     * 下线案例
     * @param contentId
     * @return
     */
    @PostMapping("/deleteRelease")
    @ResponseBody
    public Result deleteRelease(Long contentId){
        service.deleteRelease(contentId);
        return Result.success();
    }

    /**
     * 案例统计
     * @param type
     * @return
     */
    @GetMapping("/getCensus")
    @ResponseBody
    public Result getCensus(Integer type){
        //根据type获取统计信息  1、本周统计 2、本月统计 3、本季度统计 4、年度统计
        List<Census> list = service.getCensus(type);
        Long count = 0L;
        for (Census census : list) {
            count += census.getCount();
        }
        List<Integer> list2 = new ArrayList<>();
        list.sort(Comparator.comparing(Census::getId));
        for (int i = 0; i < list.size(); i++) {
            if(list.get(i).getId() == 254 || list.get(i).getId() == 262 || list.get(i).getId() == 267){
                list.remove(i);
            }
            list2.add(list.get(i).getCount());
        }
        Map<String,Object> map = new HashMap<>();
        map.put("count",count);
        map.put("list",list2);
        return Result.success(map);
    }

}
