package com.gree.mall.miniapp.controller.material;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.gree.mall.miniapp.annotation.ApiNotAuth;
import com.gree.mall.miniapp.bean.PayDetail;
import com.gree.mall.miniapp.bean.material.*;
import com.gree.mall.miniapp.constant.Constant;
import com.gree.mall.miniapp.constant.SybConstants;
import com.gree.mall.miniapp.exception.RemoteServiceException;
import com.gree.mall.miniapp.helper.ResponseHelper;
import com.gree.mall.miniapp.logic.material.WebsitSalesLogic;
import com.gree.mall.miniapp.plus.entity.AdminWebsitPayConfig;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.integration.redis.util.RedisLockRegistry;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;

@Slf4j
@RestController
@Api(value = "辅配销售API", tags ={"辅配销售API"} )
@RequestMapping(value = "/material/salses", produces = "application/json; charset=utf-8")
public class MaterialSalesController {

    @Resource
    WebsitSalesLogic websitSalesLogic;
    @Resource
    RedisLockRegistry redisLockRegistry;

    @PostMapping("/buy/list")
    @ApiOperation(value = "购买记录")
    public ResponseHelper<IPage<SalesOrderBean>> buyList(
            @ApiParam(value = "单据状态 SAVE=保存 SUBMIT=提交 PAY_NOT_TAKE=已支付,未提货 PAY_TAKE=已支付,已提货 CANCEL=取消订单") @RequestParam(required = false) String flag,
            @ApiParam(value = "页号",required = true) @RequestParam Integer pageNum,
            @ApiParam(value = "页大小",required = true) @RequestParam Integer pageSize,
            HttpServletRequest request
    ) {
        IPage<SalesOrderBean> page = websitSalesLogic.buyList(flag, pageNum, pageSize, request);
        return ResponseHelper.success(page);
    }

    @PostMapping("/detail")
    @ApiOperation(value = "购买记录详情")
    public ResponseHelper<SalesOrderBean> detail(
            HttpServletRequest request,
            @ApiParam(value = "单据编号",required = true) @RequestParam String salesId
    ) throws RemoteServiceException {
        SalesOrderBean detail = websitSalesLogic.detail(request, salesId);
        return ResponseHelper.success(detail);
    }

    @PostMapping("count")
    @ApiOperation(value = "购买记录统计")
    public ResponseHelper<MyDataCountBean> count(
            HttpServletRequest request
    ) {
        MyDataCountBean bean = websitSalesLogic.count(request);
        return ResponseHelper.success(bean);
    }

    @PostMapping("/cancel")
    @ApiOperation(value = "取消订单")
    public ResponseHelper cancel(
            HttpServletRequest request,
            @ApiParam(value = "单据编号",required = true) @RequestParam String salesId
    ) throws RemoteServiceException {
        websitSalesLogic.cancel(request, salesId);
        return ResponseHelper.success();
    }
//    @PostMapping("/pay")
//    @ApiOperation(value = "支付")
//    public ResponseHelper<PayDetail> pay(
//            HttpServletRequest request,
//            @ApiParam(value = "单据编号",required = true) @RequestParam String salesId,
//            @ApiParam(value = "是否小程序兼容",required = false) @RequestParam (required = false) Boolean miniPay,
//            @ApiParam(value = "openId",required = false) @RequestParam(required = false) String openId
//    ) throws RemoteServiceException {
//        PayDetail detail = websitSalesLogic.pay(request, salesId,miniPay,openId);
//        return ResponseHelper.success(detail);
//    }

    @PostMapping("/exist/stock/category")
    @ApiOperation(value = "辅材库存分类")
    public ResponseHelper<List<WebsitSalesCategoryVO>> existStockCategory(
            HttpServletRequest request,
            @ApiParam(value = "网点编号", required = true) @RequestParam String websitId
    ) throws RemoteServiceException {
        List<WebsitSalesCategoryVO> list = websitSalesLogic.existStockCategory(request, websitId);
        return ResponseHelper.success(list);
    }

    @PostMapping("/exist/stock/goods")
    @ApiOperation(value = "网点销售订单-辅材库存")
    public ResponseHelper<List<WebsitSalesGoodsVO>> existStockGoods(
            HttpServletRequest request,
            @ApiParam(value = "网点编号", required = true) @RequestParam String websitId,
            @ApiParam(value = "分类id") @RequestParam(required = false) String categoryId,
            @ApiParam(value = "商品类型 M=辅材 P=配件", required = true) @RequestParam String type,
            @ApiParam(value = "商品名称", required = true) @RequestParam(required = false) String goodsName
    ) throws RemoteServiceException {
        List<WebsitSalesGoodsVO> list = websitSalesLogic.existStockGoods(request, websitId, categoryId, type, goodsName);
        return ResponseHelper.success(list);
    }

    @PostMapping("/list")
    @ApiOperation("购物车列表")
    public ResponseHelper<List<WebsitShoppingCartList>> list(
            @ApiParam(value = "师傅号",required = true) @RequestParam String workerId,
            @ApiParam(value = "网点号",required = true) @RequestParam String websitId,
            @ApiParam(value = "商品类型 M=辅材 P=配件",required = true) @RequestParam String goodsType
    ){
        List<WebsitShoppingCartList> shoppingCartLists = websitSalesLogic.queryShoppingCart(workerId, websitId, goodsType);
        return ResponseHelper.success(shoppingCartLists);
    }

    @PostMapping("/add")
    @ApiOperation("添加到购物车并提交")
    public ResponseHelper<List<WebsitShoppingCartList>> addShoppingCart(@RequestBody WebsitShoppingCartBean shoppingCartBean, HttpServletRequest request) throws Exception {
        List<WebsitShoppingCartList> shoppingCartLists = websitSalesLogic.addShoppingCart(shoppingCartBean, request);
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.LOCK_ORDER + ":" + shoppingCartBean.getWebsitId() + shoppingCartBean.getGoodsType());
        if(!obtain.tryLock(10, TimeUnit.SECONDS)){
            throw new RemoteServiceException("系统繁忙，请稍后再尝试");
        }
        String salesId;
        try {
            salesId = websitSalesLogic.add(shoppingCartBean.getWebsitId(), shoppingCartBean.getGoodsType(), shoppingCartBean.getRemark(), request);
        }finally {
            obtain.unlock();
        }
        return ResponseHelper.success(salesId);
    }

    @PostMapping("/clear")
    @ApiOperation("清空购物车")
    public ResponseHelper clearShoppingCart(
            @ApiParam(value = "师傅号",required = true) @RequestParam String workerId,
            @ApiParam(value = "网点号",required = true) @RequestParam String websitId,
            @ApiParam(value = "商品类型 M=辅材 P=配件",required = true) @RequestParam String goodsType
    ){
        websitSalesLogic.clearShoppingCart(workerId, websitId, goodsType);
        return ResponseHelper.success();
    }

//    @PostMapping("/add")
//    @ApiOperation(value = "销售订单-添加")
//    public ResponseHelper add(
//            @ApiParam(value = "网点号",required = true) @RequestParam String websitId,
//            @ApiParam(value = "商品类型 M=辅材 P=配件",required = true) @RequestParam String goodsType,
//            @ApiParam(value = "备注",required = true) @RequestParam String remark,
//            HttpServletRequest request
//    ) throws Exception {
//        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.LOCK_ORDER + ":" + websitId + goodsType);
//        if(!obtain.tryLock(10, TimeUnit.SECONDS)){
//            throw new RemoteServiceException("系统繁忙，请稍后再尝试");
//        }
//        String salesId;
//        try {
//            salesId = websitSalesLogic.add(websitId, goodsType, remark, request);
//        }finally {
//            obtain.unlock();
//        }
//        return ResponseHelper.success(salesId);
//    }

    @PostMapping("/get/pay/config")
    @ApiOperation("获取支付配置")
    public ResponseHelper<List<AdminWebsitPayConfig>> getPayConfig(
            @ApiParam(value = "网点号",required = true) @RequestParam String websitId,
            @ApiParam(value = "商品类型 M=辅材 P=配件",required = true) @RequestParam String goodsType,
            HttpServletRequest request
    ){
        List<AdminWebsitPayConfig> configList = websitSalesLogic.getPayConfig(websitId, goodsType, request);
        return ResponseHelper.success(configList);
    }

//    @PostMapping("/save/pay/order")
//    @ApiOperation(value = "生成订单支付并返回短链接")
//    public ResponseHelper<WebsitSalesPayMapBean> saveSheetPayMap(@RequestBody WebsitSalesPayMapBean sheetPayMap) throws RemoteServiceException {
//        return ResponseHelper.success(websitSalesLogic.saveSheetPayMap(sheetPayMap));
//    }
//
//    @ApiNotAuth
//    @PostMapping("/pay")
//    @ApiOperation(value = "生成支付")
//    public ResponseHelper<PayDetail> websitDefault(
//            @ApiParam(value = "appOrderId或payConfigId",required = true) @RequestParam String key,
//            @ApiParam(value = "openid",required = true) @RequestParam String openid,
//            @ApiParam(value = "salesId") @RequestParam(required = false) String salesId,
//            @ApiParam(value = "通联支付类型") @RequestParam(required = false, defaultValue = SybConstants.PAY_TYPE_W06) String payType,
//            @ApiParam(value = "支付完成跳转(必须为https协议地址，且不允许带参数)") @RequestParam(required = false) String frontUrl
//    ) throws RemoteServiceException, InterruptedException {
//        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.LOCK_ORDER + ":" + key);
//        if(!obtain.tryLock(10, TimeUnit.SECONDS)){
//            throw new RemoteServiceException("系统繁忙，请稍后再尝试");
//        }
//        try {
//            PayDetail pay = websitSalesLogic.generatePayRecord(key, openid, salesId, payType, frontUrl);
//            return ResponseHelper.success(pay);
//        }finally {
//            obtain.unlock();
//        }
//    }
}
