package com.platform.yijia.service.impl;

import com.platform.yijia.dao.PayOrderMapper;
import com.platform.yijia.param.request.PayOrderRequest;
import com.platform.yijia.pojo.AppUserInfo;
import com.platform.yijia.pojo.PayOrder;

import com.platform.yijia.pojo.PayOrderExample;
import com.platform.yijia.service.PayOrderService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
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 PayOrderMapper payOrderMapper;

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

        payOrder.setStatus(payOrderRequest.getStatus());          //创建订单 未支付状态 0
        payOrder.setAmt(payOrderRequest.getAmt());              //金额
        payOrder.setOilName(payOrderRequest.getOilName());      //油品名称
        payOrder.setStationId(payOrderRequest.getStationId());  //油站id
        payOrder.setPayType(payOrderRequest.getPayType());      //支付类型
        payOrder.setPayWay(payOrderRequest.getPayWay());        //支付方式
        payOrder.setPayDate(new Date());    //支付时间
        payOrder.setOilPersonnel(payOrderRequest.getOilPersonnel());       //加油员
        payOrder.setCreatedDate(new Date());    //创建时间
        payOrder.setOrderType(payOrderRequest.getOrderType());            //订单类型

        //订单规则 时间+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);

        //根据油站和油枪获取油枪编号和价格
        HashMap<String, Object> params = new HashMap<>();
        params.put("oilGunId", payOrderRequest.getOilGun());
        params.put("stationId", payOrderRequest.getStationId());
        Map mapOilGunNoAndOilPrice = payOrderMapper.selectOilGunNoAndOilPrice(params);
        payOrder.setOilGun(mapOilGunNoAndOilPrice.get("oliGunNo").toString());         //存入油枪号

        //根据油品名称和油站id获取当前油品调价信息
        params.put("oilName", payOrderRequest.getOilName());
        List<Map> oilPriceAdjustList = payOrderMapper.selectOilPriceAdjust(params);
        String amt = payOrderRequest.getAmt();  //订单金额
        if(oilPriceAdjustList != null && oilPriceAdjustList.size() > 0){        //若存在油价价格调整时
            for (Map m : oilPriceAdjustList){
                if(compareEffectTime(m.get("takeEffectDate").toString())){      // 如果生效时间小于当前时间则使用生效时间 取离当前时间最近的调整价格（查询结果按生效时间降序排序故只做此判断即可）
                    payOrder.setOrderLiters(recKonOrderLiters(amt, m.get("oilAdjustPrice").toString(), 2));       //计算加油升数且存入
                    break;
                }
            }
        }else {     //若没有油价调整时则使用原始油价计算加油升数
            String oilPrice = mapOilGunNoAndOilPrice.get("oilPrice").toString();    //原始价格
            payOrder.setOrderLiters(recKonOrderLiters(amt, oilPrice, 2));     //计算油价升数存放
        }

        //数据落地
        payOrderMapper.insertSelective(payOrder);
        //根据订单号查询出订单
        PayOrderExample example=new PayOrderExample();
        example.or().andOrderNoEqualTo(ordNo);
        //根据订单号查询返回列表，最好是返回对象
        List<PayOrder> payOrderList= payOrderMapper.selectByExample(example);
        //返回订单号
        String ordno= payOrderList.get(0).getOrderNo();
        return ordno;
    }

    /*
     * 计算加油升数
     * @param str1
     * @param str2
     * @param scale 保留小数位数
     * @return String
     */
    public String recKonOrderLiters(String str1, String str2, int scale){
        return  String.valueOf(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);
    }

    /**
     * 修改订单信息
     * @param payOrder
     */
    @Override
    public void getUpdatePayOrder(PayOrder payOrder) {
        PayOrderExample example =new PayOrderExample();
        payOrderMapper.updateByExample(payOrder,example);
    }

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