package com.liangjian.dataplatform.member.service.impl;


import com.liangjian.dataplatform.member.dao.secondary.*;
import com.liangjian.dataplatform.member.dao.elasticsearch.UserPointLogRepository;
import com.liangjian.dataplatform.member.dao.secondary.UserWecahatInfoRepository;
import com.liangjian.dataplatform.member.entity.po.secondary.*;
import com.liangjian.dataplatform.member.entity.po.elasticsearch.UserPointLog;
import com.liangjian.dataplatform.member.entity.po.secondary.WeixinUserInfo;
import com.liangjian.dataplatform.member.service.IUserIngOrdersService;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;


@Service
public class UserIngOrdersService implements IUserIngOrdersService {
    @Autowired
    private UserOrdersRepository userOrdersRepository;

    @Autowired
    private UserProductRepository userProductRepository;

    @Autowired
    private UserPointLogRepository userPointLogRepository;

    @Autowired
    private UserLevelUnitRepository userLevelUnitRepository;

    @Autowired
    private UserOrdersPayRepository userOrdersPayRepository;

    @Autowired
    private UserWecahatInfoRepository userWecahatInfoRepository;

    @Autowired
    private WeixinUserInfoRepository weixinUserInfoRepository;


    @Autowired
    private UserOrderProductRepository userOrderProductRepository;
    //验证用户openid
    @Override
    public boolean findByOpenid(String openid,String secretPhone) {
        boolean emtp=false;
        List<WeixinUserInfo> list=userWecahatInfoRepository.findByOpenid(openid);
        if(list.size()>0 && list.get(0).getSecretPhone().equals(secretPhone)){
            emtp=true;
        }
        return emtp;
    }

    //订单详情
    @Override
    public MemIngOrders queryByAccountPhoneInfo(String ordersCode) {
        Pageable pageable = PageRequest.of(0,1, Sort.Direction.DESC,"CreationDate");
        Page<MemIngOrders> or=userOrdersRepository.queryByOrdersCode(ordersCode,pageable);
        List<MemIngOrders> list = or.getContent();
        return list.isEmpty() ? null : list.get(0);
    }


    //订单列表
    @Override
    public Page<MemIngOrders> queryByAccountPhone(String accountPhone,Integer state, Integer page, Integer size) {
        Pageable pageable = PageRequest.of(page,size, Sort.Direction.DESC,"CreationDate");
        if(state==null ||state==0){
            return userOrdersRepository.queryByAccountId(accountPhone,pageable);
        }else{
            return userOrdersRepository.queryByAccountIdAndOrderState(accountPhone,state,pageable);
        }
    }

    @Override
    public MemIngProduct getProductInfo(String productCode, String secretPhone) {
        return getProductInfoV2(productCode,secretPhone);
    }


    //待下单商品信息
    public MemIngProduct getProductInfoV2(String productCode, String secretPhone) {
        //手机号获取日志最后积分，会员等级
        Pageable pageable1 = PageRequest.of(0,1, Sort.Direction.DESC,"crtDate");
        String level = "";//默认等级
        Integer ingValue = 0;//积分
        if(secretPhone!=null&&secretPhone!=""){
            WeixinUserInfo weixinUserInfo=weixinUserInfoRepository.queryBySecretPhone(secretPhone).get();
            if(weixinUserInfo!=null){
                ingValue=weixinUserInfo.getPoint();
            }
            //全部等级
            List<UserLevelUnit> userLevelUnits=userLevelUnitRepository.findAll();
            for(UserLevelUnit userLevel : userLevelUnits){
                if(ingValue>=userLevel.getGrowthFrom() && ingValue<=userLevel.getGrowthTo()){
                    level=userLevel.getId();
                    break;
                }else if(ingValue>0){
                    level=userLevel.getId();
                }
            }
        }


        Pageable pageable = PageRequest.of(0,1, Sort.Direction.DESC,"CreationDate");
        MemIngOrders memIngOrders=new MemIngOrders();
        Page<MemIngProduct> products= userProductRepository.queryByProductCode(productCode,pageable);
        List<MemIngProduct> pdlist = products.getContent();

        MemIngProduct mpd=pdlist.isEmpty() ? null : pdlist.get(0);
        Set<MemIngProductLevel> mset=new HashSet<MemIngProductLevel>();
        if(mpd!=null){
            Set<MemIngProductLevel> productLevel = mpd.getProductLevel();
            for(MemIngProductLevel me : productLevel){
                if(me.getLevelId().equals(level)){
                    //指定价格
                    mset.add(me);
                    break;
                }
            }
            mpd.setProductLevel(mset);
        }
        return mpd;
    }

    @Override
    public Integer getUserOrderPoint(String secretPhone) {
        Integer point=0;
        Date now = new Date();
        Date now_10 = new Date(now.getTime() - 600000);
        JSONObject m=userOrderProductRepository.findBySecretPhoneAndCrtDateGreaterThanEqual(secretPhone,now_10);
        if(m!=null){
            point=Integer.parseInt(m.getString("amount"));
        }
        return point;
    }


    public Integer getUserOrderAmount(String productId) {
        Integer point=0;
        Date now = new Date();
        Date now_10 = new Date(now.getTime() - 600000);
        JSONObject m=userOrderProductRepository.findByProductIdAndCrtDateGreaterThanEqual(productId,now_10);
        if(m!=null){
            point=Integer.parseInt(m.getString("amount"));
        }
        return point;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String addOrders(WeixinUserInfo weixinUserInfo,MemIngOrders order,String productCode) {
        try {
            weixinUserInfo=weixinUserInfoRepository.queryBySecretPhone(weixinUserInfo.getSecretPhone()).get();
            String uuid = getGeneratID();
            order.setOrdersCode(uuid);
            Integer ordertate=1;//待支付
            Integer ordertatepay=1;
            //等级商品
            MemIngProduct mpd = getProductInfoV2(productCode,order.getAccountId());
            order.setMemIngProduct(mpd);
            order.setCreationDate(new Date());
            order.setLastModified(new Date());

            Integer price=mpd.getMarketPrice();//金额
            Integer ing=mpd.getMarketIng()*order.getAmount();//积分

            //计算支付状态
            Set<MemIngProductLevel> productLevel = mpd.getProductLevel();//会员当前等级需要支付金额+积分
            if(productLevel!=null){
                for(MemIngProductLevel level :productLevel){
                    price=level.getMarketPrice()*order.getAmount();
                    ing=level.getMarketIng()*order.getAmount();
                }
                if(price<=0){//无需支付
                    ordertate=2;
                    ordertatepay=4;
                }
            }

            if(price>0){
                return "暂未开通在线付款";
            }


            MemIngProduct memIngProduct = userProductRepository.findById(productCode).get();


            memIngProduct.setAmount(memIngProduct.getAmount()-getUserOrderAmount(productCode));


            if(memIngProduct.getAmount()<=0){
                return "商品库存不足";
            }

            //Integer point = getUserOrderPoint(weixinUserInfo.getSecretPhone());
            //剩余积分大于所需支付积分
            if(weixinUserInfo.getPoint()!=null && weixinUserInfo.getPoint() > ing){
                int res=updateWechatUserVersion(weixinUserInfo.getSecretPhone(),weixinUserInfo.getPoint()-ing);
                if(res<=0){
                    return "系统繁忙，稍后再试！";
                }
                MemIngProductOrder memIngProductOrder=new MemIngProductOrder();
                memIngProductOrder.setAmount(order.getAmount());
                memIngProductOrder.setCrtDate(new Date());
                memIngProductOrder.setId(getGeneratID());
                memIngProductOrder.setPoint(ing);
                memIngProductOrder.setSecretPhone(weixinUserInfo.getSecretPhone());
                userOrderProductRepository.save(memIngProductOrder);

                //记录支付表
                MemIngOrdersPay pay=new MemIngOrdersPay();
                pay.setIs_Pay(ordertatepay);
                pay.setIntegral(ing);
                pay.setPayPirce(price);
                pay.setOrdersCode(uuid);
                pay.setPayTime(new Date());
                pay.setPayType("100");
                userOrdersPayRepository.save(pay);

                order.setOrderState(ordertate);
                order.setProductCode(productCode);
                userOrdersRepository.save(order);
                //扣减积分
                /*weixinUserInfo.setPoint(weixinUserInfo.getPoint()-ing);
                weixinUserInfoRepository.save(weixinUserInfo);*/

                String str="用户下单扣减积分："+weixinUserInfo.getPoint()+" - "+ing+" = "+(weixinUserInfo.getPoint()-ing);
                //库存减1,积分减
                UserPointLog log=new UserPointLog();
                log.setId(getGeneratID());
                log.setPayment(Double.valueOf(price));
                log.setOrderAmount(Double.valueOf(price));
                log.setDiscountedPrice(0.0);
                log.setTransportCost(0.0);
                log.setValue(ing);
                log.setIncrease(false);
                log.setDataCode(uuid);
                log.setSecretPhone(weixinUserInfo.getSecretPhone());
                log.setTerminalAction(str);
                log.setTerminalCode(str);
                log.setTerminalName("订单扣减");
                log.setAction("订单扣减");
                log.setCrtDate(new Date());
                log.setLastUpdate(new Date());
                log.setOrigin(weixinUserInfo.getPoint());
                log.setBalance(weixinUserInfo.getPoint()-ing);
                userPointLogRepository.save(log);
                return "200";
            }
            return "积分余额不足";

        } catch (Exception ex) {
            ex.printStackTrace();
            return "300";
        }
    }


    public int updateWechatUserVersion(String secretPhone,Integer point){
        int res=0;
        for(int i=0;i<=5;i++){
            WeixinUserInfo w=weixinUserInfoRepository.queryBySecretPhone(secretPhone).get();
            res = weixinUserInfoRepository.updateWeiUser(point,w.getId(),w.getVersion());
            if(res>=1){
                return res;
            }
        }
        return res;
    }

    public static String getGeneratID(){
        String sformat = "MMddhhmmssSSS";
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat(sformat);
        String dateString = formatter.format(currentTime);
        dateString+= (int)(100*(Math.random()));
        return dateString;
    }
}
