package com.gxwebsoft.shop.service.impl;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxwebsoft.apps.service.EquipmentGoodsService;
import com.gxwebsoft.apps.service.EquipmentService;
import com.gxwebsoft.common.core.utils.CacheClient;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.shop.entity.Order;
import com.gxwebsoft.shop.entity.OrderGoods;
import com.gxwebsoft.shop.mapper.OrderMapper;
import com.gxwebsoft.shop.param.OrderParam;
import com.gxwebsoft.shop.service.OrderGoodsService;
import com.gxwebsoft.shop.service.OrderService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.gxwebsoft.common.core.constants.OrderConstants.*;

/**
 * 订单记录表Service实现
 *
 * @author WebSoft
 * @since 2022-11-16 11:25:58
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {
  @Resource
  private EquipmentService equipmentService;
  @Resource
  private EquipmentGoodsService equipmentGoodsService;
  @Resource
  private OrderService orderService;
  @Resource
  private OrderGoodsService orderGoodsService;
  @Resource
  private CacheClient cacheClient;

  @Override
  public PageResult<Order> pageRel(OrderParam param) {
    PageParam<Order, OrderParam> page = new PageParam<>(param);
    page.setDefaultOrder("delivery_time desc,create_time desc");
    List<Order> list = baseMapper.selectPageRel(page, param);
    // 是否查询订单商品
    if(param.getShowGoodsList() != null){
      list.forEach(d -> {
        final List<OrderGoods> goodsList = orderGoodsService.list(new LambdaQueryWrapper<OrderGoods>().eq(OrderGoods::getOrderId, d.getOrderId()).gt(OrderGoods::getTotalNum, 0));
        goodsList.forEach(g -> {
          // 比较时间前后判断是否允许取消报餐
          SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
          Date newDate = DateUtil.offset(d.getDeliveryTime(), DateField.HOUR, 21);
          try {
            Date date1 = df.parse(newDate.toString());
            Date date2 = df.parse(DateUtil.now());
            g.setIsCancel(date1.after(date2));
            final boolean before = date1.after(date2);
            System.out.println("before = " + before);
          } catch (ParseException e) {
            e.printStackTrace();
          }
        });
        d.setGoodsList(goodsList);
      });
    }
    return new PageResult<>(list, page.getTotal());
  }

  @Override
  public List<Order> listRel(OrderParam param) {
    List<Order> list = baseMapper.selectListRel(param);
    // 排序
    PageParam<Order, OrderParam> page = new PageParam<>();
    page.setDefaultOrder("create_time desc");
    return page.sortRecords(list);
  }

  @Override
  public Order getByIdRel(Integer orderId) {
    OrderParam param = new OrderParam();
    param.setOrderId(orderId);
    return param.getOne(baseMapper.selectListRel(param));
  }

  @Override
  public Order getByOutTradeNo(String outTradeNo) {
    OrderParam param = new OrderParam();
    param.setOrderNo(outTradeNo);
    return param.getOne(baseMapper.getOne(param));
  }

  /**
   * 支付成功后处理的业务(通联支付)
   */
  @Override
  public boolean allinPay(Map<String, String> params) {
    cacheClient.set(":payInfo", params.toString());
    final String outTradeNo = params.get("merchantOrderNo");
    final String trxamt = params.get("trxamt");
    final String merchantNo = params.get("merchantNo");
    final String chnltrxid = params.get("chnltrxid");
    final String payTime = params.get("payTime");
    final String fee = params.get("fee");
    final String trxStatus = params.get("trxstatus");

    // 1.是否为商城订单
    Order order = orderService.getByOutTradeNo(outTradeNo);
    if (order == null) {
      return false;
    }

    // 2.订单金额是否一致
    final BigDecimal payPrice = new BigDecimal(trxamt).divide(new BigDecimal(100));

    // 3.订单商户是否一致
//    if (!merchantNo.equals(order.getMerchantCode())) {
//      return false;
//    }

    // 4.验证appId是否一致
//    String appId = params.get("app_id");
//    System.out.println("验证appId是否一致"+appId);
//    String appIdPro = "2021003156628508";
//    if (!appId.equals(appIdPro)) {
//      System.out.println("验证appId校验失败");
//      return false;
//    }
    // 5.判断交易状态
    if (!"2".equals(trxStatus)) {
      return false;
    }
    // 6.修改订单状态
    OrderParam orderParam = new OrderParam();
    orderParam.setOrderNo(outTradeNo);
    orderParam.setPayStatus(PAY_STATUS_SUCCESS);
    orderParam.setPayPrice(payPrice);
    //
    return baseMapper.updatePayStatus(orderParam);
  }

  @Override
  public void removeOrderByTimeOut() {
    final Integer pay_status = query().eq("order_no", "2023121205993791").count();
    System.out.println("处理过期订单 = " + pay_status);
  }

  @Override
  public boolean updateByIdRel(Order order) {
    return baseMapper.updateByIdRel(order);
  }

    @Override
    public PageResult<Order> selectPageSettled(OrderParam param) {
      PageParam<Order, OrderParam> page = new PageParam<>(param);
      //page.setDefaultOrder("create_time desc");
      List<Order> list = baseMapper.selectPageSettled(page, param);
      return new PageResult<>(list, page.getTotal());
    }

  @Override
  public void updateByIdSettled(Order order) {
    baseMapper.updateByIdSettled(order);
  }


  /**
   * 支付成功后处理的业务
   */
  @Transactional(rollbackFor = {Exception.class})
  @Override
  public void paySuccess(AlipayTradeQueryResponse params) {
    System.out.println("支付成功后处理的业务");
    String outTradeNo = params.getOutTradeNo();
    String totalAmount = params.getTotalAmount();
    String receiptAmount = params.getReceiptAmount();
    // 1.是否为商城订单
    Order order = orderService.getByOutTradeNo(outTradeNo);
    if (order == null) {
      System.out.println("订单不存在！");
      return;
    }
    // 2.订单金额是否一致
    // 3.订单商户是否一致
    // 4.验证appId是否一致
    // 5.判断交易状态
    String tradeStatus = params.getTradeStatus();
    if (!"TRADE_SUCCESS".equals(tradeStatus)) {
      System.out.println("支付未成功");
      return;
    }

    // 6.修改订单状态
    order.setPayStatus(PAY_STATUS_SUCCESS);
    order.setPayMethod(PAY_METHOD_ALIPAY);
    order.setReceiptAmount(new BigDecimal(receiptAmount));
    order.setPayTime(DateUtil.date());
    order.setExpirationTime(DateUtil.nextMonth());
    orderService.updateById(order);

    // 6. 续租订单
    if (order.getRentOrderId() > 0) {
      // 主订单
      Order parentOrder = orderService.getById(order.getRentOrderId());
      // 更新过期时间延长一个月
      Date expirationTime = parentOrder.getExpirationTime();
      DateTime nextMonthTime = DateUtil.offsetMonth(expirationTime, 1);
      parentOrder.setExpirationTime(nextMonthTime);
      orderService.updateById(parentOrder);
      // 保存续费订单状态
      order.setDeliveryStatus(DELIVERY_STATUS_YES);
      order.setReceiptStatus(RECEIPT_STATUS_YES);
      order.setOrderStatus(ORDER_STATUS_COMPLETED);
      order.setStartTime(expirationTime);
      order.setExpirationTime(nextMonthTime);
      orderService.updateById(order);
    }
  }

  /**
   * 批量查询订单的关联商品
   *
   * @param orders 商品集合
   */
  private void selectOrderGoods(List<Order> orders) {
    if (orders != null && orders.size() > 0) {
      List<Integer> orderIds = orders.stream().map(Order::getOrderId).collect(Collectors.toList());
      List<OrderGoods> orderGoods = orderGoodsService.listByOrderIds(orderIds);
      for (Order order : orders) {
        List<OrderGoods> goodsList = orderGoods.stream().filter(d -> order.getOrderId().equals(d.getOrderId()))
          .collect(Collectors.toList());
        order.setGoodsList(goodsList);
      }
    }
  }

}
