package com.iformall.service.impl;

import java.util.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.iformall.common.ErrorCode;
import com.iformall.domain.po.WxCUser;
import com.iformall.domain.po.WxCoupon;
import com.iformall.domain.po.WxOrder;
import com.iformall.domain.po.WxOrderPress;
import com.iformall.enums.EnumOrderPressStatus;
import com.iformall.enums.EnumOrderPressType;
import com.iformall.enums.EnumOrderStatus;
import com.iformall.exception.MallinkException;
import com.iformall.mapper.WxOrderMapper;
import com.iformall.mapper.WxOrderPressMapper;
import com.iformall.service.WxOrderPressService;
import com.iformall.utils.PressUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.iformall.common.IdWorker;

@Service
public class WxOrderPressServiceImpl implements WxOrderPressService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
    WxOrderPressMapper wxOrderPressMapper;

	@Autowired
    WxOrderMapper wxOrderMapper;


    @Override
    public PageInfo<WxOrderPress> listAsPage(WxOrderPress record, Integer pageIndex, Integer pageSize) {
        return PageHelper.startPage(pageIndex, pageSize).doSelectPageInfo(() -> wxOrderPressMapper.findList(record));
    }

    @Override
    public WxOrderPress getById(Long id) {
        return wxOrderPressMapper.selectByPrimaryKey(id);
    }

    @Override
    public void saveOrUpdate(WxOrderPress record) {
        if (record.getId() == null) {
            //record.setId(UUID.randomUUID().toString().replaceAll("-", ""));
            final IdWorker idWorker = IdWorker.get();
        	record.setId(idWorker.nextId());
            wxOrderPressMapper.insertSelective(record);
        } else {
            wxOrderPressMapper.updateByPrimaryKeySelective(record);
        }
    }

    @Override
    public void deleteById(Long id) {
        wxOrderPressMapper.deleteByPrimaryKey(id);
    }


    @Override
    public void pressCouponJoin(WxOrder order, WxCoupon coupon, WxCUser user) {
        final IdWorker idWorker = IdWorker.get();
        Date curDate = new Date();
        // 检查此人是否已参与砍价
        WxOrderPress orderPressQ = new WxOrderPress();
        orderPressQ.setTenantId(order.getTenantId());
        orderPressQ.setOrderId(order.getId());
        orderPressQ.setUserId(user.getId());
        int count = wxOrderPressMapper.selectCount(orderPressQ);
        if(count >= 1) {
            logger.error("用户已参与砍价: " + user.getId());
            throw new MallinkException(ErrorCode.COUPON_PRESS_IS_EXIST);
        }

        // 添加 wx_order_press
        int total = coupon.getPrice() - coupon.getSalePrice();
        int left_total = order.getPressCurrentValue();
        WxOrderPress orderPress = new WxOrderPress();
        orderPress.setId(idWorker.nextId());
        orderPress.setTenantId(order.getTenantId());
        orderPress.setOrderId(order.getId());
        orderPress.setUserId(user.getId());
        orderPress.setCreateDate(curDate);
        orderPress.setFirst(EnumOrderPressType.NORMAL.getCode());
        orderPress.setPressValue(PressUtils.stateLessPressValue(total, left_total, coupon.getPressLimitNum(), order.getPressCurrentNum()));

        try {
            // 保存订单
            wxOrderPressMapper.insertSelective(orderPress);
        } catch (RuntimeException e) {
            logger.error("保存砍价记录Error：" + e.getMessage());
            throw new MallinkException(ErrorCode.DB_FAIL);
        }

        // 更新砍价信息
        Integer index = order.getPressCurrentNum() + 1;
        WxOrder orderUpdatePress = new WxOrder();
        orderUpdatePress.setId(order.getId());
        orderUpdatePress.setPressCurrentNum(index);
        orderUpdatePress.setPressCurrentValue(left_total - orderPress.getPressValue());
        if(index.equals(coupon.getPressLimitNum())) {
            orderUpdatePress.setOrderStatus(EnumOrderStatus.ORDER_STATUS_PRESS_COMPLETE.getCode());
            orderUpdatePress.setPayment(coupon.getSalePrice());
        } else {
            orderUpdatePress.setOrderStatus(EnumOrderStatus.ORDER_STATUS_PRESSING.getCode());
        }
        orderUpdatePress.setUpdateDate(new Date());
        try {
            // 保存订单
            wxOrderMapper.updateByPrimaryKeySelective(orderUpdatePress);
        } catch (RuntimeException e) {
            logger.error("更新订单Error：" + e.getMessage());
            throw new MallinkException(ErrorCode.DB_FAIL);
        }
    }

    @Override
    public int pressCouponStatus(WxOrder order, WxCUser user) {
        // 检查此人是否已参与砍价
        WxOrderPress orderPressQ = new WxOrderPress();
        orderPressQ.setTenantId(order.getTenantId());
        orderPressQ.setOrderId(order.getId());
        orderPressQ.setUserId(user.getId());
        int count = wxOrderPressMapper.selectCount(orderPressQ);
        if(count >= 1) {
            logger.info("用户已参与砍价: " + user.getId());
            return EnumOrderPressStatus.HAD_JOIN.getCode();
        }
        return EnumOrderPressStatus.NOT_JOIN.getCode();
    }
    
    
    
    
    
}
