package com.platform.yijia.service.impl;

import com.platform.yijia.dao.CustomerGradeMapper;
import com.platform.yijia.dao.PayOrderMapper;
import com.platform.yijia.param.request.PayOrderRequest;
import com.platform.yijia.pojo.*;

import com.platform.yijia.service.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.xml.crypto.Data;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service("payOrderService")
public class PayOrderServiceImpl implements PayOrderService {
    @Resource
    private CustomerGradeMapper customerGradeMapper;
    @Resource
    private PayOrderMapper payOrderMapper;
    @Resource
    private AppUserInfoService appUserInfoService;
    @Resource
    private StationService stationService;
    @Resource
    private CustomerGradeServices customerGradeServices;
    @Resource
    private ElectronicMembershipCardService electronicMembershipCardService;

    /*
     * 添加订单信息
     * @param payOrderRequest
     * @param payOrder
     * @return
     */
    @Override
    @Transactional
    public String AddPayOrderInfo(PayOrderRequest payOrderRequest, PayOrder payOrder) {

        //订单规则 时间+6位随机数
        Random random = new Random();
        String result="";
        for(int i=0;i<6;i++){
            result+=random.nextInt(10);
        }
        //System.out.println("随机生成6位数result ："+result);
        String ordNo=System.nanoTime()+result;
        payOrder.setOrderNo(ordNo);
        payOrder.setDiscountCouponAmt(payOrderRequest.getDiscountCouponAmt());  //优惠劵金额
        payOrder.setDiscountCoupon(payOrderRequest.getDiscountCoupon());        //优惠券
        payOrder.setCarNo(payOrderRequest.getCarNo());  //车牌号、
        payOrder.setCustomerGrade(payOrderRequest.getCustomerGrade());    //客户电话
        payOrder.setMemberNo(payOrderRequest.getMemberNo());     //会员卡号
        payOrder.setMemberAmt(payOrderRequest.getMemberAmt());    //会员支付金额
        //payOrder.setPrintCount(payOrderRequest.getPrintCount());    //小票数量
        payOrder.setScore(payOrderRequest.getScore());      //积分
        payOrder.setStationId(payOrderRequest.getStationId());  //油站id
        payOrder.setStatus("0");         //创建订单 未支付状态 0
        if(StringUtils.isNotBlank(payOrderRequest.getUserType())&& payOrderRequest.getUserType().equals("1")){
            payOrder.setPayWay("02");        //支付方式：02公众号，03小程序',
            payOrder.setWxAmt(Double.valueOf(payOrderRequest.getAmt()));    //微信支付金额
            payOrder.setPayType("wx");      //支付类型
        }else if(StringUtils.isNotBlank(payOrderRequest.getUserType())&& payOrderRequest.getUserType().equals("2")){
            payOrder.setPayWay("03");
            payOrder.setWxAmt(Double.valueOf(payOrderRequest.getAmt()));    //微信支付金额
            payOrder.setPayType("wx");      //支付类型
        }
        payOrder.setCreatedDate(new Date());                    //创建时间
        payOrder.setOrderType(payOrderRequest.getOrderType());  //订单类型
        payOrder.setOilGun(payOrderRequest.getOilGun());        //油枪号

        //根据油站和油枪获取加油员和油品价格 油站名称
        HashMap<String, Object> params = new HashMap<>();
        params.put("oliGunNo", payOrderRequest.getOilGun());
        params.put("stationId", payOrderRequest.getStationId());
        String oilPersonnel = "";
        //使用list原因：一个枪号对应多个加油员场景
        List<Map> mapResultList = payOrderMapper.selectPersonelName(params);
        if(mapResultList != null && mapResultList.size() > 0){
            for (Map per : mapResultList){
                if(per.containsKey("personelName") && per.get("personelName").toString() !=null && per.get("personelName").toString() !=""){
                    oilPersonnel += per.get("personelName").toString() +",";
                }
            }
            if(oilPersonnel !=""){
                payOrder.setOilPersonnel(oilPersonnel.substring(0, oilPersonnel.length()-1));   //加油员
            }
            if(mapResultList.get(0).containsKey("stationName") && mapResultList.get(0).get("stationName").toString() !="" && mapResultList.get(0).get("stationName").toString() !=null ){
                payOrder.setStationName(mapResultList.get(0).get("stationName").toString());        //油站名称
            }
        }

        //订单类型等于1时表示油品
        if(payOrderRequest.getOrderType().equals("1")){
            Double receivableAmt = payOrderRequest.getReceivableAmt();  //获取应收金额
            payOrder.setReceivableAmt(receivableAmt);
            Double oilPrice = payOrderRequest.getOilPrice();            //获取油价
            payOrder.setOilPirce(String.valueOf(oilPrice));

            Double oilLitersCheck= null;    //加油升数校验
            if(receivableAmt != null && oilPrice != null){
                //计算加油升数
                oilLitersCheck = recKonOrderLiters(receivableAmt, oilPrice, 2);
                payOrder.setOrderLiters(String.valueOf(oilLitersCheck));

                //实收金额 优惠金额
                payOrder.setAmt(Double.valueOf(payOrderRequest.getAmt()));
                payOrder.setDiscountAmt(payOrderRequest.getDiscountAmt());




                String oilName = payOrderRequest.getOilName();
                payOrder.setOilName(oilName);      //油品名称
                //根据油品名称存储油品类型 1.柴油 2 汽油
                switch (oilName){
                    case "92#":
                        payOrder.setOilType("2");
                        break;
                    case "95#":
                        payOrder.setOilType("2");
                        break;
                    case "97#":
                        payOrder.setOilType("2");
                        break;
                    case "0#":
                        payOrder.setOilType("1");
                        break;
                    case "-10#":
                        payOrder.setOilType("1");
                        break;
                    case "-20#":
                        payOrder.setOilType("1");
                        break;
                }
                //数据落地
                payOrderMapper.insertSelective(payOrder);
                //根据订单号查询出订单
                PayOrderExample example=new PayOrderExample();
                example.or().andOrderNoEqualTo(ordNo);
                //根据订单号查询返回列表，最好是返回对象
                List<PayOrder> payOrderList= payOrderMapper.selectByExample(example);
                //返回订单号
                ordNo= payOrderList.get(0).getOrderNo();
            }else {
                ordNo = "1";
            }
        }else if(payOrderRequest.getOrderType().equals("2")){       //订单类型等于2时表示非油品
            String oilName = payOrderRequest.getOilName();
            payOrder.setOilName(oilName);      //非油品名称
            Map<String, String> m = stationService.getStationAppIdAndAppSecret(payOrderRequest.getStationId());
            if(m.containsKey("stationName") && m.get("stationName") !=null){
                payOrder.setStationName(m.get("stationName"));
            }
            payOrder.setReceivableAmt(payOrderRequest.getReceivableAmt());  //非油品应收金额
            payOrder.setAmt(Double.valueOf(payOrderRequest.getAmt()));  //非油品金额
            //数据落地
            payOrderMapper.insertSelective(payOrder);
            //根据订单号查询出订单
            PayOrderExample example=new PayOrderExample();
            example.or().andOrderNoEqualTo(ordNo);
            //根据订单号查询返回列表，最好是返回对象
            List<PayOrder> payOrderList= payOrderMapper.selectByExample(example);
            //返回订单号
            ordNo= payOrderList.get(0).getOrderNo();
        }
        return ordNo;
    }

    /*
     * 计算加油升数
     * @param str1
     * @param str2
     * @param scale 保留小数位数
     * @return String
     */
    public Double recKonOrderLiters(Double str1, Double str2, int scale){
        return  new BigDecimal(str1).divide(new BigDecimal(str2), scale, BigDecimal.ROUND_HALF_UP).doubleValue();
    }

    /*
     * 判断油价生效时间是否小于当前时间
     * @param takeEffectDate
     * @return boolean
     */
    public boolean compareEffectTime(String takeEffectDate){
        boolean flag = false;
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm");
        try {
            Date teDate = df.parse(takeEffectDate);
            String currentTime = df.format(new Date());
            if(teDate.getTime() <= df.parse(currentTime).getTime()){
                flag = true;
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return flag;
    }

    /*
     * 查询订单信息
     * */
    @Override
    public List<PayOrder> getPayOrderList(String orderNo) {
        PayOrderExample example =new PayOrderExample();
        example.or().andOrderNoEqualTo(orderNo);
        return payOrderMapper.selectByExample(example);
    }

    //查询班结时间订单
    @Override
    public List<PayOrder> selectPayOrderList(PayOrder payOrder) {
        return payOrderMapper.selectPayOrderList(payOrder);
    }

    @Override
    public PayOrder getPayOrderInfoMin(PayOrder payOrder) {
        return payOrderMapper.getPayOrderInfoMin(payOrder);
    }

    /**
     * 修改订单信息
     * @param payOrder
     */
    @Override
    public int getUpdatePayOrder(PayOrder payOrder) {
//        PayOrderExample example =new PayOrderExample();
//        example.or().andOrderIdEqualTo(payOrder.getOrderId());
        return payOrderMapper.updateOrderStatus(payOrder);
    }

    @Override
    public PayOrder searchPayOrder(Integer orderId) {
        PayOrder payOrder= payOrderMapper.selectByPrimaryKey(orderId);
        return payOrder;
    }

    //根据手机号查询用户信息
    @Override
    public List<AppUserInfo> getUserInfoByOpenId(AppUserInfo appUserInfo) {
        return payOrderMapper.getUserInfoByOpenId(appUserInfo);
    }

    /*
     * 根据用户openId和用户类型userType查询用户订单
     * @param payOrder
     * @return
     */
    @Override
    public List<PayOrder> getOrderListByOpenIdAndUserType(AppUserInfo appUserInfo) {
        return payOrderMapper.getOrderListByOpenIdAndUserType(appUserInfo);
    }

    /*
     * 根据订单号查询订单信息和用户信息  注：此方法在随行付回调校验之后修改状态完成后
     * @param payOrder
     * @return
     */
    @Override
    public Map<String, Object> getOrderInfoAndUserInfoByOrderNo(PayOrder payOrder) {
        return payOrderMapper.getOrderInfoAndUserInfoByOrderNo(payOrder);
    }

    /*
     * 判断客户表是否已存在
     * @param customerManage
     * @return
     */
    @Override
    public CustomerManage isExistCustomer(CustomerManage customerManage) {
        return payOrderMapper.isExistCustomer(customerManage);
    }

    /*
     * 更新客户表 注：限用于随行付支付完成处
     * @param customerManage
     */
    @Override
    public void updateCustomer(CustomerManage customerManage) {
        payOrderMapper.updateCustomer(customerManage);
    }

    /*
     * 新增客户 注：限用于随行付支付完成处
     * @param customerManage
     */
    @Override
    public void insertCustomer(CustomerManage customerManage) {
        payOrderMapper.insertCustomer(customerManage);
    }

    /*
     *  根据手机号更新
     * @param customerManage
     */
    @Override
    public void updateCustomerByPhoneNumber(CustomerManage customerManage) {
        payOrderMapper.updateCustomerByPhoneNumber(customerManage);
    }

    //查询汇总数据
    public List<Map> selectSum(PayOrder payOrder){
        return  payOrderMapper.selectSum(payOrder);
    }
}
