package com.ruoyi.applet.contoller;

import cn.hutool.core.util.ObjectUtil;
import com.cyl.h5.pojo.request.CancelOrderRequest;
import com.cyl.h5.pojo.response.OrderPayResponse;
import com.cyl.h5.pojo.vo.form.AppointmentSubmitForm;
import com.cyl.h5.pojo.vo.form.OrderSubmitForm;
import com.cyl.h5.service.H5MemberAddressService;
import com.cyl.h5.service.H5MemberService;
import com.cyl.h5.service.H5OrderService;
import com.cyl.manager.oms.domain.Order;
import com.cyl.manager.oms.mapper.OrderMapper;
import com.cyl.manager.ums.domain.Member;
import com.cyl.manager.ums.pojo.dto.MemberAddressDTO;
import com.cyl.manager.ums.pojo.vo.MemberAddressVO;
import com.ruoyi.applet.service.IApiMallOrderService;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisService;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.config.LocalDataUtil;
import com.ruoyi.model.service.IAppletOrderDateFrequencyService;
import com.ruoyi.model.service.IAppletOrderService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanCopier;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/h5/appointment")
@Slf4j
public class H5AppointmentController {
    @Autowired
    private RedisService redisService;
    @Autowired
    private H5OrderService orderService;

    @Autowired
    private H5MemberService memberService;

    @Autowired
    private H5MemberAddressService h5MemberAddressService;

    @Autowired
    private IApiMallOrderService apiMallOrderService;

    @Autowired
    private OrderMapper orderMapper;

//    @ApiOperation("创建预约单")
    @PostMapping("/add")
    public AjaxResult submit(@RequestBody AppointmentSubmitForm form) {
        log.info("0 开始创建预约单：" + form);

        //1、查询会员
        Member member = (Member) LocalDataUtil.getVar(Constants.MEMBER_INFO);
        if(ObjectUtil.isNull(member)){
            return AjaxResult.error("token校验失败");
        }

        //2、新建会员地址
        log.info("2 新建会员地址：" + member);
        MemberAddressVO memberAddressVO =  h5MemberAddressService.selectById(form.getAddressId());
        if(ObjectUtil.isNull(memberAddressVO)){
            return AjaxResult.error("地址不存在");
        }
        Long memberId = member.getId();
        String redisKey = "h5_order_add" + memberId;
        String redisValue = memberId + "_" + System.currentTimeMillis();
        try{

            //修改订单逻辑，先取消，在生成新的订单
            if (form.getOrderId() != null){
                Order order = orderMapper.selectById(form.getOrderId());

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

                Integer oldOrderStatus = order.getStatus();

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

                apiMallOrderService.orderBatchCancel(CancelOrderRequest.builder()
                        .id(form.getOrderId())
                        .remark("修改订单退回上一笔钱")
                        .build(), null);
            }

            //3、提交订单
            log.info("3 开始提交订单：" + memberAddressVO);
            OrderSubmitForm orderSubmitForm = new OrderSubmitForm();
            final BeanCopier beanCopier = BeanCopier.create(AppointmentSubmitForm.class, OrderSubmitForm.class, false);
            beanCopier.copy(form, orderSubmitForm, null);
            orderSubmitForm.setAddressId(memberAddressVO.getId());

            //lzx增加的两个字段
            orderSubmitForm.setTeacherId(form.getTeacherId());
            orderSubmitForm.setCompanionLevel(form.getCompanionLevel());

            redisService.lock(redisKey, redisValue, 60);
            Order order = orderService.submit(orderSubmitForm);

            //4、提交服务信息
//            log.info("4 提交服务信息：" + order);
//            orderService.submitServiceInfo(order.getId(), form.getService());
//            orderService.submitOrderService(order.getId(), form.getPetOrderServices());
            //TODO 4、创建支付预付单
            log.info("4 创建支付预付单......");
            OrderPayResponse response = orderService.orderCreateAndPay(order, member, form.getOpenId());

            log.info("5 创建订单完成：" + response);
            return AjaxResult.successData(response);
            //return ResponseEntity.ok(response);
        }catch (ServiceException e){
            log.error("创建订单方法异常", e);
            throw new ServiceException(e.getMessage());
        }catch (Exception e){
            log.error("创建订单方法异常", e);
            throw new RuntimeException("服务繁忙，稍后再试");
        }finally {
            try {
                redisService.unLock(redisKey, redisValue);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
