package com.izouma.nineth.web.mobile.v1;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.izouma.nineth.aspect.CipherParam;
import com.izouma.nineth.aspect.RequestCipher;
import com.izouma.nineth.config.RedisKeys;
import com.izouma.nineth.config.SysConstants;
import com.izouma.nineth.domain.Order;
import com.izouma.nineth.domain.User;
import com.izouma.nineth.dto.PageQuery;
import com.izouma.nineth.dto.PageWrapDTO;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.lock.RedisLockException;
import com.izouma.nineth.repo.OrderRepo;
import com.izouma.nineth.service.CustomCaptchaService;
import com.izouma.nineth.service.OrderService;
import com.izouma.nineth.service.SysConfigService;
import com.izouma.nineth.utils.ApplicationContextUtil;
import com.izouma.nineth.utils.SecurityUtils;
import com.izouma.nineth.web.BaseController;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.math.NumberUtils;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/order/v1")
@Slf4j
@AllArgsConstructor
public class OrderControllerV1 extends BaseController {
    private final OrderService orderService;
    private final OrderRepo orderRepo;
    private final CustomCaptchaService customCaptchaService;
    private final RedisTemplate<String, Object> redisTemplate;

    private final SysConfigService sysConfigService;




    //@PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/all")
    public PageWrapDTO<Order> all(@RequestBody PageQuery pageQuery) {
        return orderService.all(pageQuery);
    }

    @GetMapping("/get/{id}")
    public Order get(@PathVariable Long id) {
        return orderService.getOrderInfo(id);
    }




    @PostMapping("/mqCreate")
    @RequestCipher
    public Map<String, String> mqCreate(@RequestParam Long collectionId, @RequestParam int qty,
                                        @RequestParam @CipherParam String encrytorData,
                                        @RequestParam(required = false) Long addressId,
                                        @RequestParam(required = false) Long couponId,
                                        @RequestParam(required = false) List<Long> couponIds,
                                        @RequestParam(required = false) Long invitor) {
        final User user = SecurityUtils.getAuthenticatedUser();
        BoundValueOperations<String, Object> ops = redisTemplate.boundValueOps(RedisKeys.USER_LOCK_ORDER_NUMBER + user.getId());
        Integer lockOrderNum = (Integer) ops.get();
        Integer orderLimitNumber = sysConfigService.getInt(SysConstants.LOCK_ORDER_LIMIT_NUMBER);
        if (lockOrderNum != null && lockOrderNum >= orderLimitNumber) {
            Long second = ops.getExpire();
            Long hour = second/3600;
            Long minute = ((second - hour * 3600) / 60) +1;
            throw new BusinessException("您的账号因锁单过多被暂时封停，剩余封停时间为" + hour + "小时" + minute +"分钟");
        }

        if (!ApplicationContextUtil.isRunDev()) {
            JSONObject jsonObject = JSON.parseObject(encrytorData);
            String captchaKey = jsonObject.getString("captchaKey");
            String captcha = jsonObject.getString("captcha");
            //非开发环境才使用
            if (!customCaptchaService.verify(captchaKey, captcha, true)) {
                throw new BusinessException("图形验证码错误");
            }
        }

        HashMap<String, String> map = new HashMap<>();
        try {
            String id = orderService.mqCreate(user.getId(), collectionId, qty, addressId, couponId, couponIds, invitor);
            map.put("id", id);
            map.put("result", "0");
            return map;
        } catch (RedisLockException err) {
            log.error("用户锁定下单失败，用户ID:{}, 藏品ID：{}", user.getId(), collectionId);
            throw new BusinessException("很遗憾，藏品已售罄");
        }


    }

    @PostMapping("/hide")
    public void hide(@RequestParam Long id) {
        Order order = orderRepo.findById(id).orElseThrow(new BusinessException("订单不存在"));
        order.setHide(true);
        orderRepo.save(order);
    }

    @GetMapping("/{id}/status")
    public Object status(@PathVariable String id) {
        if (!NumberUtils.isDigits(id)) {
            throw new BusinessException("请求信息错误 -" + id);
        }
        Order order = orderRepo.findById(Long.valueOf(id)).orElseThrow(new BusinessException("订单不存在"));
        return new HashMap<>() {{
            put("status", order.getStatus());
            put("projectId", order.getProjectId());
        }};
    }



    @GetMapping("/createResult")
    public Object createResult(@RequestParam String id) {
        return orderService.queryCreateOrder(id);
    }



}

