package com.huiju.estateagents.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.estateagents.base.BaseController;
import com.huiju.estateagents.base.ResponseBean;
import com.huiju.estateagents.common.CommConstant;
import com.huiju.estateagents.common.JWTUtils;
import com.huiju.estateagents.entity.TaBuildingDynamic;
import com.huiju.estateagents.entity.TaNews;
import com.huiju.estateagents.entity.TaPerson;
import com.huiju.estateagents.reportCustomerAop.ReportCustomer;
import com.huiju.estateagents.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.checkerframework.checker.units.qual.A;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
    * 资讯表  前端控制器
    * </p>
 *
 * @author jobob
 * @since 2019-07-25
 */
@RestController
@RequestMapping("/api")
@Api(value = "资讯", tags = "资讯")
public class TaNewsController extends BaseController {

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

    @Autowired
    public ITaNewsService iTaNewsService;

    @Autowired
    public ITaPersonService iTaPersonService;

    @Autowired
    public ITaSaveService iTaSaveService;

    @Autowired
    public ITaBuildingService iTaBuildingService;

    @Autowired
    private IExtendContentService iExtendContentService;
    /**
     * 分页查询列表
     * @param pageNum
     * @param pageSize
     * @return
     */
    @ApiOperation(value = "资讯列表", notes = "资讯列表")
    @ApiImplicitParams({
            @ApiImplicitParam(dataTypeClass = Integer.class, name = "pageNum", paramType = "query",value = "第几页"),
            @ApiImplicitParam(dataTypeClass = Integer.class, name = "pageSize", paramType = "query",value = "一页多少行"),
            @ApiImplicitParam(dataTypeClass = String.class, name = "buildingId", paramType = "query",value = "项目id"),
            @ApiImplicitParam(dataTypeClass = Integer.class, name = "newsTypeId", paramType = "query",value = "资讯类型id"),
            @ApiImplicitParam(dataTypeClass = Integer.class, name = "newsStatus", paramType = "query",value = "状态"),
            @ApiImplicitParam(dataTypeClass = String.class, name = "title", paramType = "query",value = "标题")
    })
    @RequestMapping(value="/admin/taNews",method= RequestMethod.GET)
    public ResponseBean taNewsList(HttpServletRequest request,
                                   @RequestParam(value ="pageNum",defaultValue = "1") Integer pageNum,
                                   @RequestParam(value ="pageSize",defaultValue = "10") Integer pageSize,
                                   @RequestParam(value = "buildingId", required = false) String buildingId,
                                   @RequestParam(value = "newsTypeId", required = false) Integer newsTypeId,
                                   @RequestParam(value = "newsStatus", required = false) Integer newsStatus,
                                   @RequestParam(value = "title", required = false) String title,
                                   @RequestParam(value = "cityId", required = false) Integer cityId){
        ResponseBean responseBean = iTaNewsService.getList(pageNum, pageSize, buildingId, getOrgId(request), newsTypeId, newsStatus, title, cityId,getTaPersonBuildingListByUserId(request));
        return responseBean;
    }

    /**
     * 微信 分页查询列表
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping(value="/wx/taNews",method= RequestMethod.GET)
    public ResponseBean wxTaNewsList(@RequestParam(value ="pageNumber",defaultValue = "1") Integer pageNumber,
                                     @RequestParam(value ="pageSize",defaultValue = "10") Integer pageSize,
                                     @RequestParam(required = false) String buildingId,
                                     @RequestParam(required = false) Integer cityId,
                                     @RequestParam(defaultValue = "false") Boolean mine,
                                     HttpServletRequest request
    ){
        List<String> targets = new ArrayList<>();
        Integer orgId = getOrgId(request);
        if (null != mine && mine) {
            String openid = getOpenId(request);
            List<TaPerson> persons = iTaPersonService.getPersonsByOpenId(openid);
            if (null == persons || persons.size() == 0) {
                return ResponseBean.error("当前账户信息异常, 清除缓存重试", ResponseBean.ERROR_UNAVAILABLE);
            }

            targets = iTaSaveService.getTargesOfPerson(persons.get(0).getPersonId(), CommConstant.FAVOR_NEWS);
        }

        IPage<TaNews> results = iTaNewsService.getWxList(pageNumber, pageSize, buildingId, targets,cityId,mine,orgId);
        return ResponseBean.success(results);
    }

    /**
     * 保存对象
     * @param taNews 实体对象
     * @return
     */
    @ApiOperation(value = "保存资讯", notes = "保存资讯")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "TaNews", name = "taNews", paramType = "body",value = "资讯详细数据")
    })
    @RequestMapping(value="/admin/taNews",method= RequestMethod.POST)
    public ResponseBean taNewsAdd(@RequestBody TaNews taNews, HttpServletRequest request){
        Integer cityId = iTaBuildingService.getCityById(taNews.getBuildingId());
        taNews.setCityId(cityId);
        taNews.setOrgId(getOrgId(request));
        ResponseBean responseBean = iTaNewsService.addTaNews(taNews);
        return responseBean;
    }

    /**
     * 根据id删除对象
     * @param id  实体ID
     */
    @ResponseBody
    @RequestMapping(value="/admin/taNews/{id}", method= RequestMethod.DELETE)
    public ResponseBean taNewsDelete(@PathVariable Integer id){
        ResponseBean responseBean = iTaNewsService.deleteTaNews(id);
        return responseBean;
    }

    /**
     * 修改对象
     * @param id  实体ID
     * @param taNews 实体对象
     * @return
     */
    @ApiOperation(value = "修改资讯", notes = "修改资讯")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "TaNews", name = "taNews", paramType = "body",value = "资讯数据"),
            @ApiImplicitParam(dataTypeClass = Integer.class, name = "taNews", paramType = "path", value = "资讯id")
    })
    @RequestMapping(value="/admin/taNews/{id}",method= RequestMethod.PUT)
    public ResponseBean taNewsUpdate(@PathVariable Integer id,
                                        @RequestBody TaNews taNews,
                                     HttpServletRequest request){
        taNews.setNewsId(id);
        Integer cityId = iTaBuildingService.getCityById(taNews.getBuildingId());
        taNews.setCityId(cityId);
        taNews.setOrgId(getOrgId(request));
        ResponseBean responseBean = iTaNewsService.updateTaNews(taNews);
        if ("1".equals(String.valueOf(taNews.getNewsStatus()))){
            // 设置为取消发布以后把轮播图和资讯设置为停用
            iExtendContentService.updateActivity(String.valueOf(id),"news",getOrgId(request));
        }
        return responseBean;
    }

    /**
     * 根据id查询对象
     * @param id  实体ID
     */
    @ApiOperation(value = "咨询详情", notes = "咨询详情")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "id", paramType = "path",value = "资讯id")
    })
    @RequestMapping(value="/admin/taNews/{id}",method= RequestMethod.GET)
    public ResponseBean taNewsGet(@PathVariable Integer id){
        ResponseBean responseBean = iTaNewsService.getTaNewsById(id);
        return responseBean;
    }

    @ApiOperation(value = "资讯置顶", notes = "资讯置顶")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "newsId", paramType = "query",value = "资讯ID"),
            @ApiImplicitParam(dataType = "Integer", name = "weight", paramType = "query",value = "权重")
    })
    @RequestMapping(value = "/admin/taNews/weight" ,method =RequestMethod.PUT)
    public  ResponseBean buildingDynamicWeight(@RequestParam Integer newsId,@RequestParam Integer weight,HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        TaNews taNews = iTaNewsService.getById(newsId);
        taNews.setWeight(weight);
        taNews.setOrgId(getOrgId(request));
        QueryWrapper<TaNews> newsQueryWrapper = new QueryWrapper<>();
        newsQueryWrapper.eq("news_id",newsId);
        if (iTaNewsService.updateById(taNews)){
            responseBean.addSuccess("成功");
        }else {
            responseBean.addError("失败");
        }
        return responseBean;
    }


    /**
     * 微信 根据id查询对象
     * @param id  实体ID
     */
    @RequestMapping(value="/wx/taNews/{id}",method= RequestMethod.GET)
    @ReportCustomer(type = "news")
    public ResponseBean wxTaNewsGet(@PathVariable Integer id,
                                    @RequestParam(value = "qrCodeId", required = false) String qrCodeId,
                                    @RequestParam(value = "channelId", required = false) String channelId,
                                    @RequestParam(value = "sceneId", required = false) String sceneId,
                                    HttpServletRequest request){
        String openid = getOpenId(request);
        List<TaPerson> persons = iTaPersonService.getPersonsByOpenId(openid);
        if (null == persons || persons.size() == 0) {
            return ResponseBean.error("当前账户信息异常, 清除缓存重试", ResponseBean.ERROR_UNAVAILABLE);
        }
        TaPerson person = persons.get(0);
        ResponseBean responseBean = iTaNewsService.getWxTaNewsById(id,person.getPersonId());
        return responseBean;
    }

    /**
     * 微信 资讯阅读量+1
     * @param id
     * @return
     */
    @RequestMapping(value = "/wx/taNews/pvNum/{id}", method = RequestMethod.PUT)
    public ResponseBean wxTaPvNum(@PathVariable Integer id) {
        ResponseBean responseBean = iTaNewsService.wxTaPvNum(id);
        return responseBean;
    }
}
