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

import com.neusoft.smart.pos.constants.DictionaryConstant;
import com.neusoft.smart.pos.dto.order.response.GetAllOrderInfoResponse;
import com.neusoft.smart.pos.dto.payment.request.FumaoPayRequest;
import com.neusoft.smart.pos.dto.payment.response.FumaoMemberInfoRes;
import com.neusoft.smart.pos.framework.exception.BusinessCommonException;
import com.neusoft.smart.pos.framework.utils.DateUtils;
import com.neusoft.smart.pos.payment.constants.PaymentErrorCode;
import com.neusoft.smart.pos.payment.dto.request.FumaoCheckUserRequest;
import com.neusoft.smart.pos.payment.dto.request.FumaoLoginRequest;
import com.neusoft.smart.pos.payment.dto.request.FumaoPosOrderSyncRequest;
import com.neusoft.smart.pos.payment.dto.request.FumaoQueryCalcRequest;
import com.neusoft.smart.pos.payment.dto.response.FumaoCheckUserResponse;
import com.neusoft.smart.pos.payment.dto.response.FumaoPosOrderSyncResponse;
import com.neusoft.smart.pos.payment.persistent.domain.FumaoUserInfo;
import com.neusoft.smart.pos.payment.persistent.domain.FumaoUserInfoExample;
import com.neusoft.smart.pos.payment.persistent.mapper.FumaoUserInfoMapper;
import com.neusoft.smart.pos.payment.repository.FumaoPayRepository;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@Service("FumaoPayService")
public class FumaoPayService {
    
    @Resource
    FumaoPayRepository fumaoPayRepository;

    @Resource
    FumaoUserInfoMapper fumaoUserInfoMapper;

    public void fumaoCheckUser(FumaoLoginRequest fumaoLoginRequest){
        FumaoCheckUserRequest fumaoCheckUserRequest = new FumaoCheckUserRequest();
        BeanUtils.copyProperties(fumaoLoginRequest, fumaoCheckUserRequest);
        String sn = fumaoLoginRequest.getSn();
        String tenantId = fumaoPayRepository.getTenantId(sn, fumaoLoginRequest.getPhone());
        if(StringUtils.isEmpty(tenantId)) {
            return;
        }
        fumaoCheckUserRequest.setTenantId(tenantId);
        FumaoCheckUserResponse response = fumaoPayRepository.fumaoCheckUser(fumaoCheckUserRequest);
        if(response != null) {
            saveFumaoUserInfo(fumaoLoginRequest.getPhone(), response);
        }
    }


    private void saveFumaoUserInfo(String phone, FumaoCheckUserResponse response) {
        // 操作员信息存数据库
        FumaoUserInfoExample fumaoUserInfoExample = new FumaoUserInfoExample();
        fumaoUserInfoExample.createCriteria().
                andTenantIdEqualTo(response.getTenant_id()).
                andOrderOperatorPhoneEqualTo(phone);
        List<FumaoUserInfo> list = fumaoUserInfoMapper.selectByExample(fumaoUserInfoExample);
        FumaoUserInfo fumaoUserInfo = new FumaoUserInfo();
        if(list != null && list.size() > 0) { // 更新记录
            fumaoUserInfo = list.get(0);
            fumaoUserInfo.setTenantId(response.getTenant_id());
            fumaoUserInfo.setMerchantId(response.getMerchant_id());
            fumaoUserInfo.setOrderOperatorId(response.getOrder_operation_id());
            fumaoUserInfo.setUpdatedAt(new Date());
            fumaoUserInfoMapper.updateByPrimaryKey(fumaoUserInfo);
        } else {        // 插入记录
            fumaoUserInfo.setTenantId(response.getTenant_id());
            fumaoUserInfo.setMerchantId(response.getMerchant_id());
            fumaoUserInfo.setOrderOperatorId(response.getOrder_operation_id());
            fumaoUserInfo.setOrderOperatorPhone(phone);
            fumaoUserInfoMapper.insert(fumaoUserInfo);
        }
    }

    public FumaoMemberInfoRes queryAndCalc(FumaoQueryCalcRequest fumaoCouponQueryCalcRequest) {
        FumaoPayRequest fumaoPayRequest = new FumaoPayRequest();
        BeanUtils.copyProperties(fumaoCouponQueryCalcRequest, fumaoPayRequest);
        FumaoUserInfo userInfo = fumaoPayRepository.getFumaoUserInfo(fumaoCouponQueryCalcRequest.getDeviceSN(), fumaoCouponQueryCalcRequest.getOperatorPhone());
        fumaoPayRequest.setMerchantId(userInfo.getMerchantId());
        fumaoPayRequest.setOrderOperatorId(userInfo.getOrderOperatorId());
        fumaoPayRequest.setTenantId(userInfo.getTenantId());
        return fumaoPayRepository.fumaoMemberInfoToThirdPlatform(fumaoPayRequest);
    }

    public FumaoPosOrderSyncResponse posOrderSync(GetAllOrderInfoResponse getAllOrderInfoResponse) {
        FumaoPosOrderSyncRequest fumaoPosOrderSyncRequest = new FumaoPosOrderSyncRequest();
        fumaoPosOrderSyncRequest.setDeviceSN(getAllOrderInfoResponse.getSerialNo());
        fumaoPosOrderSyncRequest.setOrderAmount(getAllOrderInfoResponse.getOrderAmount().toString());
        fumaoPosOrderSyncRequest.setOrderNumber(getAllOrderInfoResponse.getOrderNumber());
        fumaoPosOrderSyncRequest.setOrderTimeOfPlatform(DateUtils.format(getAllOrderInfoResponse.getCreatedAt(),DateUtils.FORMAT_LONG));

        List<GetAllOrderInfoResponse.PayInfo> payInfos = getAllOrderInfoResponse.getPayInfos();
        if(payInfos.get(0).getRequestDetailInfo() == null || payInfos.get(0).getRequestDetailInfo().equals("")) { // 没登录富茂会员
            return null;
        }

        // TODO 判断是否是富茂订单，有更好的方法吗
        JSONObject payInfoJsonObject  = JSONObject.fromObject(payInfos.get(0).getRequestDetailInfo());
        try {
            fumaoPosOrderSyncRequest.setMemPhone(payInfoJsonObject.getString("memPhone"));
            fumaoPosOrderSyncRequest.setMemId(payInfoJsonObject.getString("memId"));
            fumaoPosOrderSyncRequest.setBusinessType(payInfoJsonObject.getString("businessType"));
        } catch (Exception e) {
            return null;
        }

        FumaoUserInfo fumaoUserInfo = fumaoPayRepository.getFumaoUserInfo(getAllOrderInfoResponse.getSerialNo(),getAllOrderInfoResponse.getCreatedBy());
        fumaoPosOrderSyncRequest.setMerchantId(fumaoUserInfo.getMerchantId());
        fumaoPosOrderSyncRequest.setTenantId(fumaoUserInfo.getTenantId());
        fumaoPosOrderSyncRequest.setOrderOperatorId(fumaoUserInfo.getOrderOperatorId());

        setMemberInfo(fumaoPosOrderSyncRequest, payInfos.get(0).getRequestDetailInfo());
        if(getAllOrderInfoResponse.getOrderStatus().equals(DictionaryConstant.ORDER_UPDATE_STATUS_ZFWC.getCode())) {
            fumaoPosOrderSyncRequest.setOrderStatus("0");
            List<FumaoPosOrderSyncRequest.PaymentDetail> list = new ArrayList<>();
            for (GetAllOrderInfoResponse.PayInfo payInfo: payInfos) {
                FumaoPosOrderSyncRequest.PaymentDetail paymentDetail = new FumaoPosOrderSyncRequest.PaymentDetail();
                paymentDetail.setPayment_type(convertFumaoPayType(payInfo.getPayType()));
                paymentDetail.setPayment_number_of_platform(payInfo.getTradeId());
                paymentDetail.setPayment_amount(payInfo.getPayAmount().toString());
                paymentDetail.setPayment_order_time(DateUtils.format(payInfo.getCreatedAt(),DateUtils.FORMAT_LONG_UNMARK).concat("001"));
                paymentDetail.setOuter_payment_number(payInfo.getOuterOrderNumber());
                list.add(paymentDetail);
            }
            fumaoPosOrderSyncRequest.setPaymentDetailList(list);
        } else if(getAllOrderInfoResponse.getOrderStatus().equals(DictionaryConstant.ORDER_UPDATE_STATUS_TKWC.getCode())) {
            fumaoPosOrderSyncRequest.setOrderStatus("1");
            List<FumaoPosOrderSyncRequest.RefundDetail> list = new ArrayList<>();
            List<GetAllOrderInfoResponse.OrderRefundInfo> refundInfos = getAllOrderInfoResponse.getOrderRefunds();
            for (GetAllOrderInfoResponse.OrderRefundInfo refundInfo: refundInfos) {
                for(GetAllOrderInfoResponse.PayRefundOrderInfo payRefundOrderInfo: refundInfo.getPayRefundOrderInfos()){
                    FumaoPosOrderSyncRequest.RefundDetail refundDetail = new FumaoPosOrderSyncRequest.RefundDetail();
                    refundDetail.setPayType(convertFumaoPayType(payRefundOrderInfo.getPayType()));
                    refundDetail.setPayment_number_of_platform(payRefundOrderInfo.getTradeId());
                    refundDetail.setRefund_number_of_platform(payRefundOrderInfo.getPayRefundOrderNumber());
                    refundDetail.setRefund_amount(payRefundOrderInfo.getRefundedAmount().toString());
                    refundDetail.setRefund_order_time(DateUtils.format(payRefundOrderInfo.getCreatedAt(),DateUtils.FORMAT_LONG_UNMARK).concat("001"));
                    if(payRefundOrderInfo.getTradeId() != null) {
                        refundDetail.setRefund_status("0");
                        refundDetail.setRefund_type(convertFumaoPayType(payRefundOrderInfo.getPayType()));
                    } else {
                        refundDetail.setRefund_status("1");
                        refundDetail.setRefund_type("7");
                        // TODO 什么时候需要设置为2？
                    }
                    refundDetail.setOuter_refund_number(payRefundOrderInfo.getThirdRefundNumber());
                    refundDetail.setRefund_time(payRefundOrderInfo.getRefundedTime());
                    list.add(refundDetail);
                }
            }
            fumaoPosOrderSyncRequest.setRefundDetailList(list);
        } else {
            return null;
//            throw new BusinessCommonException(PaymentErrorCode.ORDER_IS_NOT_COMPLETED);
        }
        return fumaoPayRepository.posOrderSync(fumaoPosOrderSyncRequest);
    }

    private String convertFumaoPayType(String platformPayType) {
        if(platformPayType.equals(DictionaryConstant.PAY_TYPE_WXEWM.getCode()))
            return "0";
        else if(platformPayType.equals(DictionaryConstant.PAY_TYPE_ZFBEWM.getCode()))
            return "1";
        else if(platformPayType.equals(DictionaryConstant.PAY_TYPE_XJ.getCode()))
            return "2";
        else if(platformPayType.equals(DictionaryConstant.PAY_TYPE_DISCOUNT.getCode()))
            return "3";
        else if(platformPayType.equals(DictionaryConstant.PAY_TYPE_FM_COUPON.getCode()))
            return "4";
        else if(platformPayType.equals(DictionaryConstant.PAY_TYPE_BANK_FLM.getCode()))
            return "6";
        // TODO 记账 -- 7
        else if(platformPayType.equals(DictionaryConstant.PAY_TYPE_FM_CARD.getCode()))
            return "8";
        else
            return platformPayType;
    }

    private void setMemberInfo(FumaoPosOrderSyncRequest fumaoPosOrderSyncRequest, String payInfoString) {
        JSONObject payInfoJsonObject  = JSONObject.fromObject(payInfoString);
        try {
            fumaoPosOrderSyncRequest.setMemPhone(payInfoJsonObject.getString("memPhone"));
            fumaoPosOrderSyncRequest.setMemId(payInfoJsonObject.getString("memId"));
            fumaoPosOrderSyncRequest.setBusinessType(payInfoJsonObject.getString("businessType"));
        } catch (Exception e) {
            throw new BusinessCommonException(PaymentErrorCode.PAY_TYPE_INFO_NOT_EMPTY);
        }
    }
    
}
