package com.neusoft.smart.pos.order.repository;

import com.neusoft.smart.pos.constants.DictionaryConstant;
import com.neusoft.smart.pos.framework.utils.IdGenerateUtils;
import com.neusoft.smart.pos.framework.utils.LocalDateTimeUtils;
import com.neusoft.smart.pos.order.constants.TradeConstant;
import com.neusoft.smart.pos.order.persistent.domain.*;
import com.neusoft.smart.pos.order.persistent.mapper.OrderMasterExtMapper;
import com.neusoft.smart.pos.order.persistent.mapper.OrderMasterMapper;
import com.neusoft.smart.pos.payorder.persistent.domain.PayOrderExample;
import com.neusoft.smart.pos.payorder.persistent.domain.PayRefundOrderExample;
import com.neusoft.smart.pos.utils.PosDeviceRedisUtils;
import com.neusoft.smart.pos.utils.RequestHeaderUtil;
import lombok.val;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

@Component
public class OrderMasterRepository {

    @Resource
    private OrderMasterMapper orderMasterMapper;

    @Resource
    private OrderMasterExtMapper orderMasterExtMapper;

    /**
     * 订单信息保存方法
     * @return
     */
    public Integer saveOrder(OrderMaster orderMaster){
        //存储设备别名
        if(!StringUtils.isEmpty(orderMaster.getSerialNo())){
            orderMaster.setDeviceName(PosDeviceRedisUtils.getDeviceInfoBySerialNo(orderMaster.getSerialNo()).getAlias());
        }
        if(!StringUtils.isEmpty(RequestHeaderUtil.getUsername())){
            orderMaster.setCustomerNumber(String.valueOf(RequestHeaderUtil.getUserId()));
            orderMaster.setCreatedBy(RequestHeaderUtil.getUsername());
        }

        orderMaster.setOrderStatus(DictionaryConstant.ORDER_STATUS_DFK.getCode());
        val currentLocalTime = LocalDateTimeUtils.getNow();
        orderMaster.setCreatedAt(LocalDateTimeUtils.convertLocalDateTimeToDate(currentLocalTime));

        //计算订单失效时间，默认为2小时
        if(null == orderMaster.getTimeExpire()){
            val timeExpire = LocalDateTimeUtils.plusMinutes(currentLocalTime, TradeConstant.ORDER_DEFAULT_TIME_EXPIRE);
            orderMaster.setTimeExpire(LocalDateTimeUtils.convertLocalDateTimeToDate(timeExpire));
        }
        return orderMasterMapper.insertSelective(orderMaster);
    }

    /**
     * 订单信息状态方法
     *
     * @param orderNumber 订单编号
     * @return 是否更新成功
     */
    public Boolean updateOrderStatusByOrderNumber(String orderNumber, String orderStatus) {
        val orderMaster = new OrderMaster();
        orderMaster.setOrderStatus(orderStatus);
        orderMaster.setUpdatedAt(new Date());
        if(!StringUtils.isEmpty(RequestHeaderUtil.getUsername())){
            orderMaster.setUpdatedBy(RequestHeaderUtil.getUsername());
        }
        val example = new OrderMasterExample();
        example.createCriteria().andOrderNumberEqualTo(orderNumber);
        val result = orderMasterMapper.updateByExampleSelective(orderMaster, example);
        return result > 0 ? true : false;
    }
    /**
     * 订单信息状态方法
     *
     * @param orderNumber 订单编号
     * @return 是否更新成功
     */
    public Boolean updateOrderStatusByOrderNumber(String orderNumber, int orgId, int shopId, String orderStatus) {
        val orderMaster = new OrderMaster();
        orderMaster.setOrderStatus(orderStatus);
        orderMaster.setUpdatedAt(new Date());
        if(!StringUtils.isEmpty(RequestHeaderUtil.getUsername())){
            orderMaster.setUpdatedBy(RequestHeaderUtil.getUsername());
        }
        val example = new OrderMasterExample();
        example.createCriteria().andOrderNumberEqualTo(orderNumber).andOrgIdEqualTo(orgId).andShopIdEqualTo(shopId);
        val result = orderMasterMapper.updateByExampleSelective(orderMaster, example);
        return result > 0 ? true : false;
    }
    /**
     * 订单信息更新方法
     *
     * @param orderMaster 订单信息
     * @return 是否更新成功
     */
    public Boolean updateOrder(OrderMaster orderMaster){
        orderMaster.setUpdatedAt(new Date());
        if(!StringUtils.isEmpty(RequestHeaderUtil.getUsername())){
            orderMaster.setUpdatedBy(RequestHeaderUtil.getUsername());
        }
        val example = new OrderMasterExample();
        example.createCriteria().andOrderNumberEqualTo(orderMaster.getOrderNumber());
        val result = orderMasterMapper.updateByExampleSelective(orderMaster, example);
        return result > 0 ? true : false;
    }

    public String computeOrderStatus(String orderNumber) {
        //TODO:查询全部支付订单金额和全部退款订单金额 根据规则计算订单状态
        String orderStatus = DictionaryConstant.ORDER_UPDATE_STATUS_DFK.getCode();
        return orderStatus;
    }


    /**
     * 订单信息查询方法
     * @param orderNumber：订单编号
     * @return
     */
    public OrderMaster queryOrderByOrderNumber(String orderNumber){
        val example = new OrderMasterExample();
        example.createCriteria().andOrderNumberEqualTo(orderNumber);
        val orders = orderMasterMapper.selectByExample(example);
        return orders.size()>0?orders.get(0):null;
    }

    /**
     * 订单信息查询方法
     * @param orgId：集团编号
     * @param shopId：门店编号
     * @param orderNumber：订单编号
     * @return
     */
    public OrderMaster queryOrderByOrderNumber(Integer orgId,Integer shopId,String orderNumber){
        val example = new OrderMasterExample();
        example.createCriteria().andOrderNumberEqualTo(orderNumber)
                .andShopIdEqualTo(shopId);
        val orders = orderMasterMapper.selectByExample(example);
        return orders.size()>0?orders.get(0):null;
    }

    /**
     * 订单信息查询方法
     * @param orgId：集团编号
     * @param shopId：门店编号
     * @param orderNumber：订单编号
     * @return
     */
    public OrderMaster queryOrderByOrderNumber(Integer orgId,Integer shopId,String orderNumber,String orderType){
        val example = new OrderMasterExample();
        example.createCriteria().andOrderNumberEqualTo(orderNumber)
                .andShopIdEqualTo(shopId)
                .andOrderTypeEqualTo(orderType);
        val orders = orderMasterMapper.selectByExample(example);
        return orders.size()>0?orders.get(0):null;
    }

    public List<OrderMasterExt> queryShopOrderSummary(OrderMasterExtExample example){
        return orderMasterExtMapper.queryShopOrderSummary(example);
    }

    public List<Map> queryShopOrderDetails4Web(OrderMasterExample example){
        return orderMasterExtMapper.queryShopOrderDetails(example);
    }

    /**
     * 查询门店订单详情统计总金额
     * @param example
     * @return
     */
    public List<Map> queryShopPayOrderList(OrderMasterExample example){
        return orderMasterExtMapper.queryShopPayOrderList(example);
    }

    /**
     * 查询门店订单详情汇总信息
     * @param example
     * @return
     */
    public List<Map> queryShopDayOrder(OrderMasterExample example){
        return orderMasterExtMapper.queryShopDayOrder(example);
    }

    /**
     * 查询门店支付方式统计
     * @param example
     * @return
     */
    public List<Map> queryShopPayTypeTradeList(OrderMasterExample example){
        return orderMasterExtMapper.queryShopPayTypeTradeList(example);
    }

    /**
     * 查询门店订单详情统计总金额
     * @param example
     * @return
     */
    public List<Map> queryShopTradeOrderList(OrderMasterExample example){
        return orderMasterExtMapper.queryShopTradeOrderList(example);
    }

    public Map queryUsernameByCustomerNumber(Map param) {
        return orderMasterExtMapper.queryUsernameByCustomerNumber(param);
    }

    public List<Map> selectTradeSummary(OrderMasterExample example) {
        return orderMasterExtMapper.selectTradeSummary(example);
    }
//    /**
//     * 订单信息更新方法
//     * @param orderNumber：订单编号
//     * @return
//     */
//    public Boolean updateOrderStatusByOrderNumber(String orderNumber,String orderStatus,String payStatus,String payType){
//        return updateOrderStatusByOrderNumber(orderNumber,orderStatus,payStatus,payType,null,null,null,null);
//    }
//
//    /**
//     * 订单信息更新方法
//     * @param orderNumber：订单编号
//     * @return
//     */
//    public Boolean updateOrderStatusByOrderNumber(String orderNumber,String orderStatus,String payStatus,String payType,String retrvlRefNo,String oriTraceNo,String transDate,String oriBatchNo){
//        val orderMaster = new OrderMaster();
//        orderMaster.setOrderStatus(orderStatus);
//        orderMaster.setPayStatus(payStatus);
//        orderMaster.setUpdatedAt(new Date());
//        if(!StringUtils.isEmpty(payType)){
//            orderMaster.setPayType(payType);
//        }
//        if(!StringUtils.isEmpty(retrvlRefNo)){
//            orderMaster.setRetrvlRefNo(retrvlRefNo);
//        }
//        if(!StringUtils.isEmpty(oriTraceNo)){
//            orderMaster.setOriTraceNo(oriTraceNo);
//        }
//        if(!StringUtils.isEmpty(transDate)){
//            orderMaster.setTransDate(transDate);
//        }
//        if(!StringUtils.isEmpty(oriBatchNo)){
//            orderMaster.setOriBatchNo(oriBatchNo);
//        }
//        if(payStatus.equals(DictionaryConstant.PAY_STATUS_YFK.getCode())){
//            orderMaster.setPaidTime(new Date());
//        }
//        val example = new OrderMasterExample();
//        example.createCriteria().andOrderNumberEqualTo(orderNumber);
//        val result = orderMasterMapper.updateByExampleSelective(orderMaster,example);
//        return result>0?true:false;
//    }

    /**
     * 订单信息更新方法
     * @param orderNumber：订单编号
     * @return
     */
    public Boolean updatePrinterFlagByOrderNumber(String orderNumber){
        val orderMaster = new OrderMaster();
        orderMaster.setPrinterFlag("2");
        val example = new OrderMasterExample();
        example.createCriteria().andOrderNumberEqualTo(orderNumber);
        val result = orderMasterMapper.updateByExampleSelective(orderMaster,example);
        return result>0?true:false;
    }

//
//    /**
//     * 订单信息更新方法
//     * @param orderNumber：订单编号
//     * @return
//     */
//    public Boolean updateOrderStatusByOrderNumber(String orderNumber,String orderStatus,String payStatus,String payType,Date paidTime){
//        val orderMaster = new OrderMaster();
//        orderMaster.setOrderStatus(orderStatus);
//        orderMaster.setPayStatus(payStatus);
//        orderMaster.setUpdatedAt(new Date());
//        if(!StringUtils.isEmpty(payType)){
//            orderMaster.setPayType(payType);
//        }
//        if(payStatus.equals(DictionaryConstant.PAY_STATUS_YFK.getCode())){
//            orderMaster.setPaidTime(paidTime);
//        }
//        val example = new OrderMasterExample();
//        example.createCriteria().andOrderNumberEqualTo(orderNumber);
//        val result = orderMasterMapper.updateByExampleSelective(orderMaster,example);
//        return result>0?true:false;
//    }
//
//    /**
//     * 订单信息更新方法
//     * @param orderNumber：订单编号
//     * @return
//     */
//    public Boolean updateOrderPayStatusByOrderNumber(String orderNumber,String orderStatus,String payStatus,String payType){
//        val orderMaster = new OrderMaster();
//        orderMaster.setOrderStatus(orderStatus);
//        orderMaster.setPayStatus(payStatus);
//        orderMaster.setUpdatedAt(new Date());
//        if(!StringUtils.isEmpty(payType)){
//            orderMaster.setPayType(payType);
//        }
//        if(payStatus.equals(DictionaryConstant.PAY_STATUS_YFK.getCode())){
//            orderMaster.setPaidTime(new Date());
//        }
//        val example = new OrderMasterExample();
//        example.createCriteria().andOrderNumberEqualTo(orderNumber);
//        val result = orderMasterMapper.updateByExampleSelective(orderMaster,example);
//        return result>0?true:false;
//    }

    /**
     * 更新订单支付方式方法
     * @param orderNumber：订单编号
     * @return
     */
    public Boolean cancelOrder(String orderNumber){
        val orderMaster = new OrderMaster();
        orderMaster.setOrderStatus(DictionaryConstant.ORDER_STATUS_DDQX.getCode());
        orderMaster.setUpdatedAt(new Date());
        if(!StringUtils.isEmpty(RequestHeaderUtil.getUsername())){
            orderMaster.setUpdatedBy(RequestHeaderUtil.getUsername());
        }
        val example = new OrderMasterExample();
        example.createCriteria()
                .andOrderNumberEqualTo(orderNumber);
        //.andOrderStatusEqualTo(DictionaryConstant.ORDER_STATUS_DFK.getCode());
        val result = orderMasterMapper.updateByExampleSelective(orderMaster,example);
        return result>0?true:false;
    }

//    /**
//     * 订单信息查询方法
//     * @param orderNumber：订单编号
//     * @return
//     */
//    public Boolean updateOrderStatusByOrderNumber(String orderNumber,String orderStatus,String payStatus){
//        return updateOrderStatusByOrderNumber(orderNumber,orderStatus,payStatus,null,null,null,null,null);
//    }

    /**
     * 订单号生成方法
     * @return
     */
    public String generateOrderNumber(){
        String orderNumber;
        while(true){
            orderNumber = IdGenerateUtils.generateOrderNumber();
            val example = new OrderMasterExample();
            example.createCriteria()
                    .andOrderNumberEqualTo(orderNumber)
                    .andCreatedAtGreaterThanOrEqualTo(LocalDateTimeUtils.convertLocalDateTimeToDate(LocalDateTimeUtils.getCurrentDayStart()));
            val orderInfos = orderMasterMapper.selectByExample(example);
            if(null == orderInfos || orderInfos.size() == 0){
                break;
            }
        }
        return orderNumber;
    }


    /**
     * 查询门店订单详情统计信息
     * @param example
     * @return
     */
    public List<OrderMaster> queryShopOrderDetails(OrderMasterExample example){
        return orderMasterMapper.selectByExample(example);
    }

    public Integer queryMemberOrderDetailsCount(OrderMasterExample example){
        return orderMasterExtMapper.queryMemberOrderDetailsCount(example);
    }

    public List<OrderMasterMemberExt> queryMemberOrderDetails(OrderMasterExample example){
        return orderMasterExtMapper.queryMemberOrderDetails(example);
    }

    public Map queryMemberOrderDetailsTotalAmount(OrderMasterExample example) {
        return orderMasterExtMapper.queryMemberOrderDetailsTotalAmount(example);
    }

    /**
     * 查询门店订单详情统计信息
     * @param example
     * @return
     */
    public Integer queryShopOrderDetailsCount(OrderMasterExample example){
        return orderMasterMapper.countByExample(example);
    }

    /**
     * 查询门店订单详情统计信息
     * @param example
     * @return
     */
    public Integer countShopOrderDetailsLeftJoinPayOrderCount(OrderMasterExample example){
        return Integer.parseInt(orderMasterExtMapper.countShopOrderDetailsLeftJoinPayOrderCount(example).get("count").toString());
    }

    /**
     * 订单信息补录保存方法
     * @return
     */
    public void saveRecordOrder(List<OrderMaster> orderMasterList){
        orderMasterMapper.batchInsert(orderMasterList);
    }

    /**
     * 订单删除使用方法
     * @return
     */
    public Integer deleteOrderMasterByOrderNumber(String orderNumber){
        OrderMasterExample example = new OrderMasterExample();
        example.createCriteria().andOrderNumberEqualTo(orderNumber);
        return orderMasterMapper.deleteByExample(example);
    }

    /**
     * 订单删除使用方法
     * @return
     */
    public Integer deleteOrderMasterByOrderType(String orderType){
        OrderMasterExample example = new OrderMasterExample();
        example.createCriteria().andOrderTypeEqualTo(orderType);
        return orderMasterMapper.deleteByExample(example);
    }


    public Map queryShopOrderDetailsTotalAmount(OrderMasterExample example) {
        return orderMasterExtMapper.queryShopOrderDetailsTotalAmount(example);
    }

    public Map queryShopOrderDetailsLeftJoinPayOrderTotalAmount(OrderMasterExample example) {
        return orderMasterExtMapper.queryShopOrderDetailsLeftJoinPayOrderTotalAmount(example);
    }

    public Map queryShopOrderDetailsTotal(OrderMasterExample example) {
        return orderMasterExtMapper.queryShopOrderDetailsTotal(example);
    }

    public Long queryHasPayAmountSum(String orderNumber) {
        PayOrderExample example = new PayOrderExample();
        example.createCriteria().andMOrderNumberEqualTo(orderNumber).andPayStatusEqualTo(DictionaryConstant.PAY_STATUS_YFK.getCode());
        return orderMasterExtMapper.queryHasPayAmountSum(example).longValue();
    }


    public Long queryDiscountAmountSum(String orderNumber) {
        PayOrderExample example = new PayOrderExample();
        example.createCriteria().andMOrderNumberEqualTo(orderNumber).andPayStatusEqualTo(DictionaryConstant.PAY_STATUS_YFK.getCode()).andPayTypeEqualTo(DictionaryConstant.PAY_TYPE_DISCOUNT.getCode());
        return orderMasterExtMapper.queryHasPayAmountSum(example).longValue();
    }

    public Long queryCouponsAmountSum(String orderNumber) {
        PayOrderExample example = new PayOrderExample();
        example.createCriteria().andMOrderNumberEqualTo(orderNumber).andPayStatusEqualTo(DictionaryConstant.PAY_STATUS_YFK.getCode()).andPayTypeEqualTo(DictionaryConstant.PAY_TYPE_FM_COUPON.getCode());
        return orderMasterExtMapper.queryHasPayAmountSum(example).longValue();
    }

    public Long queryHasRefundAmountSum(String orderNumber) {
        PayRefundOrderExample example = new PayRefundOrderExample();
        example.createCriteria().andMOrderNumberEqualTo(orderNumber).andRefundStatusEqualTo(DictionaryConstant.PAY_REFUND_STATUS__YTK.getCode());
        return orderMasterExtMapper.queryHasRefundAmountSum(example).longValue();
    }

    public Long queryHasRefundAmountSumByTradeId(String tradeId) {
        PayRefundOrderExample example = new PayRefundOrderExample();
        example.createCriteria().andTradeIdEqualTo(tradeId).andRefundStatusEqualTo(DictionaryConstant.PAY_REFUND_STATUS__YTK.getCode());
        return orderMasterExtMapper.queryHasRefundAmountSum(example).longValue();
    }

    public Long queryHasRefundAmountSumByRefundNum(String refundNumber) {
        PayRefundOrderExample example = new PayRefundOrderExample();
        example.createCriteria().andRefundNumberEqualTo(refundNumber).andRefundStatusEqualTo(DictionaryConstant.PAY_REFUND_STATUS__YTK.getCode());
        return orderMasterExtMapper.queryHasRefundAmountSum(example).longValue();
    }

    public List<Map> selectLoginLogoutRecordList(Integer orgId, Date startTimeTemp, Date endTimeTemp, String operator) {
        Map<String, Object> params = new HashMap<>();
        params.put("org_id", orgId);
        params.put("start_time", startTimeTemp);
        params.put("end_time", endTimeTemp);
        if(operator != null && !operator.equals("")) {
            params.put("username",operator);
        }
        List<Map> rs =  orderMasterExtMapper.selectLoginLogoutRecordList(params);
        return rs.size()>0? rs:new ArrayList<>();
    }

    public List<Map> getOrderPayDetail(String orderNumber) {
        Map<String, Object> params = new HashMap<>();
        params.put("m_order_number", orderNumber);
        List<Map> rs =  orderMasterExtMapper.getOrderPayDetail(params);
        return rs.size()>0? rs:new ArrayList<>();
    }

    public List<String> querySpecialPayTypeShopOrderNumbers4Web(OrderMasterExample example4JoinO) {
        List<Map> maps =  orderMasterExtMapper.querySpecialPayTypeShopOrderNumbers4Web(example4JoinO);
        List<String> rs = new ArrayList<>();
        if(maps!=null) {
            maps.forEach(o->{rs.add(o.get("orderNumber").toString());});
        }
        return rs;
    }

    public Map<String,Object> queryBalanceAndPoint(String tradeId) {
        Map<String, Object> params = new HashMap<>();
        params.put("trade_id", tradeId);
        List<Map> rs =  orderMasterExtMapper.queryBalanceAndPoint(params);
        return rs.size()>0? rs.get(0):null;
    }

    public Map<String,Object> queryShopNameAndOrgName(int shopId) {
        Map<String, Object> params = new HashMap<>();
        params.put("shop_id", shopId);
        List<Map> rs =  orderMasterExtMapper.queryShopNameAndOrgName(params);
        return rs.size()>0? rs.get(0):null;
    }

}
