package com.iformall.controller.market;

import com.github.pagehelper.PageInfo;
import com.iformall.annotation.SystemControllerLog;
import com.iformall.common.ErrorCode;
import com.iformall.common.Result;
import com.iformall.common.ResultData;
import com.iformall.controller.base.BaseController;
import com.iformall.domain.dto.OrderSaveDto;
import com.iformall.domain.po.WxCUser;
import com.iformall.domain.po.WxCoupon;
import com.iformall.domain.po.WxCouponChannel;
import com.iformall.domain.po.WxOrder;
import com.iformall.domain.po.base.BaseEntity;
import com.iformall.domain.vo.WxMerchantSubsidyVo;
import com.iformall.domain.vo.WxOrderQueryVo;
import com.iformall.enums.EnumCouponChannelStatus;
import com.iformall.enums.EnumCouponChannelType;
import com.iformall.enums.EnumUserType;
import com.iformall.exception.MallinkException;
import com.iformall.service.WxCUserService;
import com.iformall.service.WxCouponChannelService;
import com.iformall.service.WxCouponService;
import com.iformall.service.WxOrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("wxOrder")
@Api(description = "订单相关接口")
public class WxOrderController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private WxCouponChannelService wxCouponChannelService;

    @Autowired
    private WxOrderService wxOrderService;

    @Autowired
    private WxCUserService wxCUserService;

    @Autowired
    private WxCouponService wxCouponService;

    @ApiOperation("分页列表接口")
    @GetMapping("list")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页数", dataType = "int", paramType = "query", required = true),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", dataType = "int", paramType = "query", required = true),
            @ApiImplicitParam(name = "status", value = "订单状态：-1全部;0-已下单/待付款;1-已支付;2-已取消(限定时间内未付款);3-未退款/待退款;4-已退款;5-退款失败", defaultValue = "0", required = false, dataType = "int")
    })
    @SystemControllerLog(description = "订单管理-列表")
    public ResultData list(@ModelAttribute WxOrder wxOrder, Integer pageNum, Integer pageSize) {
        logger.debug("[" + getIpAddr() + "] WxOrderController::list");
        if (null == wxOrder) {
            wxOrder = new WxOrder();
        }
        wxOrder.setTenantId(getTenantId());
        wxOrder.setSortColumns(BaseEntity.SortField.CreateDate_DESC,BaseEntity.SortField.Id_DESC);
        final PageInfo<WxOrder> page = wxOrderService.listAsPage(wxOrder, pageNum, pageSize);
        return new ResultData(page);
    }

    @ApiOperation("新增接口")
    @PostMapping("add")
    @SystemControllerLog(description = "订单管理-新增")
    public ResultData add(@RequestBody WxOrder wxOrder) {
        logger.debug("[" + getIpAddr() + "] WxOrderController::add");
        //Assert.notNull(wxOrder.getName(), "角色名不能为空");
        //Assert.isTrue(!checkUnique(sysRole.getName(), null), "重复的角色名");
        wxOrderService.saveOrUpdate(wxOrder);
        return new ResultData();
    }

    @ApiOperation("根据id更新接口")
    @PostMapping("update")
    @SystemControllerLog(description = "订单管理-更新")
    public ResultData update(@RequestBody WxOrder wxOrder) {
        logger.debug("[" + getIpAddr() + "] WxOrderController::update");
        wxOrderService.saveOrUpdate(wxOrder);
        return new ResultData();
    }

    @ApiOperation("根据id删除接口")
    @GetMapping("/del")
    @ApiImplicitParam(name = "id", value = "id", dataType = "Long", paramType = "query", required = true)
    @SystemControllerLog(description = "订单管理-删除")
    public ResultData delete(Long id) {
        logger.debug("[" + getIpAddr() + "] WxOrderController::delete");
        wxOrderService.deleteById(id);
        return new ResultData(Result.SUCCESS, "删除成功", null);
    }

    @ApiOperation("根据id查询接口")
    @GetMapping("/findById")
    @ApiImplicitParam(name = "id", value = "id", dataType = "Long", paramType = "query", required = true)
    @SystemControllerLog(description = "订单管理-id查询")
    public ResultData findById(Long id) {
        logger.debug("[" + getIpAddr() + "] WxOrderController::findById");
        return new ResultData(Result.SUCCESS, "查询成功", wxOrderService.getById(id));
    }


    @ApiOperation("交易列表")
    @GetMapping("listOrder")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页数", dataType = "int", paramType = "query", required = true),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", dataType = "int", paramType = "query", required = true)
    })
    @SystemControllerLog(description = "订单管理-交易列表")
    public ResultData listOrder(@ModelAttribute WxOrderQueryVo wxOrderQueryVo, Integer pageNum, Integer pageSize) {
        logger.debug("[" + getIpAddr() + "] WxOrderController::listOrder");
        if (null == wxOrderQueryVo) {
            wxOrderQueryVo = new WxOrderQueryVo();
        }
        wxOrderQueryVo.setTenantId(getTenantId());
        final PageInfo<WxOrder> page = wxOrderService.listOrderAsPage(wxOrderQueryVo, pageNum, pageSize);
        return new ResultData(page);
    }

    @ApiOperation("交易统计")
    @GetMapping("/queryOrderSummary")
    @SystemControllerLog(description = "订单管理-交易统计")
    public ResultData queryOrderSummary() {
        logger.debug("[" + getIpAddr() + "] WxOrderController::queryOrderSummary");

        Map<String, Object> data = wxOrderService.queryOrderSummary(getTenantId());

        return new ResultData(data);
    }

    @ApiOperation(value = "积分兑换订单", notes = "{\"couponChannelId\":\"String\",\"couponId\":\"String\",\"press\":\"String\",\"orderGroupId\":\"String\",\"formId\":\"String\"}")
    @PostMapping("save")
    @SystemControllerLog(description = "订单管理-积分兑换订单")
    public ResultData saveOrder(@RequestBody OrderSaveDto orderSaveDto) {
        logger.info("OrderSave: " + orderSaveDto);
        if (orderSaveDto.getCouponChannelId() == null) {
            return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "couponChannelId不能为空");
        }
        WxCouponChannel wxCouponChannel = wxCouponChannelService.getById(orderSaveDto.getCouponChannelId());
        ResultData resultData = couponChannelCheck(orderSaveDto, wxCouponChannel);
        if (resultData != null) {
            return resultData;
        }

        Long couponId = orderSaveDto.getCouponId() == null ? wxCouponChannel.getCouponId() : orderSaveDto.getCouponId();
        if (couponId == null) {
            logger.error("couponChannelId或者couponId不能为空");
            return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "couponChannelId或者couponId不能为空");
        }

        try {
            WxCUser user = wxCUserService.getById(orderSaveDto.getUserId());
            //用于标记当前操作人为A端用户
            user.setOperatorType(EnumUserType.MALLUSER.getCode());
            user.setOperatorId(getUserId());
            WxOrder order = null;
            WxCoupon coupon = wxCouponService.getById(couponId);
            if (coupon == null) {
                return new ResultData(ErrorCode.COUPON_IS_EMPTY);
            }
            if (!wxOrderService.checkCouponIsFree(coupon)) {
                return new ResultData(ErrorCode.COUPON_IS_NOT_FREE);
            }
            // 免费券
            order = wxOrderService.saveFreeOrderForCoupon(user, coupon, orderSaveDto.getCouponChannelId(), orderSaveDto.getFormId(), null);
            return new ResultData(order);
        } catch (MallinkException e) {
            logger.error(e.getMessage());
            return new ResultData(e.getErrorCode(), e.getMessage());
        } catch (Exception e) {
            logger.error(e.getMessage());
            return new ResultData(ErrorCode.ORDER_IS_FAIL, e.getMessage());
        }
    }

    private ResultData couponChannelCheck(@RequestBody OrderSaveDto orderSaveDto, WxCouponChannel wxCouponChannel) {
        if (wxCouponChannel == null) {
            logger.error("couponChannelId convert error, " + orderSaveDto.getCouponChannelId());
            return new ResultData(ErrorCode.SYS_PARAMETER_CAST_ERROR);
        }

        if (wxCouponChannel.getTargetAd().equals(EnumCouponChannelType.COUPON_CHANNEL_ID_TIMED.getCode())) {
            Date now = new Date();
            if (wxCouponChannel.getBeginTime().getTime() > now.getTime()) {
                logger.error("此券活动未开始:" + orderSaveDto.getCouponChannelId());
                return new ResultData(ErrorCode.COUPON_CHANNEL_IS_NOT_STARTED);
            }
            if (wxCouponChannel.getEndTime().getTime() < now.getTime()) {
                logger.error("此券活动已结束:" + orderSaveDto.getCouponChannelId());
                return new ResultData(ErrorCode.COUPON_CHANNEL_IS_END);
            }
        }

        if (wxCouponChannel.getStatus() == EnumCouponChannelStatus.STATUS_TAKE_OFFF.getCode()) {
            logger.error("此券已下架:" + orderSaveDto.getCouponChannelId());
            return new ResultData(ErrorCode.COUPON_CHANNEL_IS_TAKE_OFF);
        }
        return null;
    }

    @ApiOperation("查看明细")
    @GetMapping("/detail")
    @ApiImplicitParam(name = "id", value = "id", dataType = "Long", paramType = "query", required = true)
    @SystemControllerLog(description = "订单管理-id查询")
    public ResultData detail(Long id) {
        logger.debug("[" + getIpAddr() + "] WxOrderController::detail");
        WxOrder order = new WxOrder();
        order.setId(id);
        order.setTenantId(getTenantId());
        return new ResultData(Result.SUCCESS, "查询成功", wxOrderService.detailCUserVo(order));
    }

    @ApiOperation("交易列表")
    @GetMapping("summary")
    @SystemControllerLog(description = "订单管理-总计")
    public ResultData summary(@ModelAttribute WxOrderQueryVo wxOrderQueryVo) {
        logger.debug("[" + getIpAddr() + "] WxOrderController::summary");
        if (null == wxOrderQueryVo) {
            wxOrderQueryVo = new WxOrderQueryVo();
        }
        wxOrderQueryVo.setTenantId(getTenantId());
        Map<String, Long> data = wxOrderService.summary(wxOrderQueryVo);
        return new ResultData(data);
    }

    @ApiOperation("导出")
    @GetMapping("/exportData")
    @SystemControllerLog(description = "导出")
    public void exportData(@ModelAttribute WxOrderQueryVo wxOrderQueryVo, HttpServletRequest request, HttpServletResponse response) {
        logger.info("[" + getIpAddr() + "] WxOrderController/exportData");
        if (null == wxOrderQueryVo) {
            wxOrderQueryVo = new WxOrderQueryVo();
        }
        wxOrderQueryVo.setTenantId(getTenantId());
        wxOrderService.exportData(wxOrderQueryVo, request, response);
    }


}
