package cn.ysk.cashier.controller.product;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.ysk.cashier.annotation.AnonymousAccess;
import cn.ysk.cashier.annotation.Log;
import cn.ysk.cashier.config.security.security.TokenProvider;
import cn.ysk.cashier.dto.shoptable.*;
import cn.ysk.cashier.exception.BadRequestException;
import cn.ysk.cashier.mybatis.mapper.TbMerchantAccountMapper;
import cn.ysk.cashier.pojo.TbToken;
import cn.ysk.cashier.pojo.order.TbCashierCart;
import cn.ysk.cashier.pojo.shop.TbMerchantAccount;
import cn.ysk.cashier.pojo.shop.TbPlussShopStaff;
import cn.ysk.cashier.repository.TbTokenRepository;
import cn.ysk.cashier.repository.shop.TbPlussShopStaffRepository;
import cn.ysk.cashier.service.product.TbProductService;
import cn.ysk.cashier.service.shop.TbShopTableService;
import cn.ysk.cashier.utils.RabbitMsgUtils;
import cn.ysk.cashier.utils.RedisUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/api/place")
public class TbPlaceController {
    private final TbShopTableService tbShopTableService;
    private final TbProductService tbProductService;
    private final RabbitMsgUtils rabbitMsgUtils;
    @Resource
    private TbPlussShopStaffRepository staffRepository;
    @Resource
    private TbMerchantAccountMapper tbMerchantAccountMapper;
    @Resource
    private TbTokenRepository tbTokenRepository;
    @Resource
    private TokenProvider tokenProvider;
    @Lazy
    @Autowired
    private RedisUtils redisUtils;

    @GetMapping("/activate")
    @ApiOperation("查询/product")
    public ResponseEntity<Object> queryActivateTbProductInfo(@RequestParam(defaultValue = "0") Integer page,
                                                             @RequestParam(defaultValue = "30") Integer size,
                                                             @RequestParam(required = false) Integer categoryId,
                                                             @RequestParam Integer shopId,
                                                             @RequestParam(required = false) Integer productId) {
        return new ResponseEntity<>(tbProductService.activateProduct(page, size, categoryId, shopId, productId), HttpStatus.OK);
    }

    public TbPlaceController(TbShopTableService tbShopTableService, TbProductService tbProductService, RabbitMsgUtils rabbitMsgUtils) {
        this.tbShopTableService = tbShopTableService;
        this.tbProductService = tbProductService;
        this.rabbitMsgUtils = rabbitMsgUtils;
    }

    @PostMapping("/addCart")
    @ApiOperation("代客下单/shop/table")
    public ResponseEntity<TbCashierCart> addCartForUser(@Valid @RequestBody AddCartDTO addCartDTO) {
        return ResponseEntity.ok(tbShopTableService.addCartForUser(addCartDTO));
    }

    @PutMapping("/choseModel")
    @ApiOperation("代客下单/shop/table")
    public ResponseEntity<?> choseModel(@Valid @RequestBody ChoseModelDTO choseModelDTO) {
        return ResponseEntity.ok(tbShopTableService.choseModel(choseModelDTO));
    }

    @PutMapping("/updateCart")
    @ApiOperation("代客下单/shop/table")
    public ResponseEntity<TbCashierCart> updateCart(@Valid @RequestBody UpdateCartDTO updateCartDTO) {
        return ResponseEntity.ok(tbShopTableService.updateCart(updateCartDTO));
    }

    @PutMapping("/pack")
    @ApiOperation("代客下单/shop/table")
    public ResponseEntity<TbCashierCart> pack(@Valid @RequestBody PackCartDTO packCartDTO) {
        tbShopTableService.pack(packCartDTO);
        return ResponseEntity.ok(null);
    }

    @DeleteMapping("/removeCart")
    @ApiOperation("代客下单 清空购物车 /shop/table")
    public ResponseEntity<Object> removeCart(@Validated @RequestBody RemoveCartDTO removeCartDTO) {
        tbShopTableService.removeCart(removeCartDTO);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @PutMapping("/returnCart")
    @ApiOperation("代客下单 清空购物车 /shop/table")
    public ResponseEntity<Object> returnOrder(@Validated @RequestBody ReturnCartDTO ReturnCartDTO) {
        tbShopTableService.returnCart(ReturnCartDTO);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @DeleteMapping("/clearCart")
    @ApiOperation("代客下单 清空购物车 /shop/table"/**/)
    public ResponseEntity<Object> clearCart(@Validated @RequestBody ClearCartDTO clearCartDTO) {
        tbShopTableService.clearCart(clearCartDTO);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @GetMapping("/cart")
    @ApiOperation("代客下单 查询购物车 /shop/table")
    public ResponseEntity<Object> getCart(@RequestParam(defaultValue = "1") Integer page,
                                          @RequestParam(defaultValue = "10") Integer size,
                                          @RequestParam(required = false) String tableId,
                                          @RequestParam Integer shopId,
                                          @RequestParam String masterId,
                                          @RequestParam String useType) {
        return ResponseEntity.ok(tbShopTableService.getCart(tableId, page, size, shopId, masterId, useType));
    }

    @GetMapping("/pending/cart")
    @ApiOperation("代客下单 查询购物车 /shop/table")
    public ResponseEntity<Object> getPendingCart(@RequestParam Integer shopId,
                                                 @RequestParam(required = false) String tableId,
                                                 @RequestParam String useType) {
        return ResponseEntity.ok(tbShopTableService.getCar(shopId, tableId, useType));
    }

    @GetMapping("/masterId")
    @ApiOperation("代客下单 ")
    public ResponseEntity<Object> getMasterId(@RequestParam Integer shopId,
                                              @RequestParam(required = false) String tableId,
                                              @RequestParam(required = false) Integer orderId,
                                              @RequestParam(defaultValue = "") String useType) {
        return ResponseEntity.ok(tbShopTableService.getMasterId(shopId, tableId, useType, orderId));
    }

    @PostMapping("/order")
    @ApiOperation("代客下单 查询购物车 /shop/table")
    public ResponseEntity<Object> createOrder(@RequestBody CreateOrderDTO createOrderDTO) {
        return ResponseEntity.ok(tbShopTableService.createOrder(createOrderDTO, !createOrderDTO.isPostPay(), true));
    }

    @PostMapping("/pending")
    @ApiOperation("代客下单 查询购物车 /shop/table")
    public ResponseEntity<Object> pending(@RequestBody PendingDTO pendingDTO) {
        return ResponseEntity.ok(tbShopTableService.pending(pendingDTO));
    }

    @GetMapping("/payType")
    @ApiOperation("代客下单 获取支付类型")
    public ResponseEntity<Object> getPayType(@RequestParam Integer shopId) {
        return ResponseEntity.ok(tbShopTableService.getPayType(shopId));
    }

    @DeleteMapping("/order")
    @ApiOperation("代客下单 删除订单")
    public ResponseEntity<Object> delete(@Validated @RequestBody DeleteOrderDTO deleteOrderDTO) {
        return ResponseEntity.ok(tbShopTableService.deleteOrder(deleteOrderDTO));
    }

    @PutMapping("/pay")
    @ApiOperation("代客下单 支付订单")
    public ResponseEntity<Object> pay(HttpServletRequest request, @Validated @RequestBody PayDTO payDTO) {
        String token = tokenProvider.getToken(request);
        JSONObject userInfo = JSON.parseObject(JSON.toJSONString(redisUtils.get("online-token-" + token)));
        String userName = userInfo.getString("userName");
        String shopId = userInfo.getString("shopId");
        TbPlussShopStaff shopStaff = staffRepository.queryByAccount(userName, shopId);
        TbMerchantAccount merchantAccount = tbMerchantAccountMapper.selectOne(Wrappers.<TbMerchantAccount>lambdaQuery().eq(TbMerchantAccount::getAccount, shopStaff.getAccount()));
        Integer accountId = merchantAccount.getId();
        Integer staffId = shopStaff.getId();
        List<TbToken> onlineUserList = tbTokenRepository.findListByAccountIdAndStaffId(accountId, staffId);
        if (CollUtil.isNotEmpty(onlineUserList)) {
            payDTO.setToken(onlineUserList.get(0).getToken());
        }
        return ResponseEntity.ok(tbShopTableService.pay(payDTO));
    }

    @PostMapping("/returnOrder")
    public ResponseEntity<?> returnOrder(@RequestBody ReturnOrderDTO returnOrderDTO) {
        return ResponseEntity.ok(tbShopTableService.returnOrder(returnOrderDTO));
    }

    @PutMapping("/choseTable")
    @ApiOperation("代客下单 选择台桌")
    public ResponseEntity<Object> choseTable(@Validated @RequestBody ChoseTableDTO choseTableDTO) {
        return ResponseEntity.ok(tbShopTableService.choseTable(choseTableDTO));
    }

    @PutMapping("/choseCount")
    @ApiOperation("代客下单 选择用餐人数")
    public ResponseEntity<Object> choseCount(@Validated @RequestBody ChoseCountDTO choseCountDTO) {

        if (StrUtil.isBlank(choseCountDTO.getTableId())) {
            return ResponseEntity.ok(null);
        }

        if (StrUtil.isNotBlank(choseCountDTO.getTableId()) && choseCountDTO.getNum() == null) {
            throw new BadRequestException("人数不为空");
        }
        return ResponseEntity.ok(tbShopTableService.choseCount(choseCountDTO));
    }

    @PutMapping("/updateVip")
    @ApiOperation("代客下单 查询购物车 /shop/table")
    public ResponseEntity<Object> updateVip(@Validated @RequestBody UpdateVipDTO updateVipDTO) {
        return ResponseEntity.ok(tbShopTableService.updateVip(updateVipDTO));
    }

    @PostMapping("/printOrder")
    @ApiOperation("代客下单 打印订单")
    public ResponseEntity<Object> printOrder(@Validated @RequestBody BaseTableDTO baseTableDTO) {
        return ResponseEntity.ok(tbShopTableService.printOrder(baseTableDTO));
    }

    @Log("代客下单 打印菜品单")
    @ApiOperation("代客下单 打印菜品单")
    @PostMapping("printDishes")
    public ResponseEntity<Object> printDishes(@Validated @RequestBody BaseTableDTO baseTableDTO) {
        return ResponseEntity.ok(tbShopTableService.printDishes(baseTableDTO));
    }

    @AnonymousAccess
    @GetMapping("/test")
    public void test(
            @RequestParam Integer id
    ) {
//        rabbitMsgUtils.printDishesTicket(4951, false, 9783);

    }

}
