package com.huiju.estateagents.redpack.controller;

import com.alibaba.fastjson.JSON;
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.drainage.entity.TaDrainage;
import com.huiju.estateagents.drainage.mapper.TaDrainageMapper;
import com.huiju.estateagents.redpack.entity.TaRedPacket;
import com.huiju.estateagents.redpack.service.ITaOrgOrderService;
import com.huiju.estateagents.redpack.service.ITaRedPacketPersonService;
import com.huiju.estateagents.redpack.service.ITaRedPacketService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 红包助力活动  前端控制器
 * </p>
 *
 * @author fxf
 * @since 2020-06-03
 */
@RestController
@RequestMapping("/api")
public class TaRedPacketController extends BaseController {

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

    @Autowired
    public ITaRedPacketService iTaRedPacketService;

    @Autowired
    private ITaOrgOrderService iTaOrgOrderService;

    @Autowired
    private ITaRedPacketPersonService iTaRedPacketPersonService;

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

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

    /**
     * 保存对象
     *
     * @param taRedPacket 实体对象
     * @return
     */
    @RequestMapping(value = "/admin/redPacket/save", method = RequestMethod.POST)
    public ResponseBean taRedPacketAdd(@RequestBody TaRedPacket taRedPacket) {
        ResponseBean responseBean = new ResponseBean();
        try {
            if (iTaRedPacketService.save(taRedPacket)) {
                responseBean.addSuccess("success");
            } else {
                responseBean.addError("fail");
            }
        } catch (Exception e) {
            logger.error("taRedPacketAdd -=- {}", e);
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

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

    /**
     * 修改对象
     *
     * @param taRedPacket 实体对象
     * @return
     */
    @RequestMapping(value = "/admin/redPacket/update", method = RequestMethod.PUT)
    public ResponseBean taRedPacketUpdate(@RequestBody TaRedPacket taRedPacket,HttpServletRequest request) {
        ResponseBean responseBean = new ResponseBean();
        try {
            responseBean = iTaRedPacketService.updateRedPacket(taRedPacket,getOrgId(request));
        } catch (Exception e) {
            logger.error("taRedPacketUpdate -=- {}", e);
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 根据id查询对象
     *
     * @param id 实体ID
     */
    @RequestMapping(value = "/admin/redPacket/{id}", method = RequestMethod.GET)
    public ResponseBean taRedPacketGet(@PathVariable String id) {
        ResponseBean responseBean = new ResponseBean();
        try {
            TaRedPacket record = iTaRedPacketService.getById(id);
            if (record != null) {
                record = iTaRedPacketService.getRedPacketImages(record);
                responseBean.addSuccess(record);
            } else {
                responseBean.addError("fail");
            }
        } catch (Exception e) {
            logger.error("taRedPacketDelete -=- {}", e);
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 条件查询红包发送记录
     *
     * @param pageNum
     * @param pageSize
     * @param orderId
     * @param wxOrderId
     * @param tradeNo
     * @param phone
     * @param tradingStatus
     * @param request
     * @return
     */
    @RequestMapping(value = "/admin/redPacket/listSendRecord", method = RequestMethod.GET)
    public ResponseBean listSendRecord(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                       @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                       String activityId,
                                       String orderId,
                                       String wxOrderId,
                                       String tradeNo,
                                       String phone,
                                       String tradingStatus,
                                       HttpServletRequest request) {
        ResponseBean responseBean = new ResponseBean();
        try {
            responseBean = iTaOrgOrderService.listRedPacketRecords(pageNum, pageSize, phone, activityId, orderId, wxOrderId, tradeNo, tradingStatus, getOrgId(request));
        } catch (Exception e) {
            logger.error("listSendRecord -=- {}", e);
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 获取红包排行榜
     *
     * @param pageNum
     * @param pageSize
     * @param activityId
     * @param phone
     * @param request
     * @return
     */
    @RequestMapping(value = "/admin/redPacket/getRedPacketRankingList", method = RequestMethod.GET)
    public ResponseBean getRedPacketRankingList(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                                @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                                String activityId,
                                                String phone,
                                                HttpServletRequest request) {
        ResponseBean responseBean = new ResponseBean();
        try {
            responseBean = iTaRedPacketPersonService.getRedPacketRankingList(pageNum, pageSize, activityId, phone, getOrgId(request));
        } catch (Exception e) {
            logger.error("getRedPacketRankingList -=- {}", e);
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 导出红包排行榜
     *
     * @param activityId
     * @param phone
     * @param request
     * @param response
     */
    @RequestMapping(value = "/admin/redPacket/exportRedPacketRankingList", method = RequestMethod.GET)
    public void exportRedPacketRankingList(String activityId,
                                           String phone,
                                           HttpServletRequest request,
                                           HttpServletResponse response) throws Exception {
        try {
            iTaRedPacketPersonService.exportRedPacketRankingList(activityId, phone, getOrgId(request), response);
        } catch (Exception e) {
            logger.error("exportRefundOrderByCondition 异常：", e);
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, Object> map = new HashMap();
            map.put("code", ResponseBean.ERROR_UNAVAILABLE);
            map.put("message", "下载文件失败" + e.getMessage());
            response.getWriter().println(JSON.toJSONString(map));
        }
    }

    /**
     * 查询客户访问数据
     *
     * @param pageNum
     * @param pageSize
     * @param startTime
     * @param endTime
     * @param drainageId
     * @param phone
     * @param sharePersonPhone 分享人手机号
     * @param request
     * @return
     */
    @RequestMapping(value = "/admin/redPacket/listVisitRecordByCondition", method = RequestMethod.GET)
    public ResponseBean listVisitRecordByCondition(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                                   @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                                   @RequestParam(value = "startTime", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime startTime,
                                                   @RequestParam(value = "endTime", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime endTime,
                                                   String drainageId,
                                                   String phone,
                                                   String sharePersonPhone,
                                                   HttpServletRequest request) {
        ResponseBean responseBean = new ResponseBean();
        try {
            responseBean = iTaRedPacketService.listVisitRecordByCondition(pageNum, pageSize, startTime, endTime, drainageId, phone, sharePersonPhone, getOrgId(request));
        } catch (Exception e) {
            logger.error("listVisitRecordByCondition -=- {}", e);
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 导出客户访问数据
     *
     * @param startTime
     * @param endTime
     * @param drainageId
     * @param phone
     * @param sharePersonPhone
     * @param request
     * @return
     */
    @RequestMapping(value = "/admin/redPacket/exportVisitRecordByCondition", method = RequestMethod.GET)
    public void exportVisitRecordByCondition(@RequestParam(value = "startTime", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime startTime,
                                             @RequestParam(value = "endTime", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime endTime,
                                             String drainageId,
                                             String phone,
                                             String sharePersonPhone,
                                             HttpServletRequest request,
                                             HttpServletResponse response) throws Exception {
        try {
            iTaRedPacketService.exportVisitRecordByCondition(startTime, endTime, drainageId, phone, sharePersonPhone, getOrgId(request), response);
        } catch (Exception e) {
            logger.error("exportVisitRecordByCondition 异常：", e);
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, Object> map = new HashMap();
            map.put("code", ResponseBean.ERROR_UNAVAILABLE);
            map.put("message", "下载文件失败" + e.getMessage());
            response.getWriter().println(JSON.toJSONString(map));
        }
    }

}
