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.entity.TaGoods;
import com.huiju.estateagents.entity.TaPointsExchange;
import com.huiju.estateagents.service.ITaGoodsService;
import com.huiju.estateagents.service.ITaPointsExchangeService;
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;
import java.util.List;

/**
 * <p>
    * 积分兑换记录  前端控制器
    * </p>
 *
 * @author jobob
 * @since 2019-07-25
 */
@RestController
@RequestMapping("/api")
public class TaPointsExchangeController extends BaseController {

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

    @Autowired
    public ITaPointsExchangeService iTaPointsExchangeService;

    @Autowired
    private ITaGoodsService taGoodsService;

    /**
     * 分页查询列表
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping(value="/admin/taPointsExchange",method= RequestMethod.GET)
    public ResponseBean taPointsExchangeList(@RequestParam(value ="pageNum",defaultValue = "1") Integer pageNum,
                                             @RequestParam(value ="pageSize",defaultValue = "10") Integer pageSize,
                                             @RequestParam(value ="personName",required = false) String personName,
                                             @RequestParam(value ="phone",required = false) String phone,
                                             @RequestParam(value ="personType",required = false) String personType,
                                             @RequestParam(value ="targetName",required = false) String targetName,
                                             @RequestParam(value ="startCreateDate",required = false) String startCreateDate,
                                             @RequestParam(value ="endCreateDate",required = false) String endCreateDate,
                                             @RequestParam(value ="startVerifyDate",required = false) String startVerifyDate,
                                             @RequestParam(value ="endVerifyDate",required = false) String endVerifyDate,
                                             @RequestParam(value ="status",required = false) Integer status,
                                             @RequestParam(value ="tel",required = false) String tel, HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        try {
            //使用分页插件
            TaPointsExchange taPointsExchange = new TaPointsExchange();
            taPointsExchange.setPersonName(personName);
            taPointsExchange.setPhone(phone);
            taPointsExchange.setPersonType(personType);
            taPointsExchange.setTargetName(targetName);
            taPointsExchange.setStartCreateDate(startCreateDate);
            taPointsExchange.setEndCreateDate(endCreateDate);
            taPointsExchange.setStartVerifyDate(startVerifyDate);
            taPointsExchange.setEndVerifyDate(endVerifyDate);
            taPointsExchange.setStatus(status);
            taPointsExchange.setTel(tel);
            taPointsExchange.setOrgId(getOrgId(request));
            
            responseBean = iTaPointsExchangeService.selectList(pageNum,pageSize,taPointsExchange,getTaPersonBuildingListByUserId(request));

        }catch (Exception e){
            e.printStackTrace();
            logger.error("taPointsExchangeList -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }
    
    /**
     * 修改对象
     * @param taPointsExchange 实体对象
     * @return
     */
    @RequestMapping(value="/admin/taPointsExchange/change",method= RequestMethod.PUT)
    public ResponseBean taPointsExchangeStatusChange(@RequestBody TaPointsExchange taPointsExchange){
        ResponseBean responseBean = new ResponseBean();
        try {
            if (null != taPointsExchange.getStatus() && !taPointsExchange.getStatus().equals(CommConstant.STATUS_NORMAL)){
                taPointsExchange.setVerifyDate(LocalDateTime.now());
                taPointsExchange.setStatus(CommConstant.STATUS_NORMAL);
            }
            if (iTaPointsExchangeService.updateById(taPointsExchange)){
                responseBean.addSuccess(taPointsExchange);
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taPointsExchangeUpdate -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 保存对象
     * @param taPointsExchange 实体对象
     * @return
     */
    @RequestMapping(value="/taPointsExchange",method= RequestMethod.POST)
    public ResponseBean taPointsExchangeAdd(@RequestBody TaPointsExchange taPointsExchange){
        ResponseBean responseBean = new ResponseBean();
        try {
            if (iTaPointsExchangeService.save(taPointsExchange)){
                responseBean.addSuccess(taPointsExchange);
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taPointsExchangeAdd -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

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

    /**
     * 修改对象
     * @param recId  实体ID
     * @return
     */
    @RequestMapping(value="/admin/taPointsExchange/{recId}",method= RequestMethod.PUT)
    public ResponseBean taPointsExchangeUpdate(@PathVariable Integer recId){
        ResponseBean responseBean = new ResponseBean();
        try {
            TaPointsExchange taPointsExchange = iTaPointsExchangeService.getById(recId);
            if (null == taPointsExchange){
                responseBean.addError("找不到需要核销的商品");
                return responseBean;
            }
            if (taPointsExchange.getStatus().equals(CommConstant.STATUS_NORMAL)){
                responseBean.addError("此商品已经被领取");
                return responseBean;
            }
            taPointsExchange.setStatus(CommConstant.STATUS_NORMAL);
            taPointsExchange.setVerifyDate(LocalDateTime.now());
            if (iTaPointsExchangeService.updateById(taPointsExchange)){
                responseBean.addSuccess(taPointsExchange);
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taPointsExchangeUpdate -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 根据id查询对象
     * @param id  实体ID
     */
    @RequestMapping(value="/taPointsExchange/{id}",method= RequestMethod.GET)
    public ResponseBean taPointsExchangeGet(@PathVariable Integer id){
        ResponseBean responseBean = new ResponseBean();
        try {
            responseBean.addSuccess(iTaPointsExchangeService.getById(id));
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taPointsExchangeDelete -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }
    
    /**
     * 分页查询列表
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping(value="/wx/taPointsExchange",method= RequestMethod.GET)
    public ResponseBean wxPointsExchangeList(@RequestParam(value ="pageNumber",defaultValue = "1") Integer pageNumber,
                                             @RequestParam(value ="pageSize",defaultValue = "10") Integer pageSize,
                                             @RequestParam(value = "buildingId", required = false) String buildingId,
                                             @RequestParam(value = "personId", required = false) String personId){
        ResponseBean responseBean = new ResponseBean();
        try {
            //使用分页插件
            IPage<TaPointsExchange> pg = new Page<>(pageNumber, pageSize);
            QueryWrapper<TaPointsExchange> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq(null != personId, "person_id", personId);
            queryWrapper.eq(null != buildingId, "building_id",buildingId);
            queryWrapper.orderByDesc("create_date");
            
            IPage<TaPointsExchange> result = iTaPointsExchangeService.page(pg, queryWrapper);
            List<TaPointsExchange> records = result.getRecords();
            records.forEach(e -> {
                if (null == e.getStatus() || e.getStatus().equals(CommConstant.STATUS_UNACCALIMED)){
                    TaGoods goods = taGoodsService.getById(e.getTargetId());
                    e.setAddress(goods.getAddress());
                }
            });
            result.setRecords(records);
            responseBean.addSuccess(result);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taPointsExchangeList -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }
}
