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.entity.po.secondary.*;
import com.liangjian.dataplatform.member.entity.po.elasticsearch.UserPointLog;
import com.liangjian.dataplatform.member.jobUtil.EsUtils;
import com.liangjian.dataplatform.member.service.ISecretEncodeDecodeService;
import com.liangjian.dataplatform.member.service.IUserOrdersService;
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.data.jpa.repository.Modifying;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.PersistenceContext;
import javax.persistence.EntityManager;
import java.text.SimpleDateFormat;
import java.util.*;


@Service
public class UserOrdersService implements IUserOrdersService {
    @Autowired
    private UserOrdersRepository userOrdersRepository;

    @Autowired
    private UserProductRepository userProductRepository;

    @Autowired
    private UserPointLogRepository userPointLogRepository;

    @Autowired
    private UserLevelUnitRepository userLevelUnitRepository;

    @Autowired
    private UserProductLevelRepository userProductLevelRepository;

    @Autowired
    private UserProductTypeRepository userProductTypeRepository;

    @Autowired
    private  UserProductPicRepository userProductPicRepository;

    @Autowired
    private UserProductLogRepository userProductLogRepository;

    @Autowired
    private WeixinUserInfoRepository weixinUserInfoRepository;

    @Autowired
    private ISecretEncodeDecodeService iSecretEncodeDecodeService;

    @PersistenceContext(unitName = "entityManagerFactorySecondary")
    private EntityManager em;

    @PersistenceContext(unitName = "entityManagerFactoryTertiary")
    private EntityManager em1;


    public MemIngProduct getUserOpenId(String openId){
        MemIngProduct memIngProduct =new MemIngProduct();

        return memIngProduct;
    }

    //待下单商品信息
    public MemIngProduct getProductInfoV2(String productCode, String secretPhone) {
        //手机号获取日志最后积分，会员等级
        Pageable pageable1 = PageRequest.of(0,1, Sort.Direction.DESC,"crtDate");
        Page<UserPointLog> logs = userPointLogRepository.findBySecretPhone(secretPhone,pageable1);
        List<UserPointLog> list = logs.getContent();
        Integer level = 1;//默认等级
        Integer ingValue = 0;//积分
        for(UserPointLog log : list){
            ingValue=log.getValue();
        }
        //全部等级
        List<UserLevelUnit> userLevelUnits=userLevelUnitRepository.findAll();
        for(UserLevelUnit userLevel : userLevelUnits){
            if(ingValue>=userLevel.getGrowthFrom() && ingValue<=userLevel.getGrowthTo()){
                level=userLevel.getLevel();
                break;
            }else if(ingValue>0){
                level=userLevel.getLevel();
            }
        }

        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(String.valueOf(level))){
                    //指定价格
                    mset.add(me);
                    break;
                }
            }
            mpd.setProductLevel(mset);
        }
        return mpd;
    }


    /***
     * 订单列表
     * @param pageIndex
     * @param pageSize
     * @param filters
     * @return
     */
    @Override
    public Map<String,Object> getFilters(Integer pageIndex,Integer pageSize,List<FiltersUtils> filters){
        Map<String,Object> map=new HashMap<String,Object>();
        int start = pageIndex * pageSize;
        int end = (start + 1 + pageSize);
        //动态条件
        String sqlStr="";
        Integer totalCount=0;
        List<Map<String, Object>> listMap=null;
        sqlStr=EsUtils.getFilterString(filters);

        String sqlStr2=" A.*,row_number() over(  order by A.OrdersCode desc  )  as rownum ";
        String sqlStr1=" SELECT SQLSTR FROM (SELECT o.OrdersCode,o.OrderTime,o.CreationDate,o.LastModified,o.AccountId,o.Consignee,o.ADeliveryAddress,o.ProductCode,o.OrderState,o.CourierID,o.Address,o.AConsigneePhone,o.SenderType,o.BuyRemark,p.Integral,p.payPirce,p.Is_Pay,p.PayType,(ISNULL(p.PostagePrice, 0)) PostagePrice,d.ProductName,d.Manufacturer,d.Amount,(ISNULL(d.MarketPrice, 0)) MarketPrice ,d.MarketIng,d.ProductObject,u.nickname,u.point as ing " +
                " from "+
                " mem_ingOrders o LEFT JOIN mem_ingOrdersPay p ON o. OrdersCode=p.OrdersCode LEFT JOIN mem_ingProduct d ON d.ProductCode=o.ProductCode LEFT JOIN mem_weixin_user_info u ON u.secret_phone=o.AccountId where 1=1) as A where 1=1 "+sqlStr ;
        //查询订单sql
        String sql = " select * from ( " + sqlStr1.replace("SQLSTR",sqlStr2) +
                "  )AAA   where AAA.rownum > "+start+" and AAA.rownum < "+end+"  ORDER BY AAA.OrderTime desc  ";

        List list=em.createNativeQuery(sql).getResultList();

        //List序列化
        String[] key = {"OrdersCode","OrderTime","CreationDate","LastModified","AccountId","Consignee","ADeliveryAddress","ProductCode","OrderState","CourierID","Address","AConsigneePhone","SenderType","BuyRemark","Integral","payPirce","Is_Pay","PayType","PostagePrice","ProductName","Manufacturer","Amount","MarketPrice","MarketIng","ProductObject","nickname","ing"};
        listMap= transferToMap(key,list);

        //获取全部等级
        List<UserLevelUnit> userLevelUnits=userLevelUnitRepository.findAll();

        for(Map<String,Object> map1:listMap){
            if(map1.get("ing")!=null && map1.get("ing").toString()!=""){
                Integer ingValue=Integer.parseInt(map1.get("ing").toString());
                for(UserLevelUnit userLevel : userLevelUnits){
                    if(ingValue>=userLevel.getGrowthFrom() && ingValue<=userLevel.getGrowthTo()){
                        map1.put("ing",userLevel.getLevel());
                        break;
                    }else if(ingValue>0){
                        map1.put("ing",userLevel.getLevel());
                    }
                }
            }

            if(map1.get("AConsigneePhone")!=null&& !map1.get("AConsigneePhone").toString().equals("")){
                String AConsigneePhone=map1.get("AConsigneePhone").toString();
                map1.put("AConsigneePhone",AConsigneePhone.substring(0,3)+"****"+AConsigneePhone.substring(7,AConsigneePhone.length()));
            }

            if(map1.get("AccountId")!=null&& !map1.get("AccountId").toString().equals("")){
                String AccountId=map1.get("AccountId").toString();
                AccountId=iSecretEncodeDecodeService.decode(AccountId);
                map1.put("AccountId",AccountId.substring(0,3)+"****"+AccountId.substring(7,AccountId.length()));
            }
        }
        map.put("items",listMap);
        if(listMap.size()>0){
            list = em.createNativeQuery(sqlStr1.replace("SQLSTR","count(1) cn ")).getResultList();
            totalCount = Integer.parseInt(list.get(0).toString());
        }
        map.put("totalCount",totalCount);
        return map;
    }


    /***
     * 商品列表
     * @param pageIndex
     * @param pageSize
     * @param filters
     * @return
     */
    @Override
    public Map<String,Object> getProductFilters(Integer pageIndex,Integer pageSize,List<FiltersUtils> filters){
        Map<String,Object> map=new HashMap<String,Object>();
        int start = pageIndex * pageSize;
        int end = (start + 1 + pageSize);
        //动态条件
        String sqlStr="";
        Integer totalCount=0;
        List<Map<String, Object>> listMap=null;
        sqlStr=EsUtils.getFilterString(filters);
        String sqlStr2=" A.*,row_number() over(  order by A.ProductCode desc  )  as rownum ";
        String sqlStr1=" SELECT SQLSTR FROM (SELECT p.ProductCode,p.ProductObject,p.ProductName,p.ProductDesc,p.ProductType,p.Manufacturer,(ISNULL(p.PurchasePrice, 0)) PurchasePrice,p.Amount,p.State,p.IsDelete,p.ProductText,p.CreationDate,p.LastModified,(ISNULL(p.MarketPrice, 0)) MarketPrice,p.MarketIng,t.TypeName from "+
                " mem_ingProduct p LEFT JOIN mem_ingProductType t ON p.ProductType = t.TypeId WHERE p.IsDelete = 1) as A where 1=1 "+sqlStr ;
        //查询订单sql
        String sql = " select * from ( " + sqlStr1.replace("SQLSTR",sqlStr2) +
                "  )AAA   where AAA.rownum > "+start+" and AAA.rownum < "+end+"  ORDER BY AAA.LastModified desc  ";

        List list=em.createNativeQuery(sql).getResultList();

        //List序列化
        String[] key = {"ProductCode","ProductObject","ProductName","ProductDesc","ProductType","Manufacturer","PurchasePrice","Amount","State","IsDelete","ProductText","CreationDate","LastModified","MarketPrice","MarketIng","TypeName"};
        listMap= transferToMap(key,list);
        //商品图片
        for(Map<String, Object> mp:listMap){
            mp.put("dt",getProductPor(String.valueOf(mp.get("ProductCode"))));
        }
        map.put("items",listMap);
        if(listMap.size()>0){
            list = em.createNativeQuery(sqlStr1.replace("SQLSTR","count(1) cn ")).getResultList();
            totalCount = Integer.parseInt(list.get(0).toString());
        }
        map.put("totalCount",totalCount);
        return map;
    }


    /***
     * 会员权益列表
     * @param pageIndex
     * @param pageSize
     * @param filters
     * @return
     */
    @Override
    public Map<String,Object> getProductLevel(Integer pageIndex,Integer pageSize,List<FiltersUtils> filters){
        Map<String,Object> map=new HashMap<String,Object>();
        int start = pageIndex * pageSize;
        int end = (start + 1 + pageSize);
        //动态条件
        String sqlStr="";
        Integer totalCount=0;
        List<Map<String, Object>> listMap=null;
        sqlStr=EsUtils.getFilterString(filters);
        String sqlStr2=" A.*,row_number() over(  order by A.LastModified desc  )  as rownum ";
        String sqlStr1=" SELECT SQLSTR FROM ( SELECT p.ProductCode,p.ProductObject,p.ProductName,p.ProductDesc,p.ProductType,p.Manufacturer,(ISNULL(p.PurchasePrice, 0)) PurchasePrice,p.Amount,p.State,p.LastModified,t.TypeName,l.MarketIng,(ISNULL(l.MarketPrice, 0)) MarketPrice,l.LevelId,p.MarketIng as MarketIng2,p.MarketPrice as MarketPrice2 from mem_ingProductLevel l " +
                       "   LEFT JOIN mem_ingProduct p ON l.ProductCode = p.ProductCode LEFT JOIN mem_ingProductType t ON p.ProductType = t.TypeId WHERE p.IsDelete = 1) as A where 1=1 "+sqlStr ;
        //查询订单sql
        String sql = " select * from ( " + sqlStr1.replace("SQLSTR",sqlStr2) +
                "  )AAA   where AAA.rownum > "+start+" and AAA.rownum < "+end+"  ORDER BY AAA.LastModified desc  ";

        List list=em.createNativeQuery(sql).getResultList();

        //List序列化
        String[] key = {"ProductCode","ProductObject","ProductName","ProductDesc","ProductType","Manufacturer","PurchasePrice","Amount","State","LastModified","TypeName","MarketIng","MarketPrice","LevelId","MarketIng2","MarketPrice2"};
        listMap= transferToMap(key,list);

        map.put("items",listMap);
        if(listMap.size()>0){
            list = em.createNativeQuery(sqlStr1.replace("SQLSTR","count(1) cn ")).getResultList();
            totalCount = Integer.parseInt(list.get(0).toString());
        }
        map.put("totalCount",totalCount);
        return map;
    }

    /***
     * 有效等级
     * @return
     */
    @Override
    public List<Map<String, Object>> getLevel() {
        List<Map<String, Object>> listMap=null;
        String sql="SELECT id as value,'0' as parentValue,name as label from mem_user_level";
        List list=em.createNativeQuery(sql).getResultList();
        String[] key = {"value","parentValue","label"};
        return transferToMap(key,list);
    }


    /***
     * 获取产品日志
     * @param productCode
     * @return
     */
    @Override
    public Map<String, Object> getProductLog(String productCode) {
        Map<String, Object> map=new HashMap<String,Object>();
        List<MemIngProductLog>list = userProductLogRepository.findByValueOrderByCreationDate(productCode);
        map.put("obj",list);
        return map;
    }


    /***
     * 获取产品价位
     * @param productCode
     * @return
     */
    @Override
    public Map<String, Object> getProductLevel(String productCode) {
        Map<String, Object> map=new HashMap<String,Object>();
        String sql="SELECT l.name,l.[level],l.id,p.ProductCode,m.MarketIng,m.MarketPrice FROM [mem_user_level] l LEFT JOIN mem_ingProductLevel m ON m.levelId=l.id AND m.ProductCode='"+productCode+"' LEFT JOIN mem_ingProduct p ON p.ProductCode=M.ProductCode";
        List list=em.createNativeQuery(sql).getResultList();
        String[] key = {"name","level","id","ProductCode","MarketIng","MarketPrice"};
        map.put("obj",transferToMap(key,list));
        return map;
    }

    /**
     * 商品定价
     * @param product
     * @param filter
     * @return
     */
    @Override
    public boolean addMemProductLevel(String product, List<FiltersUtils> filter,String mId,String mName) {

        for(FiltersUtils f:filter){
               if(product!=null && f.getId()!=null&&(f.getMarketPrice()!=null || f.getMarketIng()!=null)){
                //获取该商品等级是否有定价
                List<Map<String, Object>> list = em.createNativeQuery("select PlId from mem_ingProductLevel WHERE ProductCode='" + product + "' AND levelId='" + f.getId() + "'").getResultList();
                MemIngProductLevel meLevel=new MemIngProductLevel();
                String PlId="";
                if(list.size()>0 ){//修改
                    PlId = String.valueOf(list.get(0));
                }else {//没有添加
                    PlId=getGeneratID();
                }
                meLevel.setPlId(PlId);
                meLevel.setCreationDate(new Date());
                meLevel.setProductCode(product);
                meLevel.setLevelId(f.getId());
                meLevel.setMarketIng(Integer.parseInt(f.getMarketIng()==null?"0":f.getMarketIng()));
                meLevel.setMarketPrice(Integer.parseInt(f.getMarketPrice()==null?"0":f.getMarketPrice()));
                userProductLevelRepository.save(meLevel);

            }
        }
        String str="修改特权定价";
        MemIngProductLog ulog=new MemIngProductLog();
        ulog.setLogId(getGeneratID());
        ulog.setCreationDate(new Date());
        ulog.setMemberId(mId);
        ulog.setKey(str);
        ulog.setText(str);
        ulog.setValue(product);
        ulog.setMemberName(mName);
        userProductLogRepository.save(ulog);
        return false;
    }

    @Override
    public boolean editMemProductLevel(MemIngProduct memIngProduct,String mId,String mName) {
        userProductRepository.save(memIngProduct);
        String str="产品下架";
        if(memIngProduct.getState()==1){
            str="产品上架";
        }
        MemIngProductLog ulog=new MemIngProductLog();
        ulog.setLogId(getGeneratID());
        ulog.setCreationDate(new Date());
        ulog.setMemberId(mId);
        ulog.setKey(str);
        ulog.setText(str);
        ulog.setMemberName(mName);
        ulog.setValue(memIngProduct.getProductCode());
        userProductLogRepository.save(ulog);
        return false;
    }

    /***
     * 商品类目
     * @param pageIndex
     * @param pageSize
     * @param filters
     * @return
     */
    @Override
    public Map<String, Object> AllproductType(Integer pageIndex, Integer pageSize, List<FiltersUtils> filters) {
        int start = pageIndex * pageSize;
        int end = (start + 1 + pageSize);
        Map<String,Object> map=new HashMap<String,Object>();
        //动态条件
        String sqlStr="";
        Integer totalCount=0;
        List<Map<String, Object>> listMap=null;
        sqlStr=EsUtils.getFilterString(filters);
        String sqlStr2=" t.TypeId,t.TypeName,t.CreationDate ,(SELECT count(1) FROM mem_ingProduct WHERE ProductType=t.TypeId) as ProductCn,row_number() over(order by t.CreationDate desc )  as rownum ";
        String sqlStr1=" select SQLSTR from mem_ingProductType t where 1=1 "+ sqlStr ;

        String sql = " select * from ( " + sqlStr1.replace("SQLSTR",sqlStr2) +
                "  )AAA   where AAA.rownum > "+start+" and AAA.rownum < "+end+"  ORDER BY AAA.CreationDate desc  ";

        List list=em.createNativeQuery(sql).getResultList();

        //List序列化
        String[] key = {"TypeId","TypeName","CreationDate","ProductCn"};
        listMap= transferToMap(key,list);

        map.put("items",listMap);
        if(listMap.size()>0){
            list = em.createNativeQuery(sqlStr1.replace("SQLSTR","count(1) cn ")).getResultList();
            totalCount = Integer.parseInt(list.get(0).toString());
        }
        map.put("totalCount",totalCount);
        return map;
    }

    /***
     * 新增商品类目
     * @param filter
     * @return
     */
    @Override
    public boolean addMemProductType(FiltersUtils filter) {
        String id="";
        if(filter.getCode()==1){
            id=getGeneratID();
        }else{
            id=filter.getTypeId();
        }
        MemIngProductType me=new MemIngProductType();
        me.setTypeId(id);
        me.setTypeName(filter.getTypeName());
        me.setCreationDate(new Date());
        userProductTypeRepository.save(me);
        return false;
    }


    /***
     * 修改商品指定类目
     * @param filter
     * @return
     */
    @Override
    public boolean editProductType(FiltersUtils filter) {
        String [] products=filter.getProductCode().split(",");
        for(String c:products){
            Optional<MemIngProduct> memIngProduct = userProductRepository.findById(c);
            MemIngProduct m = memIngProduct.get();
            m.setProductType(filter.getTypeId());
            m.setProductCode(c);
            userProductRepository.save(m);
        }

        return false;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean editProductAmount(FiltersUtils filter,String mId,String mName) {
        if(filter.getProductCode()!=null&&filter.getProductCode()!=""){
            MemIngProduct memIngProduct=userProductRepository.findById(filter.getProductCode()).get();
            if(memIngProduct.getAmount()!=null){
                String str="";
                Integer amount=memIngProduct.getAmount();
                if(filter.getCode()==2 && filter.getNum()!=null){
                    amount-=filter.getNum();
                    str=memIngProduct.getAmount()+",减少库存:"+filter.getNum();
                }else if(filter.getCode()==1 && filter.getNum()!=null){
                    amount+=filter.getNum();
                    str=memIngProduct.getAmount()+",增加库存:"+filter.getNum();
                }
                memIngProduct.setAmount(amount);
                userProductRepository.save(memIngProduct);
                MemIngProductLog ulog=new MemIngProductLog();
                ulog.setLogId(getGeneratID());
                ulog.setCreationDate(new Date());
                ulog.setMemberId(mId);
                ulog.setKey(str);
                ulog.setText(str);
                ulog.setMemberName(mName);
                ulog.setValue(memIngProduct.getProductCode());
                userProductLogRepository.save(ulog);
            }
        }
        return false;
    }

    /***
     * 修改商品信息
     * @param memIngProduct
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean addMemProduct(MemIngProduct memIngProduct,String mId,String mName) {
        String str="";
        if(memIngProduct.getProductCode()!=null&& !memIngProduct.getProductCode().equals("")){
            List<MemIngProductPic> piclist = userProductPicRepository.findAllByProductCode(memIngProduct.getProductCode());
            for (MemIngProductPic p:piclist){
                userProductPicRepository.deleteById(p.getPicID());
            }
            str="编辑商品";
            memIngProduct.setCreationDate(new Date());
        }else{
            str="添加商品";
            memIngProduct.setProductCode(getGeneratID());
        }

        memIngProduct.setIsDelete(1);
        memIngProduct.setLastModified(new Date());
        memIngProduct.setPurchasePrice((memIngProduct.getPurchasePrice()!=null?memIngProduct.getPurchasePrice():0));
        memIngProduct.setMarketIng(memIngProduct.getMarketIng());
        memIngProduct.setMarketPrice(memIngProduct.getMarketPrice());
        userProductRepository.save(memIngProduct);
        List<MemIngProductPic> mepic=memIngProduct.getPics();
        Collections.reverse(mepic);
        for(MemIngProductPic pic:mepic){
            if(pic.getUrl()!=null&&pic.getUrl()!=""){
                pic.setPicUrl(pic.getUrl());
                pic.setPicID(getGeneratID());
                pic.setProductCode(memIngProduct.getProductCode());
                pic.setCreationDate(new Date());
                pic.setIsDelete(1);
                userProductPicRepository.save(pic);
            }
        }
        MemIngProductLog ulog=new MemIngProductLog();
        ulog.setLogId(getGeneratID());
        ulog.setCreationDate(new Date());
        ulog.setMemberId(mId);
        ulog.setKey(str);
        ulog.setText(str);
        ulog.setMemberName(mName);
        ulog.setValue(memIngProduct.getProductCode());
        userProductLogRepository.save(ulog);
        return false;
    }

    /***
     * 审核订单
     * @param filter
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public String editOrder(FiltersUtils filter,String mId,String mName) {
        String jsonResult="";
        MemIngOrders or = userOrdersRepository.findById(filter.getOrderCode()).get();

        MemIngProduct memIngProduct = userProductRepository.findById(or.getProductCode()).get();
        if(memIngProduct.getAmount()<=0){
            return "库存不足，审核失败！";
        }

        Integer price=or.getMemIngOrdersPay().getPayPirce();//金额
        Integer ing=or.getMemIngOrdersPay().getIntegral();//积分
        WeixinUserInfo weixinUserInfo = weixinUserInfoRepository.queryBySecretPhone(or.getAccountId()).get();

        if(or.getMemIngProduct().getProductObject().equals("1") || or.getMemIngProduct().getProductObject()==1){//实物商品
                if(or.getOrderState()!=5) {
                    if (or.getOrderState() == 2) {//发货
                        or.setOrderState(3);
                    } else if (or.getOrderState() == 3) {//完成
                        //剩余积分大于所需支付积分
                        //if(weixinUserInfo.getPoint()!=null && weixinUserInfo.getPoint()>ing){
                            or.setOrderState(5);
                            /*String str="用户下单扣减积分："+(weixinUserInfo.getPoint()+ing)+" - "+ing+" = "+(weixinUserInfo.getPoint());
                            //库存减1,积分减
                            UserPointLog log=new UserPointLog();
                            log.setId(getGeneratID());
                            log.setPayment(Double.valueOf(price));
                            log.setOrderAmount(Double.valueOf(price));
                            log.setDiscountedPrice(0.0);
                            log.setTransportCost(Double.valueOf(or.getMemIngOrdersPay().getPostagePrice()));
                            log.setValue(ing);
                            log.setIncrease(false);
                            log.setDataCode(or.getOrdersCode());
                            log.setSecretPhone(or.getAccountId());
                            log.setTerminalAction(str);
                            log.setTerminalCode(str);
                            log.setTerminalName("后台订单审核");
                            log.setAction("订单扣减");
                            log.setCrtDate(new Date());
                            log.setLastUpdate(new Date());
                            log.setOrigin(weixinUserInfo.getPoint()+ing);
                            log.setBalance(weixinUserInfo.getPoint());
                            userPointLogRepository.save(log);*/
                            memIngProduct.setAmount(memIngProduct.getAmount()-or.getAmount());
                            userProductRepository.save(memIngProduct);
                            //weixinUserInfo.setPoint(weixinUserInfo.getPoint()-ing);
                            //weixinUserInfoRepository.save(weixinUserInfo);
                        /*}else{
                            return "用户积分余额不足！";
                        }*/
                    }
                    userOrdersRepository.save(or);
                }
            }else if(or.getMemIngProduct().getProductObject().equals("2") || or.getMemIngProduct().getProductObject()==2){//虚拟商品
                if(or.getOrderState()!=5) {

                    //if(weixinUserInfo.getPoint()!=null && weixinUserInfo.getPoint()>ing){
                        or.setOrderState(5);
                        /*String str="用户下单扣减积分："+(weixinUserInfo.getPoint()+ing)+" - "+ing+" = "+weixinUserInfo.getPoint();
                        //库存减1,积分减
                        UserPointLog log=new UserPointLog();
                        log.setId(getGeneratID());
                        log.setPayment(Double.valueOf(price));
                        log.setOrderAmount(Double.valueOf(price));
                        log.setDiscountedPrice(0.0);
                        log.setTransportCost(Double.valueOf(or.getMemIngOrdersPay().getPostagePrice()));
                        log.setValue(ing);
                        log.setIncrease(false);
                        log.setDataCode(or.getOrdersCode());
                        log.setSecretPhone(or.getAccountId());
                        log.setTerminalAction(str);
                        log.setTerminalCode(str);
                        log.setTerminalName("后台订单审核");
                        log.setAction("订单扣减");
                        log.setCrtDate(new Date());
                        log.setLastUpdate(new Date());
                        log.setOrigin(weixinUserInfo.getPoint()+ing);
                        log.setBalance(weixinUserInfo.getPoint());
                        userPointLogRepository.save(log);*/

                        memIngProduct.setAmount(memIngProduct.getAmount()-or.getAmount());
                        userProductRepository.save(memIngProduct);
                        //weixinUserInfo.setPoint(weixinUserInfo.getPoint()-ing);
                        //weixinUserInfoRepository.save(weixinUserInfo);
                    /*}else{
                        return "用户积分余额不足！";
                    }*/
                    userOrdersRepository.save(or);
                }
                jsonResult="兑换说明："+filter.getOrdesc()+",兑换链接："+filter.getOrurl();
                jsonResult += ",微信推送状态："+sendMsg(jsonResult,or.getOpenid());
            }

        MemIngProductLog ulog=new MemIngProductLog();
        ulog.setLogId(getGeneratID());
        ulog.setCreationDate(new Date());
        ulog.setMemberId(mId);
        ulog.setKey("审核订单");
        ulog.setText(jsonResult);
        ulog.setMemberName(mName);
        ulog.setValue(filter.getOrderCode());
        userProductLogRepository.save(ulog);
        return "审核成功！";
    }

    //取消订单
    @Transactional(rollbackFor = Exception.class)
    @Override
    @Modifying
    public String callOrder(FiltersUtils filter,String mId,String mName) {
        String jsonResult="";
        Optional<MemIngOrders> or1 = userOrdersRepository.findById(filter.getOrderCode());
        MemIngOrders or = or1.get();
        if(or.getOrderState()!=5){
            //获取会员当前积分
            WeixinUserInfo weixinUserInfo = weixinUserInfoRepository.queryBySecretPhone(or.getAccountId()).get();
            MemIngProduct mpd = getProductInfoV2(or.getOrdersCode(),or.getAccountId());

            Integer price=or.getMemIngOrdersPay().getPayPirce();//金额
            Integer ing=or.getMemIngOrdersPay().getIntegral();//积分
            int res=updateWechatUserVersion(weixinUserInfo.getSecretPhone(),weixinUserInfo.getPoint()+ing);
            if(res<=0){
                return "系统繁忙，稍后再试！";
            }

            or.setOrderState(6);
            userOrdersRepository.save(or);

            String str=filter.getOredit()+",取消订单返回积分";

            UserPointLog log=new UserPointLog();
            log.setId(getGeneratID());
            log.setPayment(Double.valueOf(price));
            log.setOrderAmount(Double.valueOf(price));
            log.setDiscountedPrice(0.0);
            log.setTransportCost(Double.valueOf(or.getMemIngOrdersPay().getPostagePrice()));
            log.setValue(ing);
            log.setIncrease(true);
            log.setDataCode(or.getOrdersCode());
            log.setSecretPhone(or.getAccountId());
            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);

            //weixinUserInfo.setPoint(weixinUserInfo.getPoint()+ing);
            //weixinUserInfoRepository.save(weixinUserInfo);

            //开通支付功能添加退款/price
            MemIngProductLog ulog=new MemIngProductLog();
            ulog.setLogId(getGeneratID());
            ulog.setCreationDate(new Date());
            ulog.setMemberId(mId);
            ulog.setKey(str);
            ulog.setText(str);
            ulog.setMemberName(mName);
            ulog.setValue(filter.getOrderCode());
            userProductLogRepository.save(ulog);
            jsonResult = sendMsg(str,or.getOpenid());
        }
        return jsonResult;
    }

    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 List<Map<String,Object>> getProductPor(String productCode){
        List<Map<String, Object>> listMap=null;
        String sql="SELECT top 8 PicID,ProductCode,PicUrl,CreationDate FROM mem_ingProductPic WHERE IsDelete='1' AND cast(PicUrl as varchar(max))!='' AND ProductCode='"+productCode+"' ORDER BY CreationDate DESC";
        List list=em.createNativeQuery(sql).getResultList();
        String[] key = {"PicID","ProductCode","PicUrl","CreationDate"};
        return transferToMap(key,list);
    }

    private List<Map<String, Object>> transferToMap(String[] key, List list){
        Map<String,Object> map = null;
        List<Map<String, Object>>  resultList = new java.util.ArrayList();
        for(int j = 0; j < list.size(); j++){
            Object[] objArr = (Object[])list.get(j);
            map = new HashMap<String,Object>();
            for(int i = 0; i < key.length; i++){
                if(key[i].equals("OrderTime")){
                    map.put(key[i],String.valueOf(objArr[i]));
                }else{
                    map.put(key[i],objArr[i]);
                }
            }
            resultList.add(map);
        }
        return resultList;
    }

    public String sendMsg(String message,String openid) {
        JSONObject json=new JSONObject();
        json.put("message",message);
        json.put("openid",openid);
        String retStr= null;
        try {
            retStr = EsUtils.post(json,"https://mem.360lj.com/weixin/sendMsg");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return retStr;
    }

    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;
    }

}
