package com.huiju.estateagents.redpack.controller;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
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.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.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.entity.TaPerson;
import com.huiju.estateagents.redpack.entity.TaOrgOrder;
import com.huiju.estateagents.redpack.service.ITaOrgOrderService;
import com.huiju.estateagents.service.ITaPersonService;

/**
 * <p>
 * 组织订单表  前端控制器
 * </p>
 *
 * @author fxf
 * @since 2020-06-03
 */
@RestController
@RequestMapping("/api")
public class TaOrgOrderController extends BaseController {

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

    @Autowired
    public ITaOrgOrderService iTaOrgOrderService;

    @Autowired
    public ITaPersonService iTaPersonService;


    /**
     * 分页查询列表
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping(value = "/channel/taOrgOrder", method = RequestMethod.GET)
    public ResponseBean taOrgOrderList(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                       @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                       @RequestParam(value = "orderType", required = false) String orderType,
                                       @RequestParam(value = "orgId", required = false) Integer orgId,
                                       @RequestParam(value = "tradeNo", required = false) String tradeNo,
                                       @RequestParam(value = "isOffline", required = false) Integer isOffline,
                                       @RequestParam(value = "tradingStatus", required = false) String tradingStatus,
                                       @RequestParam(value = "receivePhone", required = false) String receivePhone,
                                       @RequestParam(value = "itemType", required = false) String itemType,
                                       @RequestParam(value = "startDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDate startDate,
                                       @RequestParam(value = "endDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDate endDate) {
        ResponseBean responseBean = new ResponseBean();
        try {
            //使用分页插件
            IPage<TaOrgOrder> pg = new Page<>(pageNum, pageSize);
            IPage<TaOrgOrder> result = iTaOrgOrderService.listByCondition(pg, orderType, orgId, tradeNo, isOffline, tradingStatus, receivePhone, itemType, startDate, endDate);
            responseBean.addSuccess(result);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("taOrgOrderList -=- {}", e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

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

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

    /**
     * 修改对象
     *
     * @param id         实体ID
     * @param taOrgOrder 实体对象
     * @return
     */
    @RequestMapping(value = "/taOrgOrder/{id}", method = RequestMethod.PUT)
    public ResponseBean taOrgOrderUpdate(@PathVariable Integer id,
                                         @RequestBody TaOrgOrder taOrgOrder) {
        ResponseBean responseBean = new ResponseBean();
        try {
            if (iTaOrgOrderService.updateById(taOrgOrder)) {
                responseBean.addSuccess(taOrgOrder);
            } else {
                responseBean.addError("fail");
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("taOrgOrderUpdate -=- {}", e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 根据id查询对象
     *
     * @param id 实体ID
     */
    @RequestMapping(value = "/taOrgOrder/{id}", method = RequestMethod.GET)
    public ResponseBean taOrgOrderGet(@PathVariable Integer id) {
        ResponseBean responseBean = new ResponseBean();
        try {
            responseBean.addSuccess(iTaOrgOrderService.getById(id));
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("taOrgOrderDelete -=- {}", e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 查询接收人信息
     *
     * @param id 实体ID
     */
    @RequestMapping(value = "/channel/receiveInfo/{id}", method = RequestMethod.GET)
    public ResponseBean receiveInfoGet(@PathVariable String id, HttpServletRequest request) {
        ResponseBean responseBean = new ResponseBean();
        try {
            QueryWrapper<TaPerson> taPersonQueryWrapper = new QueryWrapper<>();
            taPersonQueryWrapper.eq("phone", id);
            taPersonQueryWrapper.eq("org_id", getOrgId(request));
            responseBean.addSuccess(iTaPersonService.getOne(taPersonQueryWrapper));
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("receiveInfoGet -=- {}", e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 创建充值订单
     *
     * @param amount
     * @param request
     * @return
     */
    @RequestMapping(value = "/admin/orgOrder/cz/saveOrder", method = RequestMethod.PUT)
    public ResponseBean saveCzOrder(@RequestParam(value = "amount") Double amount, HttpServletRequest request) {
        ResponseBean responseBean = new ResponseBean();
        try {
            responseBean = iTaOrgOrderService.saveCzOrder(amount, getOrgId(request), getUserId(request), request.getRemoteAddr());
        } catch (Exception e) {
            logger.error("saveCzOrder -=- {}", e);
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 创建退款订单
     *
     * @param amount
     * @param request
     * @return
     */
    @RequestMapping(value = "/admin/orgOrder/refund/saveOrder", method = RequestMethod.PUT)
    public ResponseBean saveRefundOrder(@RequestParam(value = "amount") Double amount, HttpServletRequest request) {
        ResponseBean responseBean = new ResponseBean();
        try {
            responseBean = iTaOrgOrderService.saveRefundOrder(amount, getOrgId(request), getUserId(request));
        } catch (Exception e) {
            logger.error("refundOrder -=- {}", e);
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 获取充值订单列表
     *
     * @param pageNum       页码
     * @param pageSize      分页大小
     * @param payStartTime  支付开始时间
     * @param payEndTime    支付结束时间
     * @param orderId       订单编号
     * @param tradeNo       交易号
     * @param wxOrderId     微信订单编号
     * @param isOffline     是否线下订单，true是，false否
     * @param tradingStatus
     * @return
     */
    @RequestMapping(value = "/admin/orgOrder/cz/list", method = RequestMethod.GET)
    public ResponseBean listCzOrderByCondition(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                               @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                               @RequestParam(value = "payStartTime", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDate payStartTime,
                                               @RequestParam(value = "payEndTime", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDate payEndTime,
                                               String orderId,
                                               String tradeNo,
                                               String wxOrderId,
                                               Boolean isOffline,
                                               String tradingStatus,
                                               HttpServletRequest request) {
        ResponseBean responseBean = new ResponseBean();
        try {
            responseBean = iTaOrgOrderService.listCzOrderByCondition(pageNum, pageSize, payStartTime, payEndTime, orderId, tradeNo, wxOrderId, isOffline, tradingStatus, getOrgId(request));
        } catch (Exception e) {
            logger.error("refundOrder -=- {}", e);
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 导出充值订单列表
     *
     * @param payStartTime  支付开始时间
     * @param payEndTime    支付结束时间
     * @param orderId       订单编号
     * @param tradeNo       交易号
     * @param wxOrderId     微信订单编号
     * @param isOffline     是否线下订单，true是，false否
     * @param tradingStatus
     * @return
     */
    @RequestMapping(value = "/admin/orgOrder/cz/exportList", method = RequestMethod.GET)
    public void exportCzOrderByCondition(@RequestParam(value = "payStartTime", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDate payStartTime,
                                         @RequestParam(value = "payEndTime", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDate payEndTime,
                                         String orderId,
                                         String tradeNo,
                                         String wxOrderId,
                                         Boolean isOffline,
                                         String tradingStatus,
                                         HttpServletRequest request,
                                         HttpServletResponse response) throws Exception {
        try {
            iTaOrgOrderService.exportCzOrderByCondition(payStartTime, payEndTime, orderId, tradeNo, wxOrderId, isOffline, tradingStatus, getOrgId(request), response);
        } catch (Exception e) {
            logger.error("exportCzOrderByCondition 异常：", 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 refundStartTime 退款开始时间
     * @param refundEndTime   退款结束时间
     * @param orderId         订单编号
     * @param auditStatus
     * @return
     */
    @RequestMapping(value = "/admin/orgOrder/refund/list", method = RequestMethod.GET)
    public ResponseBean listRefundOrderByCondition(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                                   @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                                   @RequestParam(value = "refundStartTime", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDate refundStartTime,
                                                   @RequestParam(value = "refundEndTime", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDate refundEndTime,
                                                   String orderId,
                                                   String auditStatus,
                                                   HttpServletRequest request) {
        ResponseBean responseBean = new ResponseBean();
        try {
            responseBean = iTaOrgOrderService.listRefundOrderByCondition(pageNum, pageSize, refundStartTime, refundEndTime, orderId, auditStatus, getOrgId(request));
        } catch (Exception e) {
            logger.error("refundOrder -=- {}", e);
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }


    /**
     * 导出退款订单列表
     *
     * @param refundStartTime 退款开始时间
     * @param refundEndTime   退款结束时间
     * @param orderId         订单编号
     * @param auditStatus     checking待审核，agree同意，unAgree 不同意
     * @return
     */
    @RequestMapping(value = "/admin/orgOrder/refund/exportList", method = RequestMethod.GET)
    public void exportRefundOrderByCondition(@RequestParam(value = "refundStartTime", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDate refundStartTime,
                                             @RequestParam(value = "refundEndTime", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDate refundEndTime,
                                             String orderId,
                                             String auditStatus,
                                             HttpServletRequest request,
                                             HttpServletResponse response) throws Exception {
        try {
            iTaOrgOrderService.exportRefundOrderByCondition(refundStartTime, refundEndTime, orderId, auditStatus, 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 orderId     订单编号
     * @param status      消费状态，1：成功，0：失败
     * @param consumeType 消费方式，红包：redPacket
     * @param phone       接收人手机号
     * @param request
     * @return
     */
    @RequestMapping(value = "/admin/orgOrder/listConsumeOrderByCondition", method = RequestMethod.GET)
    public ResponseBean listConsumeOrderByCondition(@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) LocalDate startTime,
                                                    @RequestParam(value = "endTime", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDate endTime,
                                                    String orderId,
                                                    Integer status,
                                                    String consumeType,
                                                    String phone,
                                                    HttpServletRequest request) {
        ResponseBean responseBean = new ResponseBean();
        try {
            responseBean = iTaOrgOrderService.listConsumeOrderByCondition(pageNum, pageSize, startTime, endTime, orderId, status, consumeType, phone, getOrgId(request));
        } catch (Exception e) {
            logger.error("listConsumeOrderByCondition -=- {}", e);
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }


    /**
     * 导出消费订单列表
     *
     * @param startTime
     * @param endTime
     * @param orderId
     * @param status
     * @param consumeType
     * @param phone
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/admin/orgOrder/exportConsumeOrderByCondition", method = RequestMethod.GET)
    public void exportConsumeOrderByCondition(@RequestParam(value = "startTime", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDate startTime,
                                              @RequestParam(value = "endTime", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDate endTime,
                                              String orderId,
                                              Integer status,
                                              String consumeType,
                                              String phone,
                                              HttpServletRequest request,
                                              HttpServletResponse response) throws Exception {
        try {
            iTaOrgOrderService.exportConsumeOrderByCondition(startTime, endTime, orderId, status, consumeType, phone, getOrgId(request), response);
        } catch (Exception e) {
            logger.error("exportConsumeOrderByCondition 异常：", 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));
        }
    }


}
