package com.neusoft.smart.pos.trade.service;


import com.neusoft.smart.pos.constants.DictionaryConstant;
import com.neusoft.smart.pos.dto.trade.request.GetMemberOrdersRequest;
import com.neusoft.smart.pos.dto.trade.response.GetMemberOrdersResponse;
import com.neusoft.smart.pos.dto.trade.response.GetMemberOrdersResponse.MemberOrder;
import com.neusoft.smart.pos.dto.trade.response.GetMemberOrdersResponse.MemberOrderDetail;
import com.neusoft.smart.pos.framework.bean.PaginationExtendBean;
import com.neusoft.smart.pos.framework.exception.BusinessCommonException;
import com.neusoft.smart.pos.framework.utils.DateUtils;
import com.neusoft.smart.pos.framework.utils.ListUtils;
import com.neusoft.smart.pos.framework.utils.MapBeanUtils;
import com.neusoft.smart.pos.framework.utils.SignUtils;
import com.neusoft.smart.pos.order.constants.TradeErrorCode;
import com.neusoft.smart.pos.order.persistent.domain.OrderMaster;
import com.neusoft.smart.pos.order.persistent.domain.OrderMasterExample;
import com.neusoft.smart.pos.order.persistent.domain.OrderMasterMemberExt;
import com.neusoft.smart.pos.order.persistent.domain.OrderTransaction;
import com.neusoft.smart.pos.order.repository.OrderMasterRepository;
import com.neusoft.smart.pos.order.repository.OrderTransactionRepository;
import com.neusoft.smart.pos.trade.persistent.domain.TradeMchInfo;
import com.neusoft.smart.pos.trade.repository.PayTypeRepository;
import com.neusoft.smart.pos.trade.repository.TradeMchInfoRepository;
import lombok.val;
import org.aspectj.weaver.patterns.HasMemberTypePattern;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("mchOrderService")
public class MchOrderService {

    @Autowired
    private OrderMasterRepository orderMasterRepository;

    @Autowired
    private OrderTransactionRepository orderTransactionRepository;

    @Autowired
    private PayTypeRepository payTypeRepository;
    
    @Autowired
    private TradeMchInfoRepository tradeMchInfoRepository;
    
    /**
     * 员工订单列表查询方法
     *
     * @return
     */
//    public GetMemberOrdersResponse queryMemberOrders(GetMemberOrdersRequest memberOrdersRequest) {
//        //1.校验参数信息
//        validateQueryMemberOrdersParams(memberOrdersRequest);
//
//        //2.查询商户号信息
//        TradeMchInfo tradeMchInfo = tradeMchInfoRepository.queryTradeMchInfo(memberOrdersRequest.getMcode());
//        if(null == tradeMchInfo){
//            throw new BusinessCommonException(TradeErrorCode.TRADE_MCH_INFO_NOT_EXIST);
//        }
//
//        //3.校验签名信息
//        if(!SignUtils.isSignatureValid(MapBeanUtils.beanToMap(memberOrdersRequest),tradeMchInfo.getSecretKey())){
//            throw new BusinessCommonException(TradeErrorCode.TRADE_MCH_SIGN_VALIDATE_ERROR);
//        }
//
//        return queryMemberOrdersHandle(memberOrdersRequest,tradeMchInfo.getOrgId());
//    }
//
    /**
     * 查询员工交易数据参数校验
     * @param memberOrdersRequest
     */
    private void validateQueryMemberOrdersParams(GetMemberOrdersRequest memberOrdersRequest){
        //商户号不能为空
        if(StringUtils.isEmpty(memberOrdersRequest.getMcode())){
            throw new BusinessCommonException(TradeErrorCode.TRADE_MCH_MCODE_EMPTY);
        }
        //签名不能为空
        if(StringUtils.isEmpty(memberOrdersRequest.getSign())){
            throw new BusinessCommonException(TradeErrorCode.TRADE_MCH_SIGN_EMPTY);
        }
        //员工卡号不能为空
        if(StringUtils.isEmpty(memberOrdersRequest.getMemberCardNo())){
            throw new BusinessCommonException(TradeErrorCode.TRADE_MCH_MEMBER_CARD_NO);
        }
        //分页数据校验
        if(memberOrdersRequest.getIsPage() == null){
            throw new BusinessCommonException(TradeErrorCode.TRADE_MCH_IS_PAGE);
        }
        if(memberOrdersRequest.getIsPage()){
            if(memberOrdersRequest.getOffset() == null){
                throw new BusinessCommonException(TradeErrorCode.TRADE_MCH_OFFSET);
            }
            if(memberOrdersRequest.getLimit() == null){
                throw new BusinessCommonException(TradeErrorCode.TRADE_MCH_LIMIT);
            }
        }
    }
    
    /**
     * 查询员工交易订单数据信息
     * @param memberOrdersRequest
     * @return
     */
    private GetMemberOrdersResponse queryMemberOrdersHandle(GetMemberOrdersRequest memberOrdersRequest,Integer orgId){
        //1.整理员工订单列表数据查询条件
        OrderMasterExample example = queryMemberOrdersExampleHandle(memberOrdersRequest,orgId);
        
        //2.查询订单总记录条数
        val orderCount = orderMasterRepository.queryMemberOrderDetailsCount(example);    //查询满足条件的总记录条数
        
        //3.查询员工订单列表数据
        if (memberOrdersRequest.getIsPage()) {
            example.setLimit(memberOrdersRequest.getLimit());
            example.setOffset(memberOrdersRequest.getOffset());
        }
        val orderMasters = orderMasterRepository.queryMemberOrderDetails(example);
        if(null != orderMasters){
            orderStatusHandle(orderMasters);
        }
        val totalMap = orderMasterRepository.queryMemberOrderDetailsTotalAmount(example);
        List<MemberOrder> memberOrderList = ListUtils.convertListToList(orderMasters, MemberOrder.class);
    
        if(null != memberOrderList && memberOrderList.size() > 0){
            val tradePayTypeDicts = payTypeRepository.queryPayTypes(null, null);
            memberOrderList.forEach(memberOrder -> {
                //3.1处理支付方式名称
                if (!StringUtils.isEmpty(memberOrder.getPayType())) {
                    tradePayTypeDicts.forEach(tradePayTypeDict -> {
                        if (memberOrder.getPayType().equals(tradePayTypeDict.getPayType())) {
                            memberOrder.setPayTypeName(tradePayTypeDict.getName());
                            return;
                        }
                    });
                }

                val cardChangeMap = orderMasterRepository.queryBalanceAndPoint(memberOrder.getTradeId());

                if(cardChangeMap != null){
                    memberOrder.setMemberPoint((Integer)cardChangeMap.get("point_after"));
                    memberOrder.setBalance(((BigDecimal)cardChangeMap.get("amount_after")).divide(new BigDecimal(100)));
                }else{
                    memberOrder.setMemberPoint(0);
                    memberOrder.setBalance(BigDecimal.valueOf(0));
                }

                //3.2处理订单状态名称
                //订单状态(@1:待付款@2:已付款@3:退款中@4:已退款@5:订单取消)
                memberOrder.setOrderStatusName(getOrderStatusName(memberOrder.getOrderStatus()));
                
                //3.3如果已退款，则设置获得积分为0
                if (DictionaryConstant.ORDER_STATUS_YTK.getCode().equals(memberOrder.getOrderStatus())) {
                    memberOrder.setMemberPoint(0);
                }
    
                //3.5处理订单类型名称
                memberOrder.setOrderTypeName(getOrderTypeName(memberOrder.getOrderType()));
                
                //3.6处理应付金额
                //memberOrder.setPayAmount(memberOrder.getOrderAmount().subtract(memberOrder.getDiscountAmount()));

                if(memberOrder.getOrderAmount() != null) {
                    memberOrder.setOrderAmount(memberOrder.getOrderAmount().divide(new BigDecimal(100)));
                }

                if(memberOrder.getRealPayAmount() != null) {
                    memberOrder.setRealPayAmount(memberOrder.getRealPayAmount().divide(new BigDecimal(100)));
                }

                if(memberOrder.getPayAmount() != null) {
                    memberOrder.setPayAmount(memberOrder.getPayAmount().divide(new BigDecimal(100)));
                }

                //3.6 查询员工订单详情数据
                //查询订单详情数据
                List<OrderTransaction> orderDetails = orderTransactionRepository.queryOrderDetails(memberOrder.getOrderNumber());
                if (null != orderDetails && orderDetails.size() > 0) {
                    memberOrder.setOrderDetails(ListUtils.convertListToList(orderDetails, MemberOrderDetail.class));
                }
            });
        }
        
        //4.整理返回数据
        PaginationExtendBean<MemberOrder> paginationExtendBean = new PaginationExtendBean<>();
        paginationExtendBean.setTotal(orderCount);
        paginationExtendBean.setRows(memberOrderList);
        
        GetMemberOrdersResponse memberOrdersResponse = new GetMemberOrdersResponse();
        memberOrdersResponse.setPaginationExtendBean(paginationExtendBean);
        memberOrdersResponse.setTotalAmount(new BigDecimal(totalMap.get("orderAmount").toString()));
        return memberOrdersResponse;
    }
    
    /**
     * 整理查询条件信息
     * @param memberOrdersRequest
     * @return
     */
    private OrderMasterExample queryMemberOrdersExampleHandle(GetMemberOrdersRequest memberOrdersRequest,Integer orgId) {
        val example = new OrderMasterExample();
        example.createCriteria().andOrgIdEqualTo(orgId)
                                .andMemberCardNoEqualTo(memberOrdersRequest.getMemberCardNo());

        //2.处理订单类型
        if (!StringUtils.isEmpty(memberOrdersRequest.getOrderType())) {
            example.getOredCriteria().get(0).andOrderTypeEqualTo(memberOrdersRequest.getOrderType());
        }
       
        //8.处理查询时间
        if(!StringUtils.isEmpty(memberOrdersRequest.getStartTime())){
            example.getOredCriteria().get(0).andCreatedAtGreaterThanOrEqualTo(DateUtils.parse(memberOrdersRequest.getStartTime()));
        }
        if(!StringUtils.isEmpty(memberOrdersRequest.getEndTime())){
            example.getOredCriteria().get(0).andCreatedAtLessThanOrEqualTo(DateUtils.parse(memberOrdersRequest.getEndTime()));
        }
        example.setOrderByClause("created_at desc");
        return example;
    }
    
    /**
     * 处理订单状态
     */
    private void orderStatusHandle(List<OrderMasterMemberExt> orderMasters) {
        for (int i = 0; i < orderMasters.size(); i++) {
            //判断订单是否超时，如果超时表示交易失败
            if (!DictionaryConstant.ORDER_UPDATE_STATUS_ZFWC.getCode().equals(orderMasters.get(i).getOrderStatus()) &&
                    !DictionaryConstant.ORDER_UPDATE_STATUS_TKWC.getCode().equals(orderMasters.get(i).getOrderStatus())) {
                orderMasters.get(i).setOrderStatus(DictionaryConstant.ORDER_STATUS_DDQX.getCode());
            }
        }
    }
    
    /**
     * 根据订单状态获取订单状态名称
     *
     * @param orderStatus
     * @return
     */
    private String getOrderStatusName(String orderStatus) {
        String orderStatusName = "";
        if (!StringUtils.isEmpty(orderStatus)) {
            DictionaryConstant dict = DictionaryConstant.getEnumByCode(DictionaryConstant.ORDER_STATUS.getCode(), transferStatus(orderStatus));
            orderStatusName = dict.getValue();
        }
        return orderStatusName;
    }

    private String transferStatus(String orderStatus) {
        if(DictionaryConstant.ORDER_UPDATE_STATUS_DFK.getCode().equals(orderStatus)){
            return DictionaryConstant.ORDER_STATUS_DFK.getCode();
        }else if(DictionaryConstant.ORDER_UPDATE_STATUS_ZFWC.getCode().equals(orderStatus)){
            return DictionaryConstant.ORDER_STATUS_YFK.getCode();
        }else if(DictionaryConstant.ORDER_UPDATE_STATUS_DTC.getCode().equals(orderStatus)
                || DictionaryConstant.ORDER_UPDATE_STATUS_TKZ.getCode().equals(orderStatus)){
            return DictionaryConstant.ORDER_STATUS_TKZ.getCode();
        }else if(DictionaryConstant.ORDER_UPDATE_STATUS_DDQX.getCode().equals(orderStatus)){
            return DictionaryConstant.ORDER_STATUS_DDQX.getCode();
        }else if(DictionaryConstant.ORDER_UPDATE_STATUS_TKWC.getCode().equals(orderStatus)
                || DictionaryConstant.ORDER_UPDATE_STATUS_YTC.getCode().equals(orderStatus)){
            return DictionaryConstant.ORDER_STATUS_YTK.getCode();
        }else{
            return orderStatus;
        }
    }
    
    /**
     * 根据订单状态获取订单状态名称
     *
     * @param orderType
     * @return
     */
    private String getOrderTypeName(String orderType) {
        String orderTypeName = "";
        if (!StringUtils.isEmpty(orderType)) {
            DictionaryConstant dict = DictionaryConstant.getEnumByCode(DictionaryConstant.ORDER_TYPE.getCode(), orderType);
            orderTypeName = dict.getValue();
        }
        return orderTypeName;
    }
}
