package com.huiju.estateagents.redpack.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.fastjson.JSON;
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.bo.request.SaveCzOrderRequestBO;
import com.huiju.estateagents.bo.request.SaveRefundOrderRequestBO;
import com.huiju.estateagents.entity.TaPerson;
import com.huiju.estateagents.excel.handler.CustomCellWriteHandler;
import com.huiju.estateagents.redpack.entity.ConsumeOrder;
import com.huiju.estateagents.redpack.entity.RechargeOrder;
import com.huiju.estateagents.redpack.entity.RefundOrder;
import com.huiju.estateagents.redpack.entity.TaOrgOrder;
import com.huiju.estateagents.redpack.service.ITaOrgOrderService;
import com.huiju.estateagents.service.ITaPersonService;
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.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <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 = "miniAppName", required = false) String miniAppName,
                                       @RequestParam(value = "itemType", required = false) String itemType,
                                       @RequestParam(value = "startDate", required = false) String startDate,
                                       @RequestParam(value = "endDate", required = false) String endDate,
                                       @RequestParam(value = "payStartDate", required = false) String payStartDate,
                                       @RequestParam(value = "payEndDate", required = false) String payEndDate,
                                       @RequestParam(value = "auditStatus", required = false) String auditStatus) {
        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, miniAppName, auditStatus, payStartDate, payEndDate);
            responseBean.addSuccess(result);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("taOrgOrderList -=- {}", e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 充值订单导出
     *
     * @return
     */
    @RequestMapping(value = "/channel/taOrgOrder/rechargeOrderExport")
    public void rechargeOrderExport(@RequestParam(value = "tradeNo", required = false) String tradeNo,
                                                   @RequestParam(value = "isOffline", required = false) Boolean isOffline,
                                                   @RequestParam(value = "tradingStatus", required = false) String tradingStatus,
                                                   @RequestParam(value = "miniAppName", required = false) String miniAppName,
                                                   @RequestParam(value = "startDate", required = false) String startDate,
                                                   @RequestParam(value = "endDate", required = false) String endDate,
                                                   @RequestParam(value = "orderType", required = false) String orderType,
                                                   @RequestParam(value = "orgId", required = false) Integer orgId,
                                                   HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=订单统计.xlsx");

        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream(), RechargeOrder.class).registerWriteHandler(new CustomCellWriteHandler()).build();
        WriteSheet writeSheet = EasyExcel.writerSheet("活动统计").build();

        // 设置 sheet, 同一个sheet只需要设置一次
        List<RechargeOrder> data = iTaOrgOrderService.rechargeListByConditionExport(orderType, tradeNo, isOffline, tradingStatus, startDate, endDate, miniAppName, orgId);
        excelWriter.write(data, writeSheet);
        // finish 会帮忙关闭流
        excelWriter.finish();
    }

    /**
     * 消费订单导出
     *
     * @return
     */
    @RequestMapping(value = "/channel/taOrgOrder/consumeOrderExport")
    public void consumeOrderExport(@RequestParam(value = "tradeNo", required = false) String tradeNo,
                                   @RequestParam(value = "tradingStatus", required = false) String tradingStatus,
                                   @RequestParam(value = "receivePhone", required = false) String receivePhone,
                                   @RequestParam(value = "miniAppName", required = false) String miniAppName,
                                   @RequestParam(value = "startDate", required = false) String startDate,
                                   @RequestParam(value = "endDate", required = false) String endDate,
                                   @RequestParam(value = "orderType", required = false) String orderType,
                                   @RequestParam(value = "orgId", required = false) Integer orgId,
                                   HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=订单统计.xlsx");

        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream(), ConsumeOrder.class).registerWriteHandler(new CustomCellWriteHandler()).build();
        WriteSheet writeSheet = EasyExcel.writerSheet("活动统计").build();

        // 设置 sheet, 同一个sheet只需要设置一次
        List<ConsumeOrder> data = iTaOrgOrderService.consumeListByConditionExport(orderType, tradeNo, receivePhone, tradingStatus, startDate, endDate, miniAppName, orgId);
        excelWriter.write(data, writeSheet);
        // finish 会帮忙关闭流
        excelWriter.finish();
    }

    /**
     * 退款订单导出
     *
     * @return
     */
    @RequestMapping(value = "/channel/taOrgOrder/refundOrderExport")
    public void refundOrderExport(@RequestParam(value = "tradeNo", required = false) String tradeNo,
                                   @RequestParam(value = "miniAppName", required = false) String miniAppName,
                                   @RequestParam(value = "startDate", required = false) String startDate,
                                   @RequestParam(value = "endDate", required = false) String endDate,
                                   @RequestParam(value = "orderType", required = false) String orderType,
                                   @RequestParam(value = "orgId", required = false) Integer orgId,
                                   @RequestParam(value = "auditStatus", required = false) String auditStatus,
                                   HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=订单统计.xlsx");

        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream(), RefundOrder.class).registerWriteHandler(new CustomCellWriteHandler()).build();
        WriteSheet writeSheet = EasyExcel.writerSheet("活动统计").build();

        // 设置 sheet, 同一个sheet只需要设置一次
        List<RefundOrder> data = iTaOrgOrderService.refundListByConditionExport(orderType, tradeNo, startDate, endDate, miniAppName, orgId, auditStatus);
        excelWriter.write(data, writeSheet);
        // finish 会帮忙关闭流
        excelWriter.finish();
    }

    /**
     * 保存对象
     *
     * @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;
    }

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

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

    /**
     * 创建退款订单
     *
     * @param requestBO
     * @param request
     * @return
     */
    @RequestMapping(value = "/admin/orgOrder/refund/saveOrder", method = RequestMethod.PUT)
    public ResponseBean saveRefundOrder(@RequestBody SaveRefundOrderRequestBO requestBO, HttpServletRequest request) {
        ResponseBean responseBean = new ResponseBean();
        try {
            responseBean = iTaOrgOrderService.saveRefundOrder(requestBO.getAmount(), 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) LocalDateTime payStartTime,
                                               @RequestParam(value = "payEndTime", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime 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) LocalDateTime payStartTime,
                                         @RequestParam(value = "payEndTime", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime 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) LocalDateTime refundStartTime,
                                                   @RequestParam(value = "refundEndTime", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime refundEndTime,
                                                   String orderId,
                                                   String wxOrderId,
                                                   String tradeNo,
                                                   String auditStatus,
                                                   HttpServletRequest request) {
        ResponseBean responseBean = new ResponseBean();
        try {
            responseBean = iTaOrgOrderService.listRefundOrderByCondition(pageNum, pageSize, refundStartTime, refundEndTime, orderId, auditStatus, wxOrderId, tradeNo, 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) LocalDateTime refundStartTime,
                                             @RequestParam(value = "refundEndTime", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime refundEndTime,
                                             String orderId,
                                             String wxOrderId,
                                             String tradeNo,
                                             String auditStatus,
                                             HttpServletRequest request,
                                             HttpServletResponse response) throws Exception {
        try {
            iTaOrgOrderService.exportRefundOrderByCondition(refundStartTime, refundEndTime, orderId, auditStatus, wxOrderId, tradeNo, 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 tradingStatus success:成功；fail:失败
     * @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) LocalDateTime startTime,
                                                    @RequestParam(value = "endTime", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime endTime,
                                                    String orderId,
                                                    String wxOrderId,
                                                    String tradeNo,
                                                    String tradingStatus,
                                                    String consumeType,
                                                    String phone,
                                                    HttpServletRequest request) {
        ResponseBean responseBean = new ResponseBean();
        try {
            responseBean = iTaOrgOrderService.listConsumeOrderByCondition(pageNum, pageSize, startTime, endTime, orderId, tradingStatus, consumeType, phone, wxOrderId, tradeNo, getOrgId(request));
        } catch (Exception e) {
            logger.error("listConsumeOrderByCondition -=- {}", e);
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }


    /**
     * 导出消费订单列表
     *
     * @param startTime
     * @param endTime
     * @param orderId
     * @param tradingStatus success:成功；fail:失败
     * @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) LocalDateTime startTime,
                                              @RequestParam(value = "endTime", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime endTime,
                                              String orderId,
                                              String wxOrderId,
                                              String tradeNo,
                                              String tradingStatus,
                                              String consumeType,
                                              String phone,
                                              HttpServletRequest request,
                                              HttpServletResponse response) throws Exception {
        try {
            iTaOrgOrderService.exportConsumeOrderByCondition(startTime, endTime, orderId, tradingStatus, consumeType, phone, wxOrderId, tradeNo, 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));
        }
    }

    /**
     * 根据订单号查询订单状态
     *
     * @param orderId
     * @return
     */
    @RequestMapping(value = "/admin/orgOrder/getByInfo", method = RequestMethod.GET)
    public ResponseBean getOrgOrderInfo(String orderId) {
        ResponseBean responseBean = new ResponseBean();
        try {
            TaOrgOrder result = iTaOrgOrderService.getById(orderId);
            if (result == null) {
                responseBean.addError("fail");
                return responseBean;
            }
            responseBean.addSuccess(result);
        } catch (Exception e) {
            logger.error("getOrgOrderInfo 异常：", e);
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }
}
