package com.iformall.controller.market;

import com.github.pagehelper.PageInfo;
import com.iformall.annotation.SystemControllerLog;
import com.iformall.common.ErrorCode;
import com.iformall.common.ResultData;
import com.iformall.controller.base.BaseController;
import com.iformall.domain.po.WxAppinfo;
import com.iformall.domain.vo.WxCouponOrderBVo;
import com.iformall.enums.EnumAppType;
import com.iformall.enums.EnumPayType;
import com.iformall.exception.MallinkException;
import com.iformall.service.WxAppinfoService;
import com.iformall.service.WxCouponOrderService;
import com.iformall.service.WxRefundOrderService;
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.Map;

@RestController
@RequestMapping("wxCouponOrder")
@Api(description = "核销和用户卡券查询接口")
public class WxCouponOrderController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private WxCouponOrderService wxCouponOrderService;

    @Autowired
    private WxRefundOrderService wxRefundOrderService;

    @Autowired
    private WxAppinfoService wxAppinfoService;

    @ApiOperation("分页列表接口")
    @GetMapping("list")
    @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 list(@ModelAttribute WxCouponOrderBVo wxCouponOrder, Integer pageNum, Integer pageSize) {
        logger.debug("[" + getIpAddr() + "] WxCouponOrderController::list");
        if (wxCouponOrder == null) wxCouponOrder = new WxCouponOrderBVo();
        wxCouponOrder.setTenantId(getTenantId());
        if (wxCouponOrder.getMerchantName() != null &&
                wxCouponOrder.getMerchantName().isEmpty()) {
            wxCouponOrder.setMerchantName(null);
        }
        return wxCouponOrderService.listAdminAsPage(wxCouponOrder, pageNum, pageSize);
    }

    @ApiOperation(value = "卡券详情接口")
    @GetMapping("detail")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "couponOrderId", value = "券ID", dataType = "Long", paramType = "query", required = true)
    })
    @SystemControllerLog(description = "券包-卡券详情")
    public ResultData detail(@RequestParam("couponOrderId")  Long couponOrderId) {
        if(couponOrderId == null) {
            return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL);
        }
        return wxCouponOrderService.detailAdminVo(couponOrderId);
    }
    
    @ApiOperation(value = "退券退款", notes = "{\"couponOrderId\":\"string\"}")
    @PostMapping("/refund")
    @SystemControllerLog(description = "券包-退券退款")
    public ResultData create(@RequestBody Map<String, String> paramMap) {
        logger.debug("[" + getIpAddr() + "] WxCouponOrderController::create");
        //Assert.notNull(wxRefundOrder.getName(), "角色名不能为空");
        //Assert.isTrue(!checkUnique(sysRole.getName(), null), "重复的角色名");
        logger.info(paramMap.toString());
        String couponOrderIdStr = paramMap.get("couponOrderId");
        if (StringUtils.isBlank(couponOrderIdStr)) {
            logger.error("couponOrderId不能为空: " + paramMap.toString());
            return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL);
        }
        Long couponOrderId = 0L;
        try {
            couponOrderId = Long.valueOf(couponOrderIdStr);
        } catch (NumberFormatException e) {
            logger.error("couponOrderId参数不正确: " + paramMap.toString());
            return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL);
        }

        WxAppinfo appinfoQ = new WxAppinfo();
        appinfoQ.setTenantId(getTenantId());
        appinfoQ.setType(EnumAppType.B.getCode());
        PageInfo<WxAppinfo> appinfoPageInfo = wxAppinfoService.listAsPage(appinfoQ, 1, 1);
        if (appinfoPageInfo.getList().size() > 0) {
            WxAppinfo appinfo = appinfoPageInfo.getList().get(0);
            if (appinfo != null) {
                try {
                    wxRefundOrderService.createRefundOrder(appinfo, couponOrderId, EnumPayType.PAY_ADMIN_REFUND, null);
                    return new ResultData();
                } 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.REFUND_ORDER_ERROR);
                }
            }
        }
        return new ResultData(ErrorCode.REFUND_ORDER_ERROR.getCode(), "AppInfo获取失败");
    }

    @GetMapping("exportData")
    @SystemControllerLog(description = "券订单数据-导出数据")
    public void exportData(@ModelAttribute WxCouponOrderBVo wxCouponOrder, HttpServletRequest request, HttpServletResponse response) {
        logger.debug("[" + getIpAddr() + "] WxCouponOrderController::exportData");
        if (wxCouponOrder == null) wxCouponOrder = new WxCouponOrderBVo();
        wxCouponOrder.setTenantId(getTenantId());
        if (wxCouponOrder.getMerchantName() != null &&
                wxCouponOrder.getMerchantName().isEmpty()) {
            wxCouponOrder.setMerchantName(null);
        }
        wxCouponOrderService.exportData(wxCouponOrder, request, response);
    }

}
