package com.yunzhi.marketing.xlk.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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.yunzhi.marketing.base.BaseController;
import com.yunzhi.marketing.base.ResponseBean;
import com.yunzhi.marketing.common.StringUtils;
import com.yunzhi.marketing.entity.TaPerson;
import com.yunzhi.marketing.service.ITaPersonService;
import com.yunzhi.marketing.xlk.dto.CurriculumDTO;
import com.yunzhi.marketing.xlk.entity.Brand;
import com.yunzhi.marketing.xlk.entity.Video;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.yunzhi.marketing.xlk.service.ICurriculumService;
import com.yunzhi.marketing.xlk.entity.Curriculum;
import org.springframework.web.bind.annotation.RestController;

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

/**
 * <p>
    * 课程表  前端控制器
    * </p>
 *
 * @author jobob
 * @since 2021-05-18
 */
@RestController
@RequestMapping("/api")
@Api(value = "课程表", tags = "xlk-课程表")
public class CurriculumController extends BaseController {

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

    @Autowired
    public ICurriculumService iCurriculumService;

    @Autowired
    public ITaPersonService taPersonService;


    /**
     * 分页查询列表
     * @param pageNum
     * @param pageSize
     * @return
     */
    @ApiOperation(value = "admin-查询课程表列表", notes = "admin-查询课程表列表")
    @RequestMapping(value="/admin/curriculum",method= RequestMethod.GET)
    public ResponseBean curriculumList(@RequestParam(value ="pageNum",defaultValue = "1") Integer pageNum,
                                       @RequestParam(value ="pageSize",defaultValue = "10") Integer pageSize,
                                       @RequestParam(value ="name",required = false) String name,
                                       @RequestParam(value ="roleId",required = false) Integer roleId,
                                       @RequestHeader("authorization") String token, HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        try {
            //使用分页插件
		    IPage<Curriculum> pg = new Page<>(pageNum, pageSize);
            LambdaQueryWrapper<Curriculum> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Curriculum::getOrgId,getOrgId(request));
            queryWrapper.eq(!StringUtils.isEmpty(name),Curriculum::getName,name);
            queryWrapper.eq(null != roleId,Curriculum::getRoleId,roleId);
            queryWrapper.orderByDesc(Curriculum::getWeight);
            queryWrapper.orderByDesc(Curriculum::getCreatedTime);

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

    /**
     * 保存对象
     * @param curriculumDTO 实体对象
     * @return
     */
    @ApiOperation(value = "admin-新增课程表", notes = "admin-新增课程表")
    @RequestMapping(value="/admin/curriculum",method= RequestMethod.POST)
    public ResponseBean curriculumAdd(@RequestBody CurriculumDTO curriculumDTO,
                                      @RequestHeader("authorization") String token, HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        try {
            Curriculum curriculum = new Curriculum();
            BeanUtils.copyProperties(curriculumDTO,curriculum);
            curriculum.setCreatedTime(LocalDateTime.now());
            curriculum.setCreatedBy(getUserId(request));
            curriculum.setOrgId(getOrgId(request));
            if (iCurriculumService.save(curriculum)){
                responseBean.addSuccess(curriculum);
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("curriculumAdd -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 根据id删除对象
     * @param id  实体ID
     */
    @ApiOperation(value = "admin-根据id删除课程表", notes = "admin-根据id删除课程表")
    @ResponseBody
    @RequestMapping(value="/admin/curriculum/{id}", method= RequestMethod.DELETE)
    public ResponseBean curriculumDelete(@PathVariable String id,
                                         @RequestHeader("authorization") String token, HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        try {
            if(iCurriculumService.removeById(id)){
                responseBean.addSuccess("success");
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("curriculumDelete -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 修改对象
     * @param id  实体ID
     * @param curriculumDTO 实体对象
     * @return
     */
    @ApiOperation(value = "admin-根据id修改课程表", notes = "admin-根据id修改课程表")
    @RequestMapping(value="/admin/curriculum/{id}",method= RequestMethod.PUT)
    public ResponseBean curriculumUpdate(@PathVariable String id,
                                        @RequestBody CurriculumDTO curriculumDTO,
                                         @RequestHeader("authorization") String token, HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        try {
            Curriculum curriculum = new Curriculum();
            BeanUtils.copyProperties(curriculumDTO,curriculum);
            curriculum.setCurriculumId(id);
            if (iCurriculumService.updateById(curriculum)){
                responseBean.addSuccess(curriculum);
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("curriculumUpdate -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 根据id查询对象
     * @param id  实体ID
     */
    @ApiOperation(value = "admin-根据id查询课程表详情", notes = "admin-根据id查询课程表详情")
    @RequestMapping(value="/admin/curriculum/{id}",method= RequestMethod.GET)
    public ResponseBean curriculumGet(@PathVariable String id,
                                      @RequestHeader("authorization") String token, HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        try {
            responseBean.addSuccess(iCurriculumService.getById(id));
        }catch (Exception e){
            e.printStackTrace();
            logger.error("curriculumDelete -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 分页查询列表
     * @param pageNum
     * @param pageSize
     * @return
     */
    @ApiOperation(value = "wx-查询课程表列表", notes = "wx-查询课程表列表")
    @RequestMapping(value="/wx/curriculum",method= RequestMethod.GET)
    public ResponseBean wxCurriculumList(@RequestParam(value ="pageNum",defaultValue = "1") Integer pageNum,
                                       @RequestParam(value ="pageSize",defaultValue = "10") Integer pageSize,
                                       @RequestParam(value ="name",required = false) String name,
                                       @RequestParam(value ="roleId",required = false) Integer roleId,
                                       @RequestHeader("authorization") String token, HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        try {
            //使用分页插件
            IPage<Curriculum> pg = new Page<>(pageNum, pageSize);
            LambdaQueryWrapper<Curriculum> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Curriculum::getOrgId,getOrgId(request));
            queryWrapper.eq(!StringUtils.isEmpty(name),Curriculum::getName,name);
            queryWrapper.eq(null != roleId,Curriculum::getRoleId,roleId);
            queryWrapper.orderByDesc(Curriculum::getWeight);
            queryWrapper.orderByDesc(Curriculum::getCreatedTime);

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

    /**
     * 分页查询列表
     * @param pageNum
     * @param pageSize
     * @return
     */
    @ApiOperation(value = "wx-查询我收藏的课程表列表", notes = "wx-查询我收藏的课程表列表")
    @RequestMapping(value="/wx/curriculum/save",method= RequestMethod.GET)
    public ResponseBean saveCurriculumList(@RequestParam(value ="pageNum",defaultValue = "1") Integer pageNum,
                                         @RequestParam(value ="pageSize",defaultValue = "10") Integer pageSize,
                                         @RequestHeader("authorization") String token, HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        try {

            String openid = getOpenId(request);
            List<TaPerson> persons = taPersonService.getPersonsByOpenId(openid);
            if (null == persons || persons.size() == 0) {
                return ResponseBean.error("当前账户信息异常, 清除缓存重试", ResponseBean.ERROR_UNAVAILABLE);
            }
            TaPerson person = persons.get(0);
            IPage<Curriculum> result = iCurriculumService.selectMySaveList(pageNum,pageSize,person);
            responseBean.addSuccess(result);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("curriculumList -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 根据id查询对象
     * @param id  实体ID
     */
    @ApiOperation(value = "wx-根据id查询课程表详情", notes = "wx-根据id查询课程表详情")
    @RequestMapping(value="/wx/curriculum/{id}",method= RequestMethod.GET)
    public ResponseBean curriculum(@PathVariable String id,
                                      @RequestHeader("authorization") String token, HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        try {
            Curriculum curriculum = iCurriculumService.getById(id);
            curriculum.setLookNum(curriculum.getLookNum() + 1);
            iCurriculumService.updateById(curriculum);
            responseBean.addSuccess(curriculum);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("curriculumDelete -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }
}
