package com.web.controller.business;

import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hai.common.exception.ErrorCode;
import com.hai.common.exception.ErrorHelp;
import com.hai.common.exception.SysCode;
import com.hai.common.security.UserCenter;
import com.hai.common.utils.ResponseMsgUtil;
import com.hai.entity.HighChildOrder;
import com.hai.entity.HighCoupon;
import com.hai.entity.HighGasOrder;
import com.hai.entity.HighOrder;
import com.hai.enum_type.GoodsType;
import com.hai.enum_type.OrderStatusEnum;
import com.hai.enum_type.UserObjectTypeEnum;
import com.hai.enum_type.UserRoleTypeEnum;
import com.hai.model.ResponseData;
import com.hai.model.UserInfoModel;
import com.hai.order.model.ExportGasOrderModel;
import com.hai.order.model.OrderCouponModel;
import com.hai.order.service.OrderService;
import com.hai.order.service.OrderServiceExt;
import com.hai.order.type.OrderOilStatus;
import com.hai.order.type.OrderProductType;
import com.hai.service.HighCouponCodeService;
import com.hai.service.HighCouponService;
import com.hai.service.HighGasOrderService;
import com.web.config.SysConst;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
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 javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.net.SocketTimeoutException;
import java.util.*;
import java.util.stream.Collectors;

@Controller
@RequestMapping(value = "coupon")
@Api(value = "卡券订单业务")
public class OrderCouponController {

    private static Logger log = LoggerFactory.getLogger(OrderCouponController.class);

    @Resource
    private UserCenter userCenter;

    @Resource
    private OrderService orderService;

    @Resource
    private HighCouponService couponService;

    @Resource
    private OrderServiceExt orderServiceExt;

    @Resource
    private HighCouponCodeService couponCodeService;

    @RequestMapping(value = "/getOrderList", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询卡券订单列表")
    public ResponseData getOrderList(@RequestParam(name = "companyId", required = false) Long companyId,
                                     @RequestParam(name = "orderNo", required = false) String orderNo,
                                     @RequestParam(name = "memPhone", required = false) String memPhone,
                                     @RequestParam(name = "couponKey", required = false) String couponKey,
                                     @RequestParam(name = "couponName", required = false) String couponName,
                                     @RequestParam(name = "couponSource", required = false) String couponSource,
                                     @RequestParam(name = "payType", required = false) Integer payType,
                                     @RequestParam(name = "orderStatus", required = false) Integer orderStatus,
                                     @RequestParam(name = "createTimeS", required = false) Long createTimeS,
                                     @RequestParam(name = "createTimeE", required = false) Long createTimeE,
                                     @RequestParam(name = "payTimeS", required = false) Long payTimeS,
                                     @RequestParam(name = "payTimeE", required = false) Long payTimeE,
                                     @RequestParam(name = "finishTimeS", required = false) Long finishTimeS,
                                     @RequestParam(name = "finishTimeE", required = false) Long finishTimeE,
                                     @RequestParam(name = "exceptionStatus", required = false) Boolean exceptionStatus,
                                     @RequestParam(name = "pageNum", required = true) Integer pageNum,
                                     @RequestParam(name = "pageSize", required = true) Integer pageSize,
                                     HttpServletRequest request) {
        try {

            UserInfoModel userInfoModel = userCenter.getSessionModel(UserInfoModel.class);
            if (userInfoModel == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMPETENCE_INSUFFICIENT, "");
            }

            Map<String,Object> map = new HashMap<>();
            if (userInfoModel.getSecUser().getObjectType().equals(UserObjectTypeEnum.type0.getType())) {
                map.put("companyId", companyId);

            } else if (userInfoModel.getSecUser().getObjectType().equals(UserObjectTypeEnum.type1.getType())) {
                map.put("companyId", userInfoModel.getBsCompany().getId());

            } else {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMPETENCE_INSUFFICIENT, "");
            }

            map.put("orderNo", orderNo);
            map.put("memPhone", memPhone);
            map.put("couponKey", couponKey);
            map.put("couponName", couponName);
            map.put("couponSource", couponSource);
            map.put("payType", payType);
            map.put("orderStatus", orderStatus);
            map.put("createTimeS", createTimeS);
            map.put("createTimeE", createTimeE);
            map.put("payTimeS", payTimeS);
            map.put("payTimeE", payTimeE);
            map.put("finishTimeS", finishTimeS);
            map.put("finishTimeE", finishTimeE);
            map.put("exceptionStatus", exceptionStatus);

            PageHelper.startPage(pageNum,pageSize);
            return ResponseMsgUtil.success(new PageInfo<>(orderServiceExt.getOrderCouponList(map)));

        } catch (Exception e) {
            log.error("OrderCouponController --> getOrderList() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }


    @RequestMapping(value = "/exportOrderCouponExcel", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "导出卡券订单")
    public ResponseData exportOrderCouponExcel(@RequestParam(name = "companyId", required = false) Long companyId,
                                               @RequestParam(name = "orderNo", required = false) String orderNo,
                                               @RequestParam(name = "memPhone", required = false) String memPhone,
                                               @RequestParam(name = "couponKey", required = false) String couponKey,
                                               @RequestParam(name = "couponName", required = false) String couponName,
                                               @RequestParam(name = "couponSource", required = false) String couponSource,
                                               @RequestParam(name = "payType", required = false) Integer payType,
                                               @RequestParam(name = "orderStatus", required = false) Integer orderStatus,
                                               @RequestParam(name = "createTimeS", required = false) Long createTimeS,
                                               @RequestParam(name = "createTimeE", required = false) Long createTimeE,
                                               @RequestParam(name = "payTimeS", required = false) Long payTimeS,
                                               @RequestParam(name = "payTimeE", required = false) Long payTimeE,
                                               @RequestParam(name = "finishTimeS", required = false) Long finishTimeS,
                                               @RequestParam(name = "finishTimeE", required = false) Long finishTimeE,
                                               @RequestParam(name = "exceptionStatus", required = false) Integer exceptionStatus,
                                               HttpServletRequest request) {
        try {

            UserInfoModel userInfoModel = userCenter.getSessionModel(UserInfoModel.class);
            if (userInfoModel == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMPETENCE_INSUFFICIENT, "");
            }
            Map<String,Object> map = new HashMap<>();
            if (userInfoModel.getSecUser().getObjectType().equals(UserObjectTypeEnum.type0.getType())) {
                map.put("companyId", companyId);

            } else if (userInfoModel.getSecUser().getObjectType().equals(UserObjectTypeEnum.type1.getType())) {
                map.put("companyId", userInfoModel.getBsCompany().getId());

            } else {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMPETENCE_INSUFFICIENT, "");
            }

            map.put("orderNo", orderNo);
            map.put("memPhone", memPhone);
            map.put("couponKey", couponKey);
            map.put("couponName", couponName);
            map.put("couponSource", couponSource);
            map.put("payType", payType);
            map.put("orderStatus", orderStatus);
            map.put("createTimeS", createTimeS);
            map.put("createTimeE", createTimeE);
            map.put("payTimeS", payTimeS);
            map.put("payTimeE", payTimeE);
            map.put("finishTimeS", finishTimeS);
            map.put("finishTimeE", finishTimeE);
            map.put("exceptionStatus", exceptionStatus);

            List<OrderCouponModel> list = orderServiceExt.getOrderCouponList(map);

            Set<String> includeColumnFiledNames = new HashSet<String>();
            for (Field field : OrderCouponModel.class.getDeclaredFields()) {
                includeColumnFiledNames.add(field.getName());
            }
            if (!userInfoModel.getSecUser().getObjectType().equals(UserObjectTypeEnum.type0.getType())) {
                includeColumnFiledNames.remove("companyName");
            }

            String fileName = "/temporary/" + System.currentTimeMillis() + ".xlsx";
            EasyExcel.write(SysConst.getSysConfig().getFileUrl() + fileName, OrderCouponModel.class)
                    .includeColumnFiledNames(includeColumnFiledNames)
                    .sheet("卡券订单")
                    .doWrite(list);

            return ResponseMsgUtil.success(fileName);

        } catch (Exception e) {
            log.error("HighOrderController --> getUserOrderList() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/getOrderDetail",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询卡券订单详情")
    public ResponseData getOrderDetail(@RequestParam(name = "orderNo", required = false) String orderNo) {
        try {

            Map<String, Object> param = new HashMap<>();
            param.put("tradeOrder", orderService.getOrderDetailByNo(orderNo));

            return ResponseMsgUtil.success(param);

        } catch (Exception e) {
            log.error("OrderCouponController -> getOrderDetail() error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }


    @RequestMapping(value="/reissue",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "补发")
    public ResponseData reissue(@RequestParam(name = "orderNo", required = true) String orderNo) {
        try {
            // 订单
            HighOrder order = orderService.getOrderDetailByNo(orderNo);
            if (order == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的交易");
            }
            if (!order.getProductType().equals(OrderProductType.PRODUCT_TYPE5.getNumber())) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "只支持卡券交易补发");
            }
            if (order.getOrderStatus().equals(OrderStatusEnum.type2.getType())) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "补发失败！交易未处于已支付状态");
            }
            if (!order.getExceptionStatus().equals(true)) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "补发失败！订单未出现异常");
            }
            // 过滤出卡券订单
            List<HighChildOrder> childOrderList = order.getHighChildOrderList().stream()
                                                    .filter(o ->
                                                            o.getGoodsType().equals(GoodsType.goodsType1.getType())
                                                            && o.getGiveawayType().equals(false)
                                                    ).collect(Collectors.toList());
            if (childOrderList.size() == 0) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知找到子交易订单");
            }
            HighChildOrder childOrder = childOrderList.get(0);

            // 补发
            couponCodeService.reissueCoupon(order,childOrder,couponService.getCouponById(childOrder.getGoodsId()));

            return ResponseMsgUtil.success("补发成功");

        } catch (Exception e) {
            log.error("OrderCouponController -> reissue() error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }

}
