package com.yonge.cooleshow.teacher.controller;

import cn.hutool.extra.servlet.ServletUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.microsvc.toolkit.common.response.template.R;
import com.microsvc.toolkit.config.jwt.utils.JwtUserInfo;
import com.yonge.cooleshow.auth.api.client.SysUserFeignService;
import com.yonge.cooleshow.auth.api.entity.SysUser;
import com.yonge.cooleshow.biz.dal.dto.req.OrderPayReq;
import com.yonge.cooleshow.biz.dal.dto.req.OrderReq;
import com.yonge.cooleshow.biz.dal.dto.search.OrderSearch;
import com.yonge.cooleshow.biz.dal.entity.UserOrder;
import com.yonge.cooleshow.biz.dal.enums.ClientEnum;
import com.yonge.cooleshow.biz.dal.enums.GoodTypeEnum;
import com.yonge.cooleshow.biz.dal.service.TenantStaffService;
import com.yonge.cooleshow.biz.dal.service.UserOrderService;
import com.yonge.cooleshow.biz.dal.service.UserPaymentCoreService;
import com.yonge.cooleshow.biz.dal.vo.UserOrderVo;
import com.yonge.cooleshow.biz.dal.vo.res.OrderPayRes;
import com.yonge.cooleshow.biz.dal.wrapper.UserPaymentOrderWrapper;
import com.yonge.cooleshow.common.controller.BaseController;
import com.yonge.cooleshow.common.entity.HttpResponseResult;
import com.yonge.cooleshow.common.enums.CacheNameEnum;
import com.yonge.cooleshow.common.enums.EPaymentVersion;
import com.yonge.cooleshow.teacher.vo.UserPaymentOrderVo;
import com.yonge.toolset.base.exception.BizException;
import com.yonge.toolset.base.page.PageInfo;
import com.yonge.toolset.base.util.StringUtil;
import com.yonge.toolset.mybatis.support.PageUtil;
import com.yonge.toolset.payment.base.enums.PaymentClientEnum;
import com.yonge.toolset.payment.util.DistributedLock;
import com.yonge.toolset.utils.date.DateUtil;
import com.yonge.toolset.utils.web.WebUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.TemporalAdjusters;
import java.util.Date;
import java.util.Objects;

/**
 * @Author: liweifan
 * @Data: 2022/3/11 18:16
 */
@RestController
@RequestMapping("${app-config.url.teacher:}/userOrder")
@Api(value = "订单接口", tags = "订单接口")
public class UserOrderController extends BaseController {
    private final static Logger log = LoggerFactory.getLogger(UserOrderController.class);
    @Autowired
    private SysUserFeignService sysUserFeignService;
    @Autowired
    private UserOrderService userOrderService;
    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private TenantStaffService tenantStaffService;

    @Autowired
    private UserPaymentCoreService userPaymentCoreService;

    @ApiOperation(value = "下单接口")
    @PostMapping("/executeOrder")
    public HttpResponseResult<UserOrder> executeOrder(@Valid @RequestBody OrderReq orderReq) {
        SysUser user = sysUserFeignService.queryUserInfo();
        if (user == null || null == user.getId()) {
            return failed(HttpStatus.FORBIDDEN, "请登录");
        }
        orderReq.setUserId(user.getId());
        orderReq.setOrderClient(ClientEnum.TEACHER);
        try {
            HttpResponseResult<UserOrder> res = DistributedLock.of(redissonClient)
                    .runIfLockToFunction(CacheNameEnum.LOCK_EXECUTE_ORDER.getRedisKey(user.getId())
                            , userOrderService::executeOrder, orderReq, 10L);
            if (null != res) {
                return res;
            } else {
                return HttpResponseResult.failed("下单失败");
            }
        } catch (BizException e) {
            return HttpResponseResult.failed(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return HttpResponseResult.failed("下单失败");
        }
    }

    @ApiOperation(value = "订单下单付款")
    @PostMapping("/orderPay")
    public HttpResponseResult<OrderPayRes> orderPay(@Valid @RequestBody OrderPayReq payReq, HttpServletRequest request) {
        SysUser user = sysUserFeignService.queryUserInfo();
        if (user == null || null == user.getId()) {
            return failed(HttpStatus.FORBIDDEN, "请登录");
        }
        if (StringUtil.isEmpty(payReq.getOrderNo())) {
            return failed("订单号不能为空");
        }
        payReq.setPaymentClient(PaymentClientEnum.TEACHER);
        payReq.setUserId(user.getId());
        payReq.setIpAddress(WebUtil.getRemoteIp(request));

        try {
            HttpResponseResult<OrderPayRes> res = DistributedLock.of(redissonClient)
                    .runIfLockToFunction(CacheNameEnum.LOCK_EXECUTE_ORDER.getRedisKey(user.getId())
                            , userOrderService::orderPay, payReq, 10L);
            if (null != res) {
                return res;
            } else {
                return HttpResponseResult.failed("付款失败");
            }
        } catch (BizException e) {
            return HttpResponseResult.failed(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return HttpResponseResult.failed("付款失败");
        }
    }


    @ApiOperation(value = "通过业务id查询用户正在交易中的订单")
    @PostMapping("/getPendingOrder")
    @ApiImplicitParams({
        @ApiImplicitParam(
            name = "goodType",
            value = "订单类型:  PRACTICE、趣纠课购买  LIVE、直播课购买 VIDEO、视频课购买 MUSIC、单曲点播 ACTI_REGIST、活动报名",
            paramType = "query", dataType = "String", required = true
        ),
        @ApiImplicitParam(
            name = "bizId",
            value = "业务id 直播课、趣纠课购买为课程组id；趣纠课为老师id；单曲点播传曲子id",
            paramType = "query", dataType = "Long"
        )
    })
    public HttpResponseResult<UserOrderVo> getPendingOrder(@ApiIgnore @RequestBody OrderSearch query) {
        if (null == query.getGoodType()
            || (!GoodTypeEnum.VIP.getCode().equals(query.getGoodType())
            && !GoodTypeEnum.SVIP.getCode().equals(query.getGoodType())
            && null == query.getBizId())) {
            return HttpResponseResult.failed("参数异常");
        }
        SysUser user = sysUserFeignService.queryUserInfo();
        if (user == null || null == user.getId()) {
            return failed(HttpStatus.FORBIDDEN, "请登录");
        }
        query.setUserId(user.getId());
        query.setOrderClient(ClientEnum.TEACHER.name());
        return userOrderService.getPendingOrder(query);
    }


    @ApiOperation(value = "取消订单")
    @PostMapping("/orderCancel")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderNo", value = "订单号", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "reason", value = "取消说明", paramType = "query", dataType = "String")
    })
    public HttpResponseResult<Boolean> orderCancel(@ApiIgnore @RequestBody OrderPayReq payReq) {
        SysUser user = sysUserFeignService.queryUserInfo();
        if (user == null || null == user.getId()) {
            return failed(HttpStatus.FORBIDDEN, "请登录");
        }
        if (StringUtil.isEmpty(payReq.getOrderNo())) {
            return failed("订单号不能为空");
        }
        payReq.setUserId(user.getId());

        UserOrder order = userOrderService.getByOrderNo(payReq.getOrderNo());
        if (null == order) {
            return failed("订单不存在");
        }
        if(order.getPaymentVersion().equals(EPaymentVersion.V2)){


            // 用户取消支付
            userPaymentCoreService.cancelPayment(JwtUserInfo.builder().userId(user.getId().toString()).clientType(ClientEnum.STUDENT.getCode()).build(), payReq.getOrderNo());
        } else {

            try {
                HttpResponseResult<Boolean> res = DistributedLock.of(redissonClient)
                        .runIfLockToFunction(CacheNameEnum.LOCK_EXECUTE_ORDER.getRedisKey(payReq.getOrderNo())
                                , userOrderService::orderCancel, payReq, 10L);
                if (null != res) {
                    return res;
                } else {
                    return HttpResponseResult.failed("取消订单失败");
                }
            } catch (BizException e) {
                return HttpResponseResult.failed(e.getMessage());
            } catch (Exception e) {
                e.printStackTrace();
                return HttpResponseResult.failed("取消订单失败");
            }
        }
        return succeed();
    }

    /**
     * 查询分页
     */
    @PostMapping("/page")
    @ApiOperation(value = "查询分页", notes = "传入orderSearch")
    public HttpResponseResult<PageInfo<UserOrderVo>> page(@RequestBody OrderSearch query) {
        SysUser user = sysUserFeignService.queryUserInfo();
        if (user == null || null == user.getId()) {
            return failed(HttpStatus.FORBIDDEN, "请登录");
        }
        query.setUserId(user.getId());
        query.setOrderClient(ClientEnum.TEACHER.getCode());
        if (StringUtil.isEmpty(query.getSearchDate())) {
            query.setSearchDate(DateUtil.format(new Date(), "yyyy-MM"));
        }
        String[] classDateSp = query.getSearchDate().split("-");
        try {
            LocalDate date = LocalDate.of(Integer.parseInt(classDateSp[0]), Integer.parseInt(classDateSp[1]), 1);

            LocalDateTime firstDay = LocalDateTime.of(date.with(TemporalAdjusters.firstDayOfMonth()), LocalTime.MIN);
            LocalDateTime lastDay = LocalDateTime.of(date.with(TemporalAdjusters.lastDayOfMonth()), LocalTime.MAX);

            query.setStartTime(firstDay);
            query.setEndTime(lastDay);
        } catch (Exception e) {
            throw new BizException("查询时间格式不正确 [" + query.getSearchDate() + "]");
        }
        IPage<UserOrderVo> pages = userOrderService.selectPage(PageUtil.getPage(query), query);
        return succeed(PageUtil.pageInfo(pages));
    }

    /**
     * 查询单条
     */
    @GetMapping("/detail/{id}")
    @ApiOperation(value = "通过id查询详情", notes = "传入id")
    public HttpResponseResult<UserOrderVo> detail(@PathVariable("id") Long id) {
        SysUser user = sysUserFeignService.queryUserInfo();
        if (user == null || null == user.getId()) {
            return failed(HttpStatus.FORBIDDEN, "请登录");
        }
        UserOrder param = new UserOrder();
        param.setUserId(user.getId());
        param.setId(id);
        UserOrderVo detail = userOrderService.detailApp(param);
        return succeed(detail);
    }

    /**
     * 查询单条
     */
    @GetMapping("/detailByOrderNo/{orderNo}")
    @ApiOperation(value = "通过订单号查询详情", notes = "传入orderNo")
    public HttpResponseResult<UserOrderVo> detailByOrderNo(@PathVariable("orderNo") String orderNo) {
        SysUser user = sysUserFeignService.queryUserInfo();
        if (user == null || null == user.getId()) {
            return failed(HttpStatus.FORBIDDEN, "请登录");
        }
        UserOrder param = new UserOrder();
        param.setUserId(user.getId());
        param.setOrderNo(orderNo);
        UserOrderVo detail = userOrderService.detailApp(param);
        return succeed(detail);
    }


    @ApiOperation(value = "用户下单", notes = "用户下单")
    @PostMapping("/executeOrder/v2")
    public R<UserPaymentOrderWrapper.PaymentConfig> executeOrderV2(@Validated @RequestBody UserPaymentOrderVo.OrderReq orderReq) {

        // 设置下单用户信息
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (Objects.isNull(sysUser)) {
            throw com.microsvc.toolkit.common.webportal.exception.BizException.from("用户信息不存在");
        }
        orderReq.setUserId(sysUser.getId());
        orderReq.setPaymentClient(ClientEnum.TEACHER.name());


        // 用户下单请求
        UserPaymentOrderWrapper.UserPaymentOrder order = JSON.parseObject(orderReq.jsonString(), UserPaymentOrderWrapper.UserPaymentOrder.class);

        // 新增数据
        UserPaymentOrderWrapper.PaymentConfig paymentConfig = userPaymentCoreService.executeOrderCreate(order);
        if (Objects.isNull(paymentConfig)) {
            throw com.microsvc.toolkit.common.webportal.exception.BizException.from("下单失败");
        }

        return R.from(paymentConfig);
    }

    @ApiOperation(value = "用户付款", notes = "用户付款")
    @PostMapping("/executePayment/v2")
    public R<UserPaymentOrderWrapper.PaymentReq> executePaymentV2(@Validated @RequestBody UserPaymentOrderVo.PaymentReqConfig config,HttpServletRequest request) {
        // 设置下单用户信息
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (Objects.isNull(sysUser)) {
            throw com.microsvc.toolkit.common.webportal.exception.BizException.from("用户信息不存在");
        }


        // 用户下单请求
        UserPaymentOrderWrapper.PaymentOrderReqConfig reqConfig = UserPaymentOrderWrapper.PaymentOrderReqConfig.from(config.jsonString());

        // 支付三方
        reqConfig.setPaymentVendor(config.getPaymentVendor());
        // 请示IP地址
        reqConfig.setIp(ServletUtil.getClientIP(request));
        // 创建用户支付数据
        UserPaymentOrderWrapper.PaymentReq paymentConfig = userPaymentCoreService.executePayment(JwtUserInfo.builder()
                .userId(sysUser.getId().toString()).clientType(ClientEnum.TEACHER.getCode()).build(), reqConfig);
        if (Objects.isNull(paymentConfig)) {
            throw com.microsvc.toolkit.common.webportal.exception.BizException.from("付款失败");
        }

        return R.from(paymentConfig);
    }

    @ApiOperation(value = "取消订单")
    @PostMapping("/orderCancel/v2")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderNo", value = "订单号", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "reason", value = "取消说明", paramType = "query", dataType = "String")
    })
    public HttpResponseResult<Boolean> orderCancelV2(@ApiIgnore @RequestBody OrderPayReq payReq) {
        SysUser user = sysUserFeignService.queryUserInfo();
        if (user == null || null == user.getId()) {
            return failed(HttpStatus.FORBIDDEN, "请登录");
        }
        if (StringUtil.isEmpty(payReq.getOrderNo())) {
            return failed("订单号不能为空");
        }
        payReq.setUserId(user.getId());

        // 用户取消支付
        userPaymentCoreService.cancelPayment(JwtUserInfo.builder().userId(user.getId().toString()).clientType(ClientEnum.TEACHER.getCode()).build(), payReq.getOrderNo());

        return HttpResponseResult.status(true);
    }


    @ApiOperation(value = "检测订单应该使用哪种支付方式")
    @PostMapping("/orderPayType")
    public HttpResponseResult<UserPaymentOrderWrapper.OrderPayTypeResp> orderPayType( @RequestBody UserPaymentOrderWrapper.OrderPayTypeReq payTypeReq) {
        SysUser user = sysUserFeignService.queryUserInfo();
        if (user == null || null == user.getId()) {
            return failed(HttpStatus.FORBIDDEN, "请登录");
        }

        payTypeReq.setBuyId(user.getId());
        payTypeReq.setClientType(ClientEnum.TEACHER);

        return HttpResponseResult.succeed(userPaymentCoreService.orderPayType(payTypeReq));
    }


}
