package com.ruoyi.applet.contoller;


import com.alibaba.fastjson.JSONObject;
import com.cyl.h5.pojo.request.CancelOrderRequest;
import com.cyl.h5.pojo.request.OrderPayRequest;
import com.cyl.h5.pojo.response.OrderPayResponse;
import com.cyl.h5.pojo.vo.H5OrderVO;
import com.cyl.manager.oms.service.OrderOperateHistoryService;
import com.cyl.manager.ums.domain.Member;
import com.ruoyi.applet.mallpojo.TeacherListRequest;
import com.ruoyi.applet.service.IApiMallOrderService;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.redis.RedisService;
import com.ruoyi.framework.config.LocalDataUtil;
import com.ruoyi.model.domain.AppUsers;
import com.ruoyi.model.domain.AppletAddress;
import com.ruoyi.model.domain.AppletUsersTeacher;
import com.ruoyi.model.service.IAppUsersService;
import com.ruoyi.model.service.IAppletAddressService;
import com.ruoyi.model.service.IAppletConfigService;
import com.ruoyi.model.service.IAppletUsersTeacherService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Api(description = "下单小程序端 - 订单信息列表")
@RestController
@RequestMapping("/applet/mall/order")
public class ApiMallOrderController extends BaseController {

    @Autowired
    private IApiMallOrderService service;

    @Autowired
    private IAppUsersService appUsersService;
    @Autowired
    private IAppletUsersTeacherService appletUsersTeacherService;
    @Autowired
    private IAppletConfigService appletConfigService;
    @Autowired
    private IAppletAddressService appletAddressService;

    @Autowired
    private RedisService redisService;

    @Autowired
    private OrderOperateHistoryService orderOperateHistoryService;

    @ApiOperation("mall-订单列表信息接口")
    @GetMapping("/listByOpenid")
    public ResponseEntity<PageImpl<H5OrderVO>> orderPageByOpenid(Integer status, String openId, Pageable pageable){
        List<Integer> statusList = new ArrayList<>();
        if (status == -1) {
            statusList.add(0);
            statusList.add(1);
            statusList.add(2);
            statusList.add(3);

        } else {
            statusList.add(status);
        }
        PageImpl<H5OrderVO> h5OrderVOS = service.orderPageByOpenid(statusList, openId, pageable);

        return ResponseEntity.ok(h5OrderVOS);
    }



    //根据订单标识查询订单详情
    @ApiOperation("mall-根据订单标识查询订单详情接口")
    @GetMapping("/orderDetail")
    public ResponseEntity<H5OrderVO> orderDetail(@RequestParam(required = false) Long orderId){
        if (orderId == null){
            throw new RuntimeException("系统繁忙");
        }
        return ResponseEntity.ok(service.orderDetail(orderId));
    }


    //根据订单标识取消订单
    @ApiOperation("mall-根据订单标识取消订单接口")
    @PostMapping("/orderCancel")
    public AjaxResult orderCancel(@RequestBody CancelOrderRequest request){
        //修改订单状态为已渠道
        String s = service.orderBatchCancel(request, null);
        return AjaxResult.success(s);




//        Member member = (Member) LocalDataUtil.getVar(Constants.MEMBER_INFO);
//        String redisKey = "h5_oms_order_cancel_"+ request.getIdList().get(0);
//        String redisValue = request.getIdList().get(0)+"_"+System.currentTimeMillis();
//        try{
//            redisService.lock(redisKey,redisValue,60);
//            return ResponseEntity.ok(service.orderBatchCancel(request, member.getId()));
//        }catch (Exception e){
//            log.error("订单取消方法异常",e);
//            throw new RuntimeException("订单取消失败");
//        }finally {
//            try {
//                redisService.unLock(redisKey,redisValue);
//            }catch (Exception e){
//                log.error("",e);
//            }
//        }
    }


    //根据订单标识去评价
    @ApiOperation("mall-根据订单标识去评价接口")
    @GetMapping("/orderEvaluate")
    public AjaxResult orderEvaluate(@RequestParam Long orderId){
        if (orderId == null){
            throw new RuntimeException("系统繁忙");
        }
        return AjaxResult.successData(service.orderEvaluate(orderId));
    }





    //查询-再来一单的历史伴宠师
    @ApiOperation("mall-查询-再来一单的历史伴宠师接口")
    @GetMapping("")
    public TableDataInfo getTeacherList(TeacherListRequest request) {
        startPage();
        AppUsers appUsers = new AppUsers();
        appUsers.setUserBcs(1);
        //如果伴宠师等级传入
        if (request.getTeacherLevels() != null) {
            appUsers.setUserBcsRole(request.getTeacherLevels());
        }
        List<AppUsers> appUsersList = appUsersService.selectAppUsersList(appUsers);
        for (AppUsers appUsers1 : appUsersList){
            AppletUsersTeacher appletUsersTeacher = appletUsersTeacherService.selectAppletUsersTeacherByUserId(appUsers1.getUserId());
            appUsers1.setAppletUsersTeacher(appletUsersTeacher);

            AppletAddress appletAddress = new AppletAddress();
            appletAddress.setUserId(appUsers.getUserId());
            List<AppletAddress> appletAddresses = appletAddressService.selectAppletAddressList(appletAddress);
            appUsers.setAppletAddresseList(appletAddresses);
        }
        return getDataTable(appUsersList);
    }


    @ApiOperation("mall-查询-再次支付")
    @PostMapping("/orderPay")
    public ResponseEntity<OrderPayResponse> orderPay(@RequestBody OrderPayRequest req){
        log.info("订单支付","提交的数据："+ JSONObject.toJSONString(req));
        String redisKey = "h5_oms_order_pay_"+req.getPayId();
        String redisValue = req.getPayId()+"_"+System.currentTimeMillis();
        try {
            redisService.lock(redisKey, redisValue, 60);
            Member member = (Member) LocalDataUtil.getVar(Constants.MEMBER_INFO);
            Long memberId = member.getId();
            req.setMemberId(memberId);
            return ResponseEntity.ok(service.orderPay(req));
        }catch (Exception e){
            log.error("支付方法异常", e);
            throw new RuntimeException(e.getMessage());
        }finally {
            try{
                redisService.unLock(redisKey,redisValue);
            }catch (Exception e){
                log.error("",e);
            }
        }
    }


}
