package com.huiju.foyo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huiju.foyo.common.BaseController;
import com.huiju.foyo.common.CommUtils;
import com.huiju.foyo.common.ConstantFoyo;
import com.huiju.foyo.common.ResponseBean;
import com.huiju.foyo.model.TaCase;
import com.huiju.foyo.model.TaCover;
import com.huiju.foyo.model.TaLikeLog;
import com.huiju.foyo.service.ITaCaseService;
import com.huiju.foyo.service.ITaCoverService;
import com.huiju.foyo.service.ITaLikeLogService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
    * 案例表  前端控制器
    * </p>
 *
 * @author jobob
 * @since 2019-08-21
 */
@RestController
@RequestMapping("/")
public class TaCaseController extends BaseController {

    private final Logger logger = LoggerFactory.getLogger(TaCaseController.class);

    @Autowired
    public ITaCaseService iTaCaseService;

    @Autowired
    public ITaLikeLogService iTaLikeLogService;

    @Autowired
    public ITaCoverService iTaCoverService;

    /**
     * 分页查询列表
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping(value="/admin/case/list",method= RequestMethod.GET)
    public ResponseBean taCaseList(@RequestParam(value ="pageNum",defaultValue = "1") Integer pageNum,
                                   @RequestParam(value ="pageSize",defaultValue = "10") Integer pageSize,
                                   @RequestParam(required = false) String type){
        ResponseBean responseBean = new ResponseBean();
        try {
            //使用分页插件
		    IPage<TaCase> pg = new Page<>(pageNum, pageSize);
            QueryWrapper<TaCase> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq(null != type, "type", type);
            queryWrapper.eq("status", ConstantFoyo.STATUS_EFFECTIVE);
            queryWrapper.orderByDesc("sort");
            queryWrapper.orderByDesc("create_time");

            IPage<TaCase> result = iTaCaseService.page(pg, queryWrapper);
            responseBean.addSuccess(result);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taCaseList -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 保存对象
     * @param taCase 实体对象
     * @return
     */
    @RequestMapping(value="/admin/case/add",method= RequestMethod.POST)
    public ResponseBean taCaseAdd(@RequestBody TaCase taCase){
        ResponseBean responseBean = new ResponseBean();
        try {
            if (null != taCase.getId()){
                taCase.setUpdateBy(ConstantFoyo.USER_ADMIN);
                taCase.setCreateTime(LocalDateTime.now());
                if (iTaCaseService.updateById(taCase)){
                    responseBean.addSuccess(taCase);
                }else {
                    responseBean.addError("fail");
                }
            }else{
                taCase.setStatus(ConstantFoyo.STATUS_EFFECTIVE);
                taCase.setCreateBy(ConstantFoyo.USER_ADMIN);
                taCase.setCreateTime(LocalDateTime.now());
                if (iTaCaseService.save(taCase)){
                    responseBean.addSuccess(taCase);
                }else {
                    responseBean.addError("fail");
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taCaseAdd -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 根据id删除对象
     */
    @ResponseBody
    @RequestMapping(value="/admin/case/delete", method= RequestMethod.DELETE)
    public ResponseBean taCaseDelete(@RequestBody String[] ids){
        ResponseBean responseBean = new ResponseBean();
        try {
            List<String> idList = Arrays.asList(ids);
            if(iTaCaseService.removeByIds(idList)){
                responseBean.addSuccess("success");
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taCaseDelete -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 修改对象
     * @param id  实体ID
     * @param taCase 实体对象
     * @return
     */
    @RequestMapping(value="/taCase/{id}",method= RequestMethod.PUT)
    public ResponseBean taCaseUpdate(@PathVariable Integer id,
                                        @RequestBody TaCase taCase){
        ResponseBean responseBean = new ResponseBean();
        try {
            if (iTaCaseService.updateById(taCase)){
                responseBean.addSuccess(taCase);
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taCaseUpdate -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 根据id查询对象
     * @param id  实体ID
     */
    @RequestMapping(value="/admin/case/{id}",method= RequestMethod.GET)
    public ResponseBean taCaseGet(@PathVariable Integer id){
        ResponseBean responseBean = new ResponseBean();
        try {
            responseBean.addSuccess(iTaCaseService.getById(id));
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taCaseDelete -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }
    
    /**
     * 分页查询列表
     * @return
     */
    @RequestMapping(value="/pc/case/{state}/list",method= RequestMethod.GET)
    public ResponseBean pcCaseList(@PathVariable String state,
                                   @RequestParam(value ="pageNum",defaultValue = "1") Integer pageNum,
                                   @RequestParam(value ="pageSize",defaultValue = "10") Integer pageSize,
                                   @RequestParam(required = false) String caseType
                                   ){
        ResponseBean responseBean = new ResponseBean();
        if (!state.equals(ConstantFoyo.TYPE_CASE) && !state.equals(ConstantFoyo.TYPE_MOVEMENT)){
            responseBean.addError("不符合的类型");
            return responseBean;
        }
        try {
            IPage<TaCase> pg = new Page<>(pageNum, pageSize);
            QueryWrapper<TaCase> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq(null != caseType && !"".equals(caseType.trim()), "ta_case_type_id", caseType);
            queryWrapper.eq("status", ConstantFoyo.STATUS_EFFECTIVE);
            queryWrapper.eq("type",state);
            queryWrapper.orderByDesc("topping");
            queryWrapper.orderByDesc("sort");
            queryWrapper.orderByDesc("create_time");
            IPage<TaCase> result = iTaCaseService.page(pg, queryWrapper);
            responseBean.addSuccess(result);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taCaseList -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    @GetMapping("/pc/case/{caseId}")
    public ResponseBean get(@PathVariable Integer caseId) {
        TaCase taCase = iTaCaseService.getById(caseId);
        if (null == taCase) {
            return ResponseBean.error("非法的案例或者动态ID");
        }

        // 封面
        QueryWrapper<TaCover> wrapper = new QueryWrapper<>();
        wrapper.eq("type", taCase.getType());
        wrapper.last("limit 1");
        TaCover taCover = iTaCoverService.getOne(wrapper);

        // 上一条, 下一条
        List<TaCase> brothers = iTaCaseService.getBrothers(taCase);

        // 推荐随机获取数据
        QueryWrapper<TaCase> query = new QueryWrapper<>();
        query.eq("type", taCase.getType());
        query.ne("id", caseId);
        query.last("ORDER BY RAND() LIMIT 10");
        List<TaCase> recommends = iTaCaseService.list(query);

        Map<String, Object> result = new HashMap<String, Object>(){{
            put("current", taCase);
            put("cover", taCover);
            put("brothers", brothers);
            put("recommends", recommends);
        }};

        return ResponseBean.success(result);
    }

    @PostMapping("/pc/like/case/{caseId}")
    public ResponseBean postLike(@PathVariable Integer caseId, HttpServletRequest request) {
        String ip = CommUtils.getIpAddr(request);

        TaCase taCase = iTaCaseService.getById(caseId);
        if (null == taCase) {
            return ResponseBean.error("非法的案例或者动态ID");
        }

        TaLikeLog taLikeLog = new TaLikeLog();
        taLikeLog.setAgent("ip="+ip);
        taLikeLog.setCreateDate(LocalDateTime.now());
        taLikeLog.setTarget(caseId);
        taLikeLog.setTargetType("case");

        Integer likeNum = iTaLikeLogService.postCaseLike(taCase, taLikeLog);
        return ResponseBean.success(likeNum);
    }
}
