package com.huiju.estateagents.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
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.entity.TaBuilding;
import com.huiju.estateagents.entity.TaPoster;
import com.huiju.estateagents.service.ITaBuildingService;
import com.huiju.estateagents.service.TaPosterService;
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.time.LocalDateTime;

/**
 * <p>
 * 分享海报表  前端控制器
 * </p>
 *
 * @author jobob
 * @since 2019-09-21
 */
@RestController
@RequestMapping("/api")
public class TaPosterController extends BaseController {

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

    @Autowired
    public TaPosterService iPosterService;

    @Autowired
    private ITaBuildingService iTaBuildingService;


    /**
     * 分页查询列表
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping(value = "/poster", method = RequestMethod.GET)
    public ResponseBean posterList(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                   @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        ResponseBean responseBean = new ResponseBean();
        try {
            //使用分页插件
            IPage<TaPoster> pg = new Page<>(pageNum, pageSize);
            QueryWrapper<TaPoster> queryWrapper = new QueryWrapper<>();
            queryWrapper.orderByDesc("create_date");

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

    /**
     * 保存对象
     *
     * @param poster 实体对象
     * @return
     */
    @RequestMapping(value = "/admin/poster", method = RequestMethod.POST)
    public ResponseBean posterAdd(@RequestBody TaPoster poster, HttpServletRequest request) {
        ResponseBean responseBean = new ResponseBean();
        try {
            poster.setStatus(CommConstant.STATUS_NORMAL);
            poster.setOrgId(getOrgId(request));
            poster.setCreateDate(LocalDateTime.now());
            if (iPosterService.save(poster)) {

                // 为了兼容 小程序3.0 -> v3.4的后端
                updateBuildingPoster(poster);
                responseBean.addSuccess(poster);
            } else {
                responseBean.addError("fail");
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("posterAdd -=- {}", e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 项目添加海报的时候，往项目的 poster 字段插入一张图片
     * 为了兼容 小程序3.0 -> v3.4的后端
     * @param poster
     */
    private void updateBuildingPoster(TaPoster poster) {
        // 项目添加海报的时候，往项目的 poster 字段插入一张图片
        // 为了兼容 小程序3.0 -> v3.4的后端
        if ("building".equals(poster.getTargetType())) {
            UpdateWrapper<TaBuilding> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("building_id", poster.getTargetId());
            updateWrapper.set("poster", poster.getPosterImg());
            iTaBuildingService.update(updateWrapper);
        }
    }

    /**
     * 根据id删除对象
     *
     * @param id 实体ID
     */
    @ResponseBody
    @RequestMapping(value = "/poster/{id}", method = RequestMethod.DELETE)
    public ResponseBean posterDelete(@PathVariable Integer id) {
        ResponseBean responseBean = new ResponseBean();
        try {
            if (iPosterService.removeById(id)) {
                responseBean.addSuccess("success");
            } else {
                responseBean.addError("fail");
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("posterDelete -=- {}", e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 修改对象
     *
     * @param id     实体ID
     * @param poster 实体对象
     * @return
     */
    @RequestMapping(value = "/admin/poster/{id}", method = RequestMethod.PUT)
    public ResponseBean posterUpdate(@PathVariable Integer id,
                                     @RequestBody TaPoster poster) {
        ResponseBean responseBean = new ResponseBean();
        poster.setPosterId(id);
        try {
            if (iPosterService.updateById(poster)) {

                // 为了兼容 小程序3.0 -> v3.4的后端
                updateBuildingPoster(poster);
                responseBean.addSuccess(poster);
            } else {
                responseBean.addError("fail");
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("posterUpdate -=- {}", e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 查询对象
     */
    @RequestMapping(value = "/admin/poster", method = RequestMethod.GET)
    public ResponseBean posterGet(@RequestParam String targetId,@RequestParam String targetType ) {
        ResponseBean responseBean = new ResponseBean();
        try {
            responseBean.addSuccess(iPosterService.getPostersForTarget(targetId,targetType));
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("posterDelete -=- {}", e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }
    
    /**
     * 查询对象
     */
    @RequestMapping(value = "/admin/used/poster", method = RequestMethod.GET)
    public ResponseBean posterUsed(@RequestParam String targetId,@RequestParam String targetType ) {
        ResponseBean responseBean = new ResponseBean();
        try {
            responseBean.addSuccess(iPosterService.getUsedPostersForTarget(targetId,targetType));
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("posterDelete -=- {}", e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }
}
