package com.ruoyi.applet.contoller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
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.domain.Order;
import com.cyl.manager.oms.mapper.OrderMapper;
import com.cyl.manager.oms.service.OrderOperateHistoryService;
import com.cyl.manager.ums.domain.Member;
import com.cyl.manager.ums.mapper.MemberMapper;
import com.cyl.manager.ums.service.MemberService;
import com.cyl.manager.ums.service.MemberWechatService;
import com.ruoyi.applet.mallpojo.TeacherListRequest;
import com.ruoyi.applet.service.IApiMallOrderService;
import com.ruoyi.applet.utils.WechatRefundUtil;
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.common.core.sms.AliyunSmsUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.config.LocalDataUtil;
import com.ruoyi.model.domain.*;
import com.ruoyi.model.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.websocket.WsSession;
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.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


@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;

    @Autowired
    private IAppletOrderService appletOrderService;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private WechatRefundUtil wechatRefundUtil;

    @Autowired
    private IOmsOrderEvaluationService orderEvaluationService;

    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private MemberWechatService memberWechatService;


    @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);
            statusList.add(11);
        } else {
            statusList.add(status);
        }
        PageImpl<H5OrderVO> h5OrderVOS = service.orderPageByOpenid(statusList, openId, pageable);

        Member member = memberWechatService.isRegister(openId);

        for (H5OrderVO h5OrderVO : h5OrderVOS) {
            List<OmsOrderEvaluation> list = orderEvaluationService.lambdaQuery()
                    .eq(OmsOrderEvaluation::getOrderId, h5OrderVO.getOrderId())
                    .eq(OmsOrderEvaluation::getMemberId, member.getId())
                    .list();

            h5OrderVO.setEvaluation(list.size() > 0);
        }


        return ResponseEntity.ok(h5OrderVOS);
    }

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

        H5OrderVO h5Order = service.orderDetail(orderId);


        if (h5Order == null){
            throw new RuntimeException("订单不存在");
        }

        Member member = memberWechatService.isRegister(openId);


        List<OmsOrderEvaluation> list = orderEvaluationService.lambdaQuery()
                .eq(OmsOrderEvaluation::getOrderId, h5Order.getOrderId())
                .eq(OmsOrderEvaluation::getMemberId, member.getId())
                .list();

        h5Order.setEvaluation(list.size() > 0);

        return ResponseEntity.ok(h5Order);
    }


    //修改基础订单数据
    @ApiOperation("mall-修改基础订单数据")
    @PostMapping("/updateBaseOrder")
    public AjaxResult updateBaseOrder(
                @RequestParam Long id,
                @RequestParam String contactName,
                @RequestParam String contactPhone,
                @RequestParam(required = false) String paymentMethod
            ){

        Order order = orderMapper.selectById(id);


        if (order == null){
            return AjaxResult.error("订单不存在");
        }

        order.setReceiverName(contactName);
        order.setReceiverPhone(contactPhone);

        orderMapper.updateById(order);

        return AjaxResult.success();
    }


    //根据订单标识取消订单
    @ApiOperation("mall-根据订单标识取消订单接口")
    @PostMapping("/orderCancel")
    public AjaxResult orderCancel(@RequestBody CancelOrderRequest request){

        Order order = orderMapper.selectById(request.getId());

        if (order == null){
            return AjaxResult.error("订单不存在");
        }

        Integer oldOrderStatus = order.getStatus();

        if (oldOrderStatus == 5){
            return AjaxResult.error("无效订单");
        }
        if (oldOrderStatus > 2){
            return AjaxResult.error("订单进行中无法取消/修改");
        }

        try {
            // 先取消订单
            String cancelResult = service.orderBatchCancel(request, null);

            //TODO 短信通知 通知内容需要修改一下

            AppletOrder appletOrder = appletOrderService.lambdaQuery()
                    .eq(AppletOrder::getOrderId, order.getId()).one();

            if(appletOrder != null){

                AppUsers appUsers = appUsersService.selectAppUsersByUserId(appletOrder.getUserId());

                AliyunSmsUtils.sendOrderUpdate(appUsers.getUserTelephone(), "取消订单", order.getId() + "");

            }
            AppletConfig appletConfig = appletConfigService.getByCode("admin_phone_list");

            String adminPhoneList = appletConfig.getParamValueText();
            if(StringUtils.isNotEmpty(adminPhoneList)){
                for (String phone : adminPhoneList.split(",")) {
                    AliyunSmsUtils.sendOrderUpdate(phone, "取消订单", order.getId() + "");
                }
            }

            return AjaxResult.success(cancelResult);
        } catch (Exception e) {
            log.error("订单取消或退款申请失败", e);
            return AjaxResult.error("订单取消失败：" + e.getMessage());
        }
    }




    //根据订单标识去评价
    @ApiOperation("mall-根据订单标识去评价接口")
    @GetMapping("/orderEvaluate")
    public AjaxResult orderEvaluate(OmsOrderEvaluation evaluation, String openId){
        if (evaluation == null){
            throw new RuntimeException("系统繁忙");
        }
        Member member = memberWechatService.isRegister(openId);

        evaluation.setMemberId(member.getId());
        evaluation.setCreateTime(LocalTime.now());
        service.orderEvaluate(evaluation);

        return AjaxResult.success();
    }


    //查询服务过自己的伴宠师
    @ApiOperation("mall-查询服务过自己的伴宠师")
    @GetMapping("/getTecByUser")
    public AjaxResult getTecByUser(String openId){

        if (openId == null){
            AjaxResult.error("openId不能为空");
        }

        Member member = memberWechatService.isRegister(openId);


        List<Order> orders = orderMapper.selectList(Wrappers.<Order>lambdaQuery()
                .select(Order::getTeacherId)
                .eq(Order::getMemberId, member.getId()));

        ArrayList<Long> ids = new ArrayList<>();

        for (Order order : orders) {
            if (order != null){
                ids.add(order.getTeacherId());
            }
        }

        List<AppUsers> appUsersList = appUsersService
                .lambdaQuery()
                .in(ids.size() > 0, AppUsers::getUserId, ids)
                .list();

        for (AppUsers appUsers : appUsersList) {
            appUsers.setAppletAddresseList(appletAddressService
                    .lambdaQuery()
                    .eq(AppletAddress::getUserId, appUsers.getUserId())
                    .list());

            AppletUsersTeacher appletUsersTeacher = appletUsersTeacherService.selectAppletUsersTeacherByUserId(appUsers.getUserId());
            appUsers.setAppletUsersTeacher(appletUsersTeacher);

        }

        return AjaxResult.success(appUsersList);
    }


    //查询-再来一单的历史伴宠师
//    @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 = memberWechatService.isRegister(req.getOpenId());

            Long memberId = member.getId();

            req.setMemberId(memberId);
            req.setWechatType(2);
            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);
            }
        }
    }


}
