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.ResponseBean;
import com.huiju.estateagents.common.CommConstant;
import com.huiju.estateagents.entity.TaPolicy;
import com.huiju.estateagents.common.JWTUtils;
import com.huiju.estateagents.entity.TdCity;
import com.huiju.estateagents.service.ITdCityService;
import com.huiju.estateagents.service.ITaPolicyService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
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 com.huiju.estateagents.base.BaseController;

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

/**
 * <p>
    * 购房政策表  前端控制器
    * </p>
 *
 * @author jobob
 * @since 2019-09-04
 */
@RestController
@RequestMapping("/api")
@Api(value = "政策维护", tags = "政策维护")
public class TaPolicyController extends BaseController {

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

    @Autowired
    public ITaPolicyService iTaPolicyService;

    @Autowired
    private ITdCityService iTdCityService;


    /**
     * 分页查询列表
     * @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 = Integer.class, name = "cityId", paramType = "query",value = "城市ID")
    })
    @RequestMapping(value="/admin/taPolicy",method= RequestMethod.GET)
    public ResponseBean taPolicyList(@RequestParam(value ="pageNum",defaultValue = "1") Integer pageNum,
									 @RequestParam(value ="pageSize",defaultValue = "10") Integer pageSize,
                                     @RequestParam(value ="cityId", required = false) Integer cityId,
                                     HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        try {
            //使用分页插件
		    IPage<TaPolicy> pg = new Page<>(pageNum, pageSize);
            QueryWrapper<TaPolicy> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq(null != cityId,"city_id",cityId);
            queryWrapper.orderByDesc("weight", "create_date");
            queryWrapper.eq("status", CommConstant.STATUS_NORMAL);
            queryWrapper.eq("org_id", getOrgId(request));

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

    /**
     * 分页查询列表
     * @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 = Integer.class, name = "cityId", paramType = "query",value = "城市ID")
    })
    @RequestMapping(value="/wx/taPolicy",method= RequestMethod.GET)
    public ResponseBean taPolicyListCity(@RequestParam(value ="pageNumber",defaultValue = "1") Integer pageNumber,
                                     @RequestParam(value ="pageSize",defaultValue = "10") Integer pageSize,
                                         @RequestParam(value ="cityId", required = false) Integer cityId,HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        try {
            //使用分页插件
            IPage<TaPolicy> pg = new Page<>(pageNumber, pageSize);
            QueryWrapper<TaPolicy> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("city_id",cityId);
            queryWrapper.eq("publish_status",CommConstant.IS_PUBLISH);
            queryWrapper.eq("org_id",getOrgId(request));
            queryWrapper.orderByDesc("weight", "create_date");
            queryWrapper.eq("status", CommConstant.STATUS_NORMAL);

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

    /**
     * 保存对象
     * @param taPolicy 实体对象
     * @return
     */
    @ApiOperation(value = "后台政策维护保存", notes = "后台政策维护保存")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "TaPolicy", name = "taPolicy", paramType = "body",value = "政策数据")
    })
    @RequestMapping(value="/admin/taPolicy",method= RequestMethod.POST)
    public ResponseBean taPolicyAdd(@RequestBody TaPolicy taPolicy, HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        try {

            if(taPolicy.getPublishStatus().equals(CommConstant.IS_PUBLISH)){
                taPolicy.setPublishDate(LocalDateTime.now());
                String personId = getPersonId(request);
                taPolicy.setPublishUser(personId);
            }

            TdCity tdCity = iTdCityService.getById(taPolicy.getCityId());
            taPolicy.setCityName(tdCity.getName());

            taPolicy.setStatus(1);
            taPolicy.setCreateDate(LocalDateTime.now());
            taPolicy.setOrgId(getOrgId(request));

            if (iTaPolicyService.save(taPolicy)){
                responseBean.addSuccess(taPolicy);
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            logger.error("taPolicyAdd -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 根据id删除对象
     * @param id  实体ID
     */
    @ApiOperation(value = "后台政策维护删除", notes = "后台政策维护删除")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "id", paramType = "path",value = "政策数据ID")
    })
    @ResponseBody
    @RequestMapping(value="/admin/taPolicy/{id}", method= RequestMethod.DELETE)
    public ResponseBean taPolicyDelete(@PathVariable Integer id){
        ResponseBean responseBean = new ResponseBean();
        try {
            TaPolicy policy=iTaPolicyService.getById(id);
            policy.setStatus(CommConstant.STATUS_DELETE);
            if(iTaPolicyService.updateById(policy)){
                responseBean.addSuccess("success");
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            logger.error("taPolicyDelete -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 修改对象
     * @param id  实体ID
     * @param taPolicy 实体对象
     * @return
     */
    @ApiOperation(value = "后台政策维护修改", notes = "后台政策维护修改")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "id", paramType = "path",value = "政策数据ID"),
            @ApiImplicitParam(dataType = "TaPolicy", name = "taPolicy", paramType = "body",value = "政策数据")
    })
    @RequestMapping(value="/admin/taPolicy/{id}",method= RequestMethod.PUT)
    public ResponseBean taPolicyUpdate(@PathVariable Integer id,
                                        @RequestBody TaPolicy taPolicy,
                                       HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        try {


            if(taPolicy.getPublishStatus().equals(CommConstant.IS_PUBLISH)){
                taPolicy.setPublishDate(LocalDateTime.now());
                String personId = getPersonId(request);
                taPolicy.setPublishUser(personId);
            }

            TdCity tdCity = iTdCityService.getById(taPolicy.getCityId());
            taPolicy.setCityName(tdCity.getName());
            taPolicy.setOrgId(getOrgId(request));

            if (iTaPolicyService.updateById(taPolicy)){
                responseBean.addSuccess(taPolicy);
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            logger.error("taPolicyUpdate -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 根据id查询对象
     * @param id  实体ID
     */
    @ApiOperation(value = "后台政策维护查询", notes = "后台政策维护查询")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "id", paramType = "path",value = "政策数据ID")
    })
    @RequestMapping(value="/admin/taPolicy/{id}",method= RequestMethod.GET)
    public ResponseBean taPolicyGet(@PathVariable Integer id){
        ResponseBean responseBean = new ResponseBean();
        try {
            responseBean.addSuccess(iTaPolicyService.getById(id));
        }catch (Exception e){
            logger.error("taPolicyDelete -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 根据id查询对象
     * @param id  实体ID
     */
    @ApiOperation(value = "微信政策维护查询", notes = "微信政策维护查询")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "id", paramType = "path",value = "政策数据ID")
    })
    @RequestMapping(value="/wx/taPolicy/{id}",method= RequestMethod.GET)
    public ResponseBean taPolicyGetWx(@PathVariable Integer id){
        ResponseBean responseBean = new ResponseBean();
        try {
            TaPolicy policy = iTaPolicyService.getById(id);
            if (null != policy) {
                policy.setPvNum(policy.getPvNum() + 1);
                iTaPolicyService.updateById(policy);
            }
            responseBean.addSuccess(policy);
        }catch (Exception e){
            logger.error("taPolicyDelete -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }
}
