package com.yonge.cooleshow.teacher.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
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.common.enums.CacheNameEnum;
import com.yonge.cooleshow.biz.dal.service.UserOrderService;
import com.yonge.toolset.payment.util.DistributedLock;
import com.yonge.toolset.mybatis.support.PageUtil;
import com.yonge.cooleshow.biz.dal.vo.UserOrderVo;
import com.yonge.cooleshow.biz.dal.vo.res.OrderPayRes;
import com.yonge.cooleshow.common.controller.BaseController;
import com.yonge.cooleshow.common.entity.HttpResponseResult;
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.payment.base.enums.PaymentClientEnum;
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.web.bind.annotation.*;
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.concurrent.TimeUnit;

/**
 * @Author: liweifan
 * @Data: 2022/3/11 18:16
 */
@RestController
@RequestMapping("/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;

    @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 = "取消订单")
    @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());

        try {
            HttpResponseResult<Boolean> res = DistributedLock.of(redissonClient)
                    .runIfLockToFunction(CacheNameEnum.LOCK_EXECUTE_ORDER.getRedisKey(user.getId())
                            , 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("取消订单失败");
        }
    }

    /**
     * 查询分页
     */
    @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);
    }
}
