package com.yunzhi.marketing.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.yunzhi.marketing.base.BaseController;
import com.yunzhi.marketing.base.ResponseBean;
import com.yunzhi.marketing.service.*;
import com.yunzhi.marketing.service.impl.HelpActivityServiceImpl;
import com.yunzhi.marketing.entity.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
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.List;
import java.util.stream.Collectors;

/**
 * <p>
    * 辅助内容表  前端控制器
    * </p>
 *
 * @author jobob
 * @since 2019-07-25
 */
@RestController
@RequestMapping("/api")
@Api(value = "轮播图", tags = "轮播图")
public class ExtendContentController extends BaseController {

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

    @Autowired
    public IExtendContentService iExtendContentService;

    @Autowired
    private ITaBuildingDynamicService iTaBuildingDynamicService;

    @Autowired
    private ITaBuildingService iTaBuildingService;

    @Autowired
    private ITdCityService iTdCityService;

    @Autowired
    private ITaNewsService iTaNewsService;

    @Autowired
    private ITaShareActivityService iTaShareActivityService;

    @Autowired
    private HelpActivityServiceImpl helpActivityService;

    /**
     * 分页查询列表
     * @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 = String.class, name = "contentType", paramType = "query",value = "内容类型"),
            @ApiImplicitParam(dataTypeClass = String.class, name = "showPosition", paramType = "query",value = "发布位置"),
            @ApiImplicitParam(dataTypeClass = Integer.class, name = "status", paramType = "query",value = "状态"),
            @ApiImplicitParam(dataTypeClass = String.class, name = "showType", paramType = "query",value = "发布类型")
    })
    @RequestMapping(value="/admin/extendContent",method= RequestMethod.GET)
    public ResponseBean extendContentList(@RequestParam(value ="pageNum",defaultValue = "1") Integer pageNum,
                                          @RequestParam(value ="pageSize",defaultValue = "10") Integer pageSize,
                                          @RequestParam(value = "cityId", required = false) Integer cityId,
                                          @RequestParam(value = "buildingId", required = false) String buildingId,
                                          @RequestParam(value = "contentType", required = false) String contentType,
                                          @RequestParam(value = "showPosition", required = false) String showPosition,
                                          @RequestParam(value = "status", required = false) Integer status,
                                          @RequestParam(value = "showType", required = false) String showType, HttpServletRequest request){
            ResponseBean responseBean = new ResponseBean();
            IPage<ExtendContent> pg = new Page<>(pageNum, pageSize);

        List<TaPersonBuilding> taPersonBuildingList = getTaPersonBuildingListByUserId(request);
        QueryWrapper<ExtendContent> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq(cityId != null, "city_id", cityId);
            queryWrapper.eq(StringUtils.isNotBlank(buildingId), "building_id", buildingId);
            queryWrapper.eq(StringUtils.isNotBlank(showType), "show_type", showType);
            queryWrapper.eq(StringUtils.isNotBlank(contentType), "content_type", contentType);
            queryWrapper.eq(StringUtils.isNotBlank(showPosition), "show_position", showPosition);
            queryWrapper.ne("status",9);
            queryWrapper.eq(status != null, "status", status);
            queryWrapper.eq( "org_id", getOrgId(request));
            queryWrapper.and(taPersonBuildingList.size() > 0, wapper -> wapper.in("building_id",taPersonBuildingList.stream().map(TaPersonBuilding::getBuildingId).collect(Collectors.toList())).or().eq("create_user",getUserId(request)));
            queryWrapper.orderByDesc("order_no");
            queryWrapper.orderByDesc("create_date");
            IPage<ExtendContent> result = iExtendContentService.page(pg, queryWrapper);

            result.getRecords().forEach(e -> {
                QueryWrapper<TdCity> tdCityQueryWrapper = new QueryWrapper<>();
                tdCityQueryWrapper.eq("id", e.getCityId());
                TdCity tdCity = iTdCityService.getOne(tdCityQueryWrapper);
                QueryWrapper<TaBuilding> taBuildingQueryWrapper = new QueryWrapper<>();
                taBuildingQueryWrapper.eq("building_id", e.getBuildingId());
                TaBuilding taBuilding = iTaBuildingService.getOne(taBuildingQueryWrapper);
                e.setCityName(null == tdCity ? "" : tdCity.getName());
                if (taBuilding != null && e.getIsHaveActive()){
                    e.setBuildingName(taBuilding.getBuildingName());
                }
            });
            result.setRecords(result.getRecords());
            responseBean.addSuccess(result);
            return responseBean;
    }

    /**
     * 微信 开屏 / 轮播图
     */
    @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 = String.class, name = "contentType", paramType = "query",value = "内容类型"),
            @ApiImplicitParam(dataTypeClass = String.class, name = "targetId", paramType = "query",value = ""),
            @ApiImplicitParam(dataTypeClass = String.class, name = "contentId", paramType = "query",value = "内容ID"),
            @ApiImplicitParam(dataTypeClass = Integer.class, name = "cityId", paramType = "query",value = "城市ID")
    })
    @RequestMapping(value="/wx/extendContent/{showType}",method= RequestMethod.GET)
    public ResponseBean extendContentListShowType(@PathVariable(value = "showType") String showType,
                                                  @RequestParam(value = "showPosition", required = false) String showPosition,
                                                  @RequestParam(value = "targetId", required = false) String targetId,
                                                  @RequestParam(value = "contentType", required = false) String contentType,
                                                  @RequestParam(value = "buildingId", required = false) String buildingId,
                                                  @RequestParam(value = "contentId", required = false) String contentId,
                                                  @RequestParam(value = "cityId", required = false) Integer cityId,
                                                  HttpServletRequest request){
        ResponseBean responseBean= iExtendContentService.selectExtendContentListShowType(showType, showPosition, targetId,contentType, buildingId, contentId, cityId,getOrgId(request));
        return responseBean;
    }

    /**
     * 针对首屏优化, 获取一些 banner, 开屏等配置
     * @param cityId
     * @param request
     * @return
     */
    @GetMapping("/wx/extendContent")
    public ResponseBean extendContentListOfWX(@RequestParam(value = "cityId") Integer cityId, HttpServletRequest request) {
        return iExtendContentService.selectExtendContentListShowType(null, null, null,null, null, null, cityId,getOrgId(request));
    }


    /**
     * 保存对象
     * @param extendContent 实体对象
     * @return
     */
    @ApiOperation(value = "后台轮播图保存", notes = "后台轮播图保存")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "ExtendContent", name = "extendContent", paramType = "body",value = "轮播图内容")
    })
    @RequestMapping(value="/admin/extendContent",method= RequestMethod.POST)
    public ResponseBean extendContentAdd(@RequestBody ExtendContent extendContent, HttpServletRequest request){
        ResponseBean  responseBean = new ResponseBean();
        //一个城市只能有一个开屏广告
        boolean existFlag = iExtendContentService.advertistExistFlag(extendContent, getOrgId(request));
        if (!existFlag){
            responseBean.addError("该发布位置已有开屏广告，请勿再次上架");
            return responseBean;
        }

        if (extendContent.getCityId() == null){
            Integer cityId = iTaBuildingService.getCityById(extendContent.getBuildingId());
            extendContent.setCityId(cityId);
        }
        extendContent.setCreateDate(LocalDateTime.now());
        extendContent.setOrgId(getOrgId(request));
        if (StringUtils.isEmpty(extendContent.getContentType())){
            extendContent.setContentType("nothing");
        }
        extendContent.setCreateUser(getUserId(request));
        responseBean = iExtendContentService.extendContentAdd(extendContent);
        responseBean.addSuccess(extendContent);
        return responseBean;
    }

    /**
     * 根据id删除对象
     * @param id  实体ID
     */
    @ApiOperation(value = "后台轮播图删除", notes = "后台轮播图删除")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "id", paramType = "payh",value = "轮播图id")
    })
    @ResponseBody
    @RequestMapping(value="/admin/extendContent/{id}", method= RequestMethod.DELETE)
    public ResponseBean extendContentDelete(@PathVariable Integer id){
        ResponseBean responseBean = new ResponseBean();
        try {
            if(iExtendContentService.removeById(id)){
                responseBean.addSuccess("success");
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("extendContentDelete -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 修改对象
     * @param id  实体ID
     * @param extendContent 实体对象
     * @return
     */
    @ApiOperation(value = "后台轮播图保存", notes = "后台轮播图保存")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "id", paramType = "path",value = "轮播图id"),
            @ApiImplicitParam(dataType = "ExtendContent", name = "extendContent", paramType = "body",value = "轮播图内容")
    })
    @RequestMapping(value="/admin/extendContent/{id}",method= RequestMethod.PUT)
    public ResponseBean extendContentUpdate(@PathVariable Integer id,
                                        @RequestBody ExtendContent extendContent,HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        extendContent.setContentId(id);
        try {
            if (extendContent.getCityId() == null){
                Integer cityId = iTaBuildingService.getCityById(extendContent.getBuildingId());
                extendContent.setCityId(cityId);
            }
            extendContent.setOrgId(getOrgId(request));

            if (extendContent.getStatus() == 1){
                boolean publishFlag = iExtendContentService.judgleRelationBuildAndActivity(extendContent);
                if (!publishFlag){
                    responseBean.addError("关联的项目或者活动已取消发布，上架失败");
                    return responseBean;
                }
            }

            //一个城市只能有一个开屏广告
            boolean existFlag = iExtendContentService.advertistExistFlag(extendContent, getOrgId(request));
            if (!existFlag){
                responseBean.addError("该发布位置已有开屏广告，请勿再次上架");
                return responseBean;
            }

            if (StringUtils.isEmpty(extendContent.getContentType())){
                extendContent.setContentType("nothing");
            }

            if (iExtendContentService.updateById(extendContent)){
                responseBean.addSuccess(extendContent);
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("extendContentUpdate -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 删除对象，逻辑删除，修改状态为9
     * @param id  实体ID
     * @return
     */
    @ApiOperation(value = "后台轮播图删除", notes = "后台轮播图删除")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "id", paramType = "path",value = "轮播图id")
    })
    @RequestMapping(value="/admin/extendContentDelete/{id}",method= RequestMethod.PUT)
    public ResponseBean extendContentUpdate(@PathVariable Integer id, HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        ExtendContent extendContent = new ExtendContent();
        extendContent.setContentId(id);
        extendContent.setStatus(9);
        try {
            iExtendContentService.updateById(extendContent);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("extendContentDelete -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 根据id查询对象
     * @param id  实体ID
     */
    @ApiOperation(value = "后台轮播图查询", notes = "后台轮播图查询")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "id", paramType = "payh",value = "轮播图id")
    })
    @RequestMapping(value="/admin/extendContent/{id}",method= RequestMethod.GET)
    public ResponseBean extendContentGet(@PathVariable Integer id){
        ResponseBean responseBean = new ResponseBean();
        try {
            ExtendContent extendContent = iExtendContentService.getById(id);
            TaBuildingDynamic taBuildingDynamic = iTaBuildingDynamicService.getById(extendContent.getTargetId());
            TaBuilding building = iTaBuildingService.getById(extendContent.getBuildingId());
            if (building != null){
                extendContent.setBuildingStatus(building.getStatus());
            }
            if (null != taBuildingDynamic) {
                extendContent.setTargetName(taBuildingDynamic.getTitle());
            }
            responseBean.addSuccess(extendContent);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("extendContentDelete -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }
}
