package com.sqx.modules.shopping.service.impl;

import com.alibaba.fastjson.JSON;
import com.sqx.modules.app.entity.*;
import com.sqx.modules.app.service.*;
import com.sqx.modules.common.service.CommonInfoService;
import com.sqx.modules.material.service.MaterialArtificerService;
import com.sqx.modules.shopping.dao.*;
import com.sqx.modules.shopping.entity.*;
import com.sqx.modules.shopping.service.*;
import com.sqx.modules.shopping.utils.AmountCalUtil;
import com.sqx.modules.shopping.utils.DateUtil;
import com.sqx.modules.shopping.utils.Result;
import com.sqx.modules.shopping.utils.ResultUtil;
import com.sqx.modules.shopping.utils.excel.ExcelData;
import org.apache.commons.lang3.StringUtils;
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.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class SelfOrdersServiceImpl implements OrdersService {
    @Autowired
    private OrdersRepository ordersRepository;
    @Autowired
    private OrdersJpaRepository jpaRepository;
    @Autowired
    private OrdersRelationService ordersRelationService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private SelfAliPayService selfAliPayService;
    @Autowired
    private SelfWXService selfWXService;
    @Autowired
    private CommonInfoService commonRepository;
    @Autowired
    private SelfOrdersRemindJpaRepository selfOrdersRemindJpaRepository;
    @Autowired
    private SelfGoodsVirtualService selfGoodsVirtualService;
    @Autowired
    private OrdersRelationJpaRepository ordersRelationJpaRepository;
    @Autowired
    private UserService userService;
    @Autowired
    private GoodsTypeJpaRepository goodsJpaTypeRepository;
    @Autowired
    private SelfGoodsSkuService skuService;
    @Autowired
    private UserMoneyService userMoneyService;
    @Autowired
    private UserMoneyDetailsService userMoneyDetailsService;
    @Autowired
    private UserVipService userVipService;
    @Autowired
    private MaterialArtificerService materialArtificerService;
    @Autowired
    private UserSadDetailsService userSadDetailsService;



    /**
     * 订单列表
     * @param page
     * @param size
     * @param orderNum
     * @param status
     * @return
     */
    @Override
    public Result findAll(Integer page, Integer size, String orderNum, String status, String title,String mobile, String startTime, String endTime,String sendWay) {
        //根据时间排序
        Pageable pageable = PageRequest.of(page, size, Sort.by(new Sort.Order(Sort.Direction.DESC, "createAt")));
        // 构造自定义查询条件
        Specification<SelfOrders> queryCondition = new Specification<SelfOrders>() {
            @Override
            public Predicate toPredicate(Root<SelfOrders> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicateList = new ArrayList<>();
                if (StringUtils.isNotEmpty(orderNum)) {
                    predicateList.add(criteriaBuilder.equal(root.get("orderNum"), orderNum));
                }
                if (!"0".equals(status)) {
                    predicateList.add(criteriaBuilder.equal(root.get("status"), status));
                }
                if (StringUtils.isNotEmpty(title)) {
                    predicateList.add(criteriaBuilder.like(root.get("title"), "%"+title+"%"));
                }
                if (StringUtils.isNotEmpty(mobile)) {
                    predicateList.add(criteriaBuilder.equal(root.get("mobile"), mobile));
                }
                if (StringUtils.isNotEmpty(startTime)){
                    predicateList.add(criteriaBuilder.greaterThanOrEqualTo(root.get("createAt"), startTime));
                }
                if (StringUtils.isNotEmpty(endTime)){
                    predicateList.add(criteriaBuilder.lessThanOrEqualTo(root.get("createAt"), endTime));
                }
                if (StringUtils.isNotEmpty(sendWay)){
                    predicateList.add(criteriaBuilder.lessThanOrEqualTo(root.get("sendWay"), sendWay));
                }
                return criteriaBuilder.and(predicateList.toArray(new Predicate[predicateList.size()]));
            }
        };
        Page<SelfOrders> all = jpaRepository.findAll(queryCondition, pageable);
        List<SelfOrders> list = all.getContent();
        List<GoodsType> allType = goodsJpaTypeRepository.findAll();
        for (SelfOrders g : list) {
            for (GoodsType goodsType : allType) {
                Long typeId = g.getType();
                if (typeId!=null && typeId.equals(goodsType.getId())){
                    g.setGoodsType(goodsType);
                }
            }
        }
        return ResultUtil.success(all);
    }


    @Override
    public ExcelData listExcel( String orderNum, String status, String title,String mobile, String startTime, String endTime,String sendWay) {
        // 构造自定义查询条件
        Specification<SelfOrders> queryCondition = new Specification<SelfOrders>() {
            @Override
            public Predicate toPredicate(Root<SelfOrders> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicateList = new ArrayList<>();
                if (StringUtils.isNotEmpty(orderNum)) {
                    predicateList.add(criteriaBuilder.equal(root.get("orderNum"), orderNum));
                }
                if (!"0".equals(status)) {
                    predicateList.add(criteriaBuilder.equal(root.get("status"), status));
                }
                if (StringUtils.isNotEmpty(title)) {
                    predicateList.add(criteriaBuilder.like(root.get("title"), "%"+title+"%"));
                }
                if (StringUtils.isNotEmpty(mobile)) {
                    predicateList.add(criteriaBuilder.equal(root.get("mobile"), mobile));
                }
                if (StringUtils.isNotEmpty(startTime)){
                    predicateList.add(criteriaBuilder.greaterThanOrEqualTo(root.get("createAt"), startTime));
                }
                if (StringUtils.isNotEmpty(endTime)){
                    predicateList.add(criteriaBuilder.lessThanOrEqualTo(root.get("createAt"), endTime));
                }
                if (StringUtils.isNotEmpty(sendWay)){
                    predicateList.add(criteriaBuilder.lessThanOrEqualTo(root.get("sendWay"), sendWay));
                }
                return criteriaBuilder.and(predicateList.toArray(new Predicate[predicateList.size()]));
            }
        };
        List<SelfOrders> all = jpaRepository.findAll(queryCondition);
        ExcelData data = new ExcelData();
        data.setName("订单列表");
        List<String> titles = new ArrayList();
        titles.add("商品图片");titles.add("商品标题");titles.add("商品规格");titles.add("商品个数");
        //titles.add("订单备注");
        titles.add("订单类型");titles.add("订单号");titles.add("收货人");
        titles.add("手机号");titles.add("详细地址");titles.add("商品价格");titles.add("支付金额");
        titles.add("佣金");titles.add("退款原因");titles.add("驳回原因");titles.add("支付方式");titles.add("创建时间");
        titles.add("付款时间");titles.add("收货时间");titles.add("订单状态");
        data.setTitles(titles);
        List<List<Object>> rows = new ArrayList();
        for(SelfOrders orders:all){
            List<Object> row = new ArrayList();
            row.add(orders.getImg());row.add(orders.getTitle());row.add(StringUtils.isEmpty(orders.getDetailJson())?"无":orders.getDetailJson());row.add(orders.getNumber());
            row.add(StringUtils.isEmpty(orders.getDescrition())?"未填写":orders.getDescrition());
            row.add(orders.getOrderNum());row.add(StringUtils.isEmpty(orders.getConsignee())?"":orders.getConsignee());
            row.add(StringUtils.isEmpty(orders.getMobile())?"":orders.getMobile());row.add(StringUtils.isEmpty(orders.getDetail())?"":orders.getDetail());row.add(orders.getPrice());row.add(orders.getPayMoney());
            row.add(orders.getCommissionPrice());row.add(StringUtils.isEmpty(orders.getRefund())?"":orders.getRefund());row.add(StringUtils.isEmpty(orders.getRefusedRefund())?"":orders.getRefusedRefund());
            //1app微信 2微信公众号 3微信小程序 4app支付宝 5H5支付宝 6零钱 7积分
            if(orders.getPayWay()==null) {
                row.add("未支付");
            }else if(orders.getPayWay()==1){
                row.add("app微信");
            }else if(orders.getPayWay()==2){
                row.add("微信公众号");
            }else if(orders.getPayWay()==3){
                row.add("微信小程序");
            }else if(orders.getPayWay()==4){
                row.add("app支付宝");
            }else if(orders.getPayWay()==5){
                row.add("H5支付宝");
            }else if(orders.getPayWay()==6){
                row.add("零钱");
            }else if(orders.getPayWay()==7){
                row.add("积分");
            }else{
                row.add("未知");
            }
            row.add(orders.getCreateAt());
            row.add(StringUtils.isEmpty(orders.getPayTime())?"":orders.getPayTime());
            row.add(StringUtils.isEmpty(orders.getFinishTime())?"":orders.getFinishTime());
            //1待付款 2已付款 3已发货 4已收货 5已取消 6退款中 7已退款 8拒绝退款 9拼团中 10已评价
            if(orders.getStatus()==1){
                row.add("待付款");
            }else if(orders.getStatus()==2){
                row.add("已付款");
            }else if(orders.getStatus()==3){
                row.add("已发货");
            }else if(orders.getStatus()==4){
                row.add("已收货");
            }else if(orders.getStatus()==5){
                row.add("已取消");
            }else if(orders.getStatus()==6){
                row.add("退款中");
            }else if(orders.getStatus()==7){
                row.add("已退款");
            }else if(orders.getStatus()==8){
                row.add("拒绝退款");
            }else if(orders.getStatus()==9){
                row.add("拼团中");
            }else if(orders.getStatus()==10){
                row.add("已评价");
            }else{
                row.add("未知");
            }
            rows.add(row);
        }
        data.setRows(rows);
        return data;
    }




    /**
     * 用户端订单列表
     * @param page
     * @param size
     * @param userId
     * @param status
     * @return
     */
    @Override
    public Result findMyList(Integer page, Integer size, String userId, String status) {
        //根据时间排序
        Pageable pageable = PageRequest.of(page, size, Sort.by(new Sort.Order(Sort.Direction.DESC, "createAt")));
        // 构造自定义查询条件
        Specification<SelfOrders> queryCondition = new Specification<SelfOrders>() {
            @Override
            public Predicate toPredicate(Root<SelfOrders> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicateList = new ArrayList<>();
                if (StringUtils.isNotEmpty(userId)) {
                    predicateList.add(criteriaBuilder.equal(root.get("userId"), userId));
                }
                if (!"0".equals(status)) {
                    predicateList.add(criteriaBuilder.equal(root.get("status"), status));
                }
                return criteriaBuilder.and(predicateList.toArray(new Predicate[predicateList.size()]));
            }
        };
        Page<SelfOrders> all = jpaRepository.findAll(queryCondition, pageable);
        //处理订单分销
        List<SelfOrderRelation> all1 = ordersRelationJpaRepository.findAll();
        List<GoodsType> allType = goodsJpaTypeRepository.findAll();
        for (SelfOrders o : all.getContent()) {
            List<SelfOrderRelation> relationList = new ArrayList<>();
            for (SelfOrderRelation r : all1) {
                if (o.getId().toString().equals(r.getOrderId().toString())){
                    relationList.add(r);
                }
            }
            for (GoodsType goodsType : allType) {
                Long typeId = o.getType();
                if (typeId!=null && typeId.equals(goodsType.getId())){
                    o.setGoodsType(goodsType);
                }
            }
            o.setRelationList(relationList);
        }
        return ResultUtil.success(all);
    }

    /**
     * 生成订单编号
     * @return
     */
    private String getGeneralOrder() {
        Date date=new Date();
        String newString = String.format("%0"+4+"d", (int)((Math.random()*9+1)*1000));
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String format = sdf.format(date);
        return format+newString;
    }

    /**
     * 保存订单
     * @param entity
     * @return
     */
    @Override
    public Result saveBody(SelfOrders entity) {
        /*
        前端传入：用户id、收货人、手机号、详细地址、商品类型、商品标题、商品图片、商品描述、商品价格、商品个数、支付金额、
        后台生成：创建时间、订单号、订单状态
         */
        entity.setCreateAt(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); //创建时间
        entity.setOrderNum(this.getGeneralOrder()); //订单号
        entity.setStatus(1); //订单状态待支付
        /*
         * 支付金额 需要后端去验证金额
         */
//        UserEntity userById = userService.selectUserById(entity.getUserId());
        Long goodsId = entity.getGoodsId();
        SelfGoods byId = goodsService.findById(goodsId);
        if(byId.getStatus().equals(2)){
            return ResultUtil.error(-200,"商品已经下架了！");
        }

        if (!skuService.checkStock(entity.getSkuId(), entity.getNumber())){
            return ResultUtil.error(-1,entity.getTitle()+"库存不足");
        }
        skuService.lessStock(entity.getSkuId(), entity.getNumber()); //sku库存减少对应数量

        entity.setPrice(byId.getMemberPrice());
        entity.setMemberPrice(byId.getMemberPrice());
//        UserVip userVip = userVipService.selectUserVipByUserId(userById.getUserId());
//        if(userVip==null || userVip.getIsVip()!=1){
//            Double aDouble = AmountCalUtil.moneyMul(byId.getPrice(), entity.getNumber());
//            entity.setPayMoney(aDouble);
//        }else{
//            Double aDouble = AmountCalUtil.moneyMul(byId.getMemberPrice(), entity.getNumber());
//            entity.setPayMoney(aDouble);
//        }
        if(entity.getSendWay()==1 && byId.getPostagePrice()!=null){
            entity.setPayMoney(AmountCalUtil.add(entity.getPayMoney(),byId.getPostagePrice()));
        }


        if(entity.getSfrxdh()!=null && entity.getSfrxdh()>0){
            UserSadDetails userMoneyDetails=new UserSadDetails();
            userMoneyService.updateSad(2,entity.getUserId(),entity.getSfrxdh());
            //查询用户当前余额
            UserMoney userNowMoney = userMoneyService.selectUserMoneyByUserId(entity.getUserId());
            //插入余额
            userMoneyDetails.setBalance(userNowMoney.getSad());
            //插入操作类型为已操作用户余额
            userMoneyDetails.setManipulateType(2);
            userMoneyDetails.setUserId(entity.getUserId());
            userMoneyDetails.setTitle("[购买商品]标题："+entity.getTitle());
            userMoneyDetails.setContent("盛安豆优惠："+entity.getSfrxdh());
            userMoneyDetails.setType(2);
            userMoneyDetails.setMoney(userNowMoney.getSad());
            userMoneyDetails.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            userMoneyDetails.setBlRole(2);
            userMoneyDetails.setBlFlag(1);
            userSadDetailsService.insert(userMoneyDetails);
        }

        //添加盛安豆
        this.addSad(entity);


        return ResultUtil.success(jpaRepository.save(entity));
    }

    @Override
    public Result updateBody(SelfOrders entity) {
        Long goodsId = entity.getGoodsId();
        SelfGoods byId = goodsService.findById(goodsId);
        UserEntity userById = userService.selectUserById(entity.getUserId());
        UserVip userVip = userVipService.selectUserVipByUserId(userById.getUserId());
        if(userVip==null || userVip.getIsVip()!=1){
            Double aDouble = AmountCalUtil.moneyMul(byId.getPrice(), entity.getNumber());
            entity.setPayMoney(aDouble);
        }else{

            Double aDouble = AmountCalUtil.moneyMul(byId.getMemberPrice(), entity.getNumber());
            entity.setPayMoney(aDouble);
        }
        entity.setPayMoney(AmountCalUtil.add(entity.getPayMoney(),byId.getPostagePrice()));
        return ResultUtil.success(jpaRepository.save(entity));
    }

    @Override
    public Result findOne(Long id) {
        return ResultUtil.success(jpaRepository.findById(id).orElse(null));
    }

    @Override
    public Result delete(Long id) {
        jpaRepository.deleteById(id);
        return ResultUtil.success();
    }

    /**
     * 收入统计
     * @param data
     * @param way
     * @return
     */
    @Override
    public Result income(String data, int way) {
        List<SelfOrders> list =  ordersRepository.findByStatus();
        switch (way){
            case 1: data = data.substring(0,4); break; //年，截取前四个
            case 2: data = data.substring(0,7); break; //月，前6
            default: break; //日，或者其他不做处理
        }
        BigDecimal sum0 = new BigDecimal("0.00"); //总收入
        BigDecimal sum1 = new BigDecimal("0.00"); //收入
        BigDecimal pay1 = new BigDecimal("0.00"); //微信
        BigDecimal pay2 = new BigDecimal("0.00"); //支付宝
        BigDecimal pay3 = new BigDecimal("0.00"); //余额
        int refundNum=0;
        BigDecimal refundMoney = new BigDecimal("0.00"); //退款金额
        for (SelfOrders o : list) {
            BigDecimal money = o.getPayMoney()== null?new BigDecimal("0.00"):BigDecimal.valueOf(o.getPayMoney()); //订单金额
            sum0 = sum0.add(money);
            if (StringUtils.isNotEmpty(o.getPayTime()) && o.getPayTime().contains(data)){
                sum1 = sum1.add(money);
                switch (o.getPayWay()){ //根据支付方式细分：支付方式（1app微信 2微信公众号 3微信小程序 4app支付宝 5H5支付宝 6零钱）
                    case 1 : pay1 = pay1.add(money); break;
                    case 2 : pay1 = pay1.add(money); break;
                    case 3 : pay1 = pay1.add(money); break;
                    case 4 : pay2 = pay2.add(money); break;
                    case 5 : pay2 = pay2.add(money); break;
                    case 6 : pay3 = pay3.add(money); break;
                    default: break;
                }
            }
            if(o.getStatus().equals(7)){
                refundNum++;
                refundMoney=refundMoney.add(money);
            }
        }
        BigDecimal refundIncome = sum1.subtract(refundMoney);
        Map<String, Object> map = new HashMap<>();
        map.put("sum0", sum0);
        map.put("sum1", sum1);
        map.put("pay1", pay1);
        map.put("pay2", pay2);
        map.put("pay3", pay3);
        map.put("refundMoney", refundMoney);
        map.put("refundIncome", refundIncome);
        map.put("refundNum", refundNum);
        return ResultUtil.success(map);
    }

    /**
     * 订单成交量统计
     * @param data
     * @return
     */
    @Override
    public Result statistical(String data) {
        // 构造自定义查询条件
        Specification<SelfOrders> queryCondition = new Specification<SelfOrders>() {
            @Override
            public Predicate toPredicate(Root<SelfOrders> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicateList = new ArrayList<>();
                predicateList.add(criteriaBuilder.equal(root.get("status"), 4)); //统计已收货
                return criteriaBuilder.and(predicateList.toArray(new Predicate[predicateList.size()]));
            }
        };
        List<SelfOrders> list = jpaRepository.findAll(queryCondition);
        int sum0 = 0; //年
        int sum1 = 0; //月
        int sum2 = 0; //日
        for (SelfOrders o : list) {
            if (StringUtils.isEmpty(o.getFinishTime())){
                continue;
            }
            if (o.getFinishTime().contains(data.substring(0, 4))){
                String orderTime = o.getFinishTime();
                if (orderTime.contains(data.substring(0, 4))){
                    sum0 ++;
                }
                if (orderTime.contains(data.substring(0, 7))){
                    sum1 ++;
                }
                if (orderTime.contains(data)){
                    sum2 ++;
                }
            }
        }
        Map<String, Object> map = new HashMap<>();
        map.put("sum0", sum0);
        map.put("sum1", sum1);
        map.put("sum2", sum2);
        return ResultUtil.success(map);
    }

    /**
     * 取消订单
     * @param id
     * @return
     */
    @Override
    public Result orderCancel(Long id) {
        SelfOrders orders = jpaRepository.findById(id).orElse(null);
        if (orders.getStatus() == 1){
            skuService.addStock(orders.getSkuId(), orders.getNumber());
            orders.setStatus(5); //设置为已取消
            orders = jpaRepository.save(orders);
            return ResultUtil.success(orders);
        }else {
            return ResultUtil.error(-1, "当前订单不可取消");
        }
    }

    /**
     * 发货
     * @param id
     * @param expressName
     * @param expressNumber
     * @return
     */
    @Override
    public Result express(Long id, String expressName, String expressNumber) {
        SelfOrders orders = jpaRepository.findById(id).orElse(null);
        orders.setExpressName(expressName);
        orders.setExpressNumber(expressNumber);
        orders.setStatus(3); //设置为已发货
        orders.setExpressTime(DateUtil.createTime());
        return ResultUtil.success(jpaRepository.save(orders));
    }
    /**
     * 虚拟商品发货
     * @param id
     * @return
     */
    @Override
    public Result expressVirtual(Long id) {
        SelfOrders orders = jpaRepository.findById(id).orElse(null);
        if (orders.getIsExpress() != 2){ //是否需要发货(1需要发货 2无需发货)
            return ResultUtil.error(-1, "非虚拟商品,发货失败");
        }
        //虚拟商品发货，发货成功为确认收货，否则不做变化
        SelfGoodsVirtual v = this.sendExpress(orders);
        if (v != null){
            orders.setVirtualId(v.getId()); //虚拟商品id
            orders.setExpressTime(DateUtil.createTime()); //发货时间
            orders.setStatus(4); //确认收货
            SelfOrders save = jpaRepository.save(orders);
            return ResultUtil.success(save);
        }else {
            return ResultUtil.error(-1, "虚拟商品库存不足："+orders.getTitle());
        }
    }

    /**
     * 确认收货
     * @param id
     * @return
     */
    @Override
    public Result orderConfirm(Long id) {
        //1.订单设置已收货
        SelfOrders orders = jpaRepository.findById(id).orElse(null);
        orders.setStatus(4); //4已收货
        orders.setFinishTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); //设置完成时间
        //2.订单分销
        List<SelfOrderRelation> list = ordersRelationService.findByOrdersId(id); //订单关联的分销列表
        for (SelfOrderRelation s : list) {
            //立刻到账
            s.setFinishTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            ordersRelationService.addMoney(s);

        }
        Long userId = orders.getUserId();
        //8.商品销量+1
        goodsService.salesAddOne(orders.getGoodsId());

        return ResultUtil.success(jpaRepository.save(orders));
    }


    /**
     * 零钱支付
     * @param id 订单id
     * @return
     */
    @Override
    public Result changePay(String id) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date=sdf.format(new Date());
        String[] ids = id.split(",");
        for (String s : ids) {
            //1.获取订单、用户信息
            SelfOrders orders = jpaRepository.findById(Long.valueOf(s)).orElse(null);
            if(orders==null){
                continue;
            }
            double payMoney = orders.getPayMoney();
            UserMoney userMoney = userMoneyService.selectUserMoneyByUserId(orders.getUserId());
            double money = userMoney.getMoney().doubleValue();
            if (payMoney > money){
                return ResultUtil.error(500,"钱包余额不足！");
            }
            userMoneyService.updateMoney(2,orders.getUserId(),payMoney);
            UserMoneyDetails userMoneyDetails=new UserMoneyDetails();
            //查询用户当前余额
            UserMoney userNowMoney = userMoneyService.selectUserMoneyByUserId(orders.getUserId());
            //插入余额
            userMoneyDetails.setBalance(userNowMoney.getMoney());
            //插入操作类型为已操作用户余额
            userMoneyDetails.setManipulateType(2);
            userMoneyDetails.setUserId(orders.getUserId());
            userMoneyDetails.setTitle("[购买商品]标题："+orders.getTitle());
            userMoneyDetails.setContent("钱包支付："+payMoney);
            userMoneyDetails.setType(2);
            userMoneyDetails.setMoney(BigDecimal.valueOf(payMoney));
            userMoneyDetails.setCreateTime(date);
            userMoneyDetails.setBlRole(2);
            userMoneyDetails.setBlFlag(1);
            userMoneyDetailsService.insert(userMoneyDetails);
            //订单分销
            this.fenXiao(orders);
            //4.支付成功处理订单
            orders.setPayWay(6); //支付方式（1app微信 2微信公众号 3微信小程序 4app支付宝 5H5支付宝 6零钱）
            orders.setPayTime(DateUtil.createTime()); //设置支付时间
            orders.setStatus(2); //订单状态（1待付款 2已付款 3已发货 4已收货 5已取消 6退款中 7已退款 8拒绝退款 9拼团中）
            //虚拟商品处理
            if (orders.getOrderType() == 1) { //普通订单
                if (orders.getIsExpress() == 2){ //是否需要发货(1需要发货 2无需发货)
                    //虚拟商品发货，发货成功为确认收货，否则不做变化
                    SelfGoodsVirtual v = this.sendExpress(orders);
                    if (v != null){
                        orders.setVirtualId(v.getId()); //虚拟商品id
                        orders.setExpressTime(DateUtil.createTime()); //发货时间
                        orders.setStatus(4); //确认收货
                    }
                }else if (orders.getIsExpress() == 3){ //核销订单
                    orders.setStatus(3); //待收货、待使用
                }
            }
            jpaRepository.save(orders);
            //执行物料包添加操作
            materialArtificerService.changePay(orders.getGoodsId(),orders.getUserId(),orders.getNumber());
            //公众号消息通知
            //userService.orderPay(orders.getUserId(), orders.getOrderNum(),orders.getPayMoney().toString(),orders.getCreateAt());
        }
        return ResultUtil.success();
    }

    //添加盛安豆及盛安豆记录
    public void addSad(SelfOrders orders){
        Long goodsId = orders.getGoodsId();
        SelfGoods goodsPar = goodsService.findById(goodsId);
        Double sad = 0.0;
        if(goodsPar.getSad()>0){
            sad = Double.parseDouble(goodsPar.getSad()+"") * orders.getNumber();
        }
        if(sad>0){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String date=sdf.format(new Date());
            userMoneyService.updateSad(1,orders.getUserId(),sad);
            UserSadDetails userMoneyDetails=new UserSadDetails();
            //查询用户当前余额
            UserMoney userNowMoney = userMoneyService.selectUserMoneyByUserId(orders.getUserId());
            //插入余额
            userMoneyDetails.setBalance(userNowMoney.getSad());
            //插入操作类型为已操作用户余额
            userMoneyDetails.setManipulateType(2);
            userMoneyDetails.setUserId(orders.getUserId());
            userMoneyDetails.setTitle("[购买商品]标题："+orders.getTitle());
            userMoneyDetails.setContent("获得盛安豆："+sad);
            userMoneyDetails.setType(1);
            userMoneyDetails.setMoney(userNowMoney.getSad());
            userMoneyDetails.setCreateTime(date);
            userMoneyDetails.setBlRole(2);
            userMoneyDetails.setBlFlag(1);
            userSadDetailsService.insert(userMoneyDetails);
        }
    }

    /**
     * 订单分销处理
     */
    @Override
    public void fenXiao(SelfOrders o) {
        //1.查询订单
        BigDecimal commissionPrice = o.getCommissionPrice(); //订单的佣金
        //2.查询订单用户
        UserEntity u = userService.selectUserById(o.getUserId());
        BigDecimal sum = commissionPrice; //计算可以分配佣金
        //分销金额不能0
        if (sum.doubleValue() < 0.01){
            return;
        }
        //4.判断有无上级
        String invitation = u.getInviterCode();
        UserEntity shangJiUser = userService.queryByInvitationCode(invitation);
        if(shangJiUser!=null) {
            BigDecimal rate=shangJiUser.getShopRate();
            BigDecimal myCommission = commissionPrice.multiply(rate);
            SelfOrderRelation s = new SelfOrderRelation();
            s.setOrderId(o.getId());
            s.setStatus(1);
            s.setPayMoney(o.getPayMoney());
            s.setGoodsId(o.getGoodsId());
            s.setGoodsImg(o.getImg());
            s.setGoodsTitle(o.getTitle());
            //不同部分：佣金不同、代理佣金、团队
            s.setUserId(shangJiUser.getUserId()); //团长id
            s.setUserName(shangJiUser.getUserName()); //团长姓名
            s.setPhone(shangJiUser.getPhone()); //团长手机号
            s.setCommissionPrice(myCommission.doubleValue()); //佣金不同
            s.setCommissionMoney(commissionPrice.doubleValue()); //代理佣金
            s.setDetail("【直属购买】"+o.getTitle());
            s.setMoneyFrom(1); //直属
            s.setLowerUserId(u.getUserId());
            s.setLowerUserName(u.getUserName());
            ordersRelationService.saveBody(s);
            /*invitation = shangJiUser.getInviterCode();
            UserEntity feiUser = userService.queryByInvitationCode(invitation);
            if(feiUser!=null) {
                rate=feiUser.getShopRate();
                myCommission = commissionPrice.multiply(rate);
                SelfOrderRelation s2 = new SelfOrderRelation();
                s2.setOrderId(o.getId());
                s2.setStatus(1);
                s2.setPayMoney(o.getPayMoney());
                s2.setGoodsId(o.getGoodsId());
                s2.setGoodsImg(o.getImg());
                s2.setGoodsTitle(o.getTitle());
                s2.setUserId(feiUser.getUserId()); //团长id
                s2.setUserName(feiUser.getUserName()); //团长姓名
                s2.setPhone(feiUser.getPhone()); //团长手机号
                s2.setCommissionPrice(myCommission.doubleValue()); //佣金不同
                s2.setCommissionMoney(commissionPrice.doubleValue()); //代理佣金
                s2.setDetail("【非直属购买】"+o.getTitle());
                s2.setMoneyFrom(3); //非直属
                s2.setLowerUserId(u.getUserId());
                s2.setLowerUserName(u.getUserName());
                ordersRelationService.saveBody(s2);
            }*/
        }
    }


    /**
     * 检测支付
     * @param id
     * @return
     */
    @Override
    public Result checkPay(Long id) {
        SelfOrders one = jpaRepository.getOne(id);
        if (one.getStatus() == 2){
            return ResultUtil.success(one);
        }
        return ResultUtil.error(-1, "未支付");
    }

    @Override
    public SelfOrders findByOrderNum(String orderNum) {
        return jpaRepository.findByOrderNum(orderNum);
    }


    //处理虚拟商品
    @Override
    public SelfGoodsVirtual sendExpress(SelfOrders orders){
        //发送虚拟商品
        SelfGoodsVirtual v = selfGoodsVirtualService.sendGoods(orders.getGoodsId());
        if (v != null) { //有商品
            return v;
        }else { //无商品时,后台管理发送发货提醒
            SelfOrderRemind r = new SelfOrderRemind();
            r.setOrdersId(orders.getId());
            r.setCreateTime(DateUtil.createTime());
            r.setStatus(1);
            selfOrdersRemindJpaRepository.save(r);
            return null;
        }
    }

    /**
     * 发起退款
     * @param id
     * @param refund
     * @return
     */
    @Override
    public Result refund(Long id, String refund) {
        SelfOrders orders = jpaRepository.findById(id).orElse(null);
        if (orders.getIsExpress() == 2){
            return ResultUtil.error(-1, "虚拟商品不支持退款");
        }
        orders.setRefund(refund);
        orders.setOldStatus(orders.getStatus());
        orders.setStatus(6); //6退款中
        return ResultUtil.success(jpaRepository.save(orders));
    }

    /**
     * 确认退款
     * @param id
     * @return
     */
    @Override
    public Result refundMoney(Long id) {
        boolean refund = true;
        //1.获取订单
        SelfOrders orders = jpaRepository.findById(id).orElse(null);
        Integer payWay = orders.getPayWay();
        //2.零钱支付退款
        if (payWay == 6){ //支付方式（1app微信 2微信公众号 3微信小程序 4app支付宝 5H5支付宝 6零钱）
            //2.1用户信息
            //2.2用户零钱增加
            userMoneyService.updateMoney(1,orders.getUserId(),orders.getPayMoney());
            //2.3零钱增加明细
            UserMoneyDetails userMoneyDetails=new UserMoneyDetails();
            //查询用户当前余额
            UserMoney userNowMoney = userMoneyService.selectUserMoneyByUserId(orders.getUserId());
            //插入余额
            userMoneyDetails.setBalance(userNowMoney.getMoney());
            //插入操作类型为已操作用户余额
            userMoneyDetails.setManipulateType(2);
            userMoneyDetails.setUserId(orders.getUserId());
            userMoneyDetails.setTitle("[商品退款]标题："+orders.getTitle());
            userMoneyDetails.setContent("自营商城退款，订单号："+orders.getOrderNum());
            userMoneyDetails.setType(1);
            userMoneyDetails.setMoney(BigDecimal.valueOf(orders.getPayMoney()));
            userMoneyDetails.setCreateTime(DateUtil.createTime());
            userMoneyDetailsService.save(userMoneyDetails);

        }else if (payWay == 4 || payWay == 5){
            //3.支付宝退款
            refund = selfAliPayService.refund(id);
        }else if (payWay == 1 || payWay == 2 || payWay == 3){
            //4.微信退款
            refund = selfWXService.refund(id);
        }
        //5.删除分销订单
        List<SelfOrderRelation> list = ordersRelationService.findByOrdersId(id); //订单关联的分销列表
        for (SelfOrderRelation s : list) {
            ordersRelationService.delete(s.getId());
        }
        //6.处理订单已退款
        if (refund){
            orders.setStatus(7); //已退款
            jpaRepository.save(orders);
            return ResultUtil.success();
        }else {
            return ResultUtil.error(-1,"退款失败");
        }
    }

    /**
     * 拒绝退款
     * @param ordersId
     * @param refusedRefund
     * @return
     */
    @Override
    public Result refusedRefund(Long ordersId, String refusedRefund) {
        SelfOrders order = jpaRepository.getOne(ordersId);
        order.setStatus(order.getOldStatus());
        order.setRefusedRefund(refusedRefund);
        order = jpaRepository.save(order);
        return ResultUtil.success(order);
    }

    @Override
    public Result pendingOrder() {
        return ResultUtil.success(ordersRepository.pendingOrder());
    }

    @Override
    public Result remind(Long ordersId) {
        SelfOrderRemind remind = selfOrdersRemindJpaRepository.findByOrdersId(ordersId);
        if (remind != null){
            if (remind.getStatus() == 1){
                return ResultUtil.error(0, "已经提醒发货");
            }else {
                remind.setStatus(1);
                selfOrdersRemindJpaRepository.save(remind);
            }
        }else{
            SelfOrderRemind r = new SelfOrderRemind();
            r.setOrdersId(ordersId);
            r.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            r.setStatus(1);
            selfOrdersRemindJpaRepository.save(r);
        }
        return ResultUtil.success();
    }

    @Override
    public Result remindOrder() {
        // 构造自定义查询条件
        Specification<SelfOrderRemind> queryCondition = new Specification<SelfOrderRemind>() {
            @Override
            public Predicate toPredicate(Root<SelfOrderRemind> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicateList = new ArrayList<>();
                predicateList.add(criteriaBuilder.equal(root.get("status"), 1));
                return criteriaBuilder.and(predicateList.toArray(new Predicate[predicateList.size()]));
            }
        };
        List<SelfOrderRemind> all = selfOrdersRemindJpaRepository.findAll(queryCondition);
        for (SelfOrderRemind r : all) {
            r.setStatus(2);
            selfOrdersRemindJpaRepository.save(r);
        }
        return ResultUtil.success(all.size());
    }

    @Override
    public List<SelfOrders> findByPayNum(String payNum) {
        return jpaRepository.findByPayNum(payNum);
    }

    /**
     * 订单数量统计
     * @param userId
     * @return
     */
    @Override
    public Result count(Long userId) {
        Map<String, Object> map = new HashMap<>();
        int count1 = 0;
        int count2 = 0;
        int count3 = 0;
        int count4 = 0;
        int count5 = 0;
        int count6 = 0;
        int count7 = 0;
        int count8 = 0;
        //订单状态（1待付款 2已付款 3已发货 4已收货 5已取消 6退款中 7已退款 8拒绝退款 9拼团中 10已评价）
        List<SelfOrders> list = ordersRepository.findByUserId(userId);
        for (SelfOrders o : list) {
            switch (o.getStatus()){
                case 1: count1++; break;
                case 2: count2++; break;
                case 3: count3++; break;
                case 4: count4++; break;
                case 5: count5++; break;
                case 6: count6++; break;
                case 7: count7++; break;
                case 8: count8++; break;
            }
        }
        map.put("count1", count1); //待付款
        map.put("count2", count2); //代发货
        map.put("count3", count3); //待收货
        map.put("count4", count4); //待评价
        map.put("count5", count5); //已取消
        map.put("count6", count6); //6退款中
        map.put("count7", count7); //7已退款
        map.put("count8", count8); //8拒绝退款
        return ResultUtil.success(map);
    }

    @Override
    public Result findExpress(String expressNumber) {
        String appCode = commonRepository.findOne(103).getValue();
        String host = "https://wuliu.market.alicloudapi.com";// 【1】请求地址 支持http 和 https 及 WEBSOCKET
        String path = "/kdi";  // 【2】后缀
        String appcode = appCode; // 【3】开通服务后 买家中心-查看AppCode
        String no = expressNumber;// 【4】请求参数，详见文档描述
        String type = ""; //  【4】请求参数，不知道可不填 95%能自动识别
        String urlSend = host + path + "?no=" + no +"&type="+type;  // 【5】拼接请求链接
        try {
            URL url = new URL(urlSend);
            HttpURLConnection httpURLCon = (HttpURLConnection) url.openConnection();
            httpURLCon .setRequestProperty("Authorization", "APPCODE " + appcode);// 格式Authorization:APPCODE (中间是英文空格)
            int httpCode = httpURLCon.getResponseCode();
            if (httpCode == 200) {
                String json = read(httpURLCon.getInputStream());
                return ResultUtil.success(JSON.parseObject(json));
            } else {
                Map<String, List<String>> map = httpURLCon.getHeaderFields();
                String error = map.get("X-Ca-Error-Message").get(0);
                if (httpCode == 400 && error.equals("Invalid AppCode `not exists`")) {
                    System.out.println("AppCode错误 ");
                } else if (httpCode == 400 && error.equals("Invalid Url")) {
                    System.out.println("请求的 Method、Path 或者环境错误");
                } else if (httpCode == 400 && error.equals("Invalid Param Location")) {
                    System.out.println("参数错误");
                } else if (httpCode == 403 && error.equals("Unauthorized")) {
                    System.out.println("服务未被授权（或URL和Path不正确）");
                } else if (httpCode == 403 && error.equals("Quota Exhausted")) {
                    System.out.println("套餐包次数用完 ");
                } else {
                    System.out.println("参数名错误 或 其他错误");
                    System.out.println(error);
                }
            }
        } catch (MalformedURLException e) {
            System.out.println("URL格式错误");
        } catch (UnknownHostException e) {
            System.out.println("URL地址错误");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultUtil.error(-1, "查询失败");
    }

    @Override
    public Result changeSadPay(String ordersId) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date=sdf.format(new Date());
        String[] ids = ordersId.split(",");
        for (String s : ids) {
            //1.获取订单、用户信息
            SelfOrders orders = jpaRepository.findById(Long.valueOf(s)).orElse(null);
            if(orders==null){
                continue;
            }
            double payMoney = orders.getPayMoney();
            UserMoney userMoney = userMoneyService.selectUserMoneyByUserId(orders.getUserId());
            double money = userMoney.getSad().doubleValue();
            if (payMoney > money){
                return ResultUtil.error(500,"盛安豆余额不足！");
            }
            userMoneyService.updateSad(2,orders.getUserId(),payMoney);
            UserSadDetails userMoneyDetails=new UserSadDetails();
            //查询用户当前余额
            UserMoney userNowMoney = userMoneyService.selectUserMoneyByUserId(orders.getUserId());
            //插入余额
            userMoneyDetails.setBalance(userNowMoney.getSad());
            //插入操作类型为已操作用户余额
            userMoneyDetails.setManipulateType(2);
            userMoneyDetails.setUserId(orders.getUserId());
            userMoneyDetails.setTitle("[购买商品]标题："+orders.getTitle());
            userMoneyDetails.setContent("盛安豆支付："+payMoney);
            userMoneyDetails.setType(2);
            userMoneyDetails.setMoney(userNowMoney.getSad());
            userMoneyDetails.setCreateTime(date);
            userMoneyDetails.setBlRole(2);
            userMoneyDetails.setBlFlag(1);
            userSadDetailsService.insert(userMoneyDetails);

            //4.支付成功处理订单
            orders.setPayWay(6); //支付方式（1app微信 2微信公众号 3微信小程序 4app支付宝 5H5支付宝 6零钱）
            orders.setPayTime(DateUtil.createTime()); //设置支付时间
            orders.setStatus(2); //订单状态（1待付款 2已付款 3已发货 4已收货 5已取消 6退款中 7已退款 8拒绝退款 9拼团中）
            //虚拟商品处理
            if (orders.getOrderType() == 1) { //普通订单
                if (orders.getIsExpress() == 2){ //是否需要发货(1需要发货 2无需发货)
                    //虚拟商品发货，发货成功为确认收货，否则不做变化
                    SelfGoodsVirtual v = this.sendExpress(orders);
                    if (v != null){
                        orders.setVirtualId(v.getId()); //虚拟商品id
                        orders.setExpressTime(DateUtil.createTime()); //发货时间
                        orders.setStatus(4); //确认收货
                    }
                }else if (orders.getIsExpress() == 3){ //核销订单
                    orders.setStatus(3); //待收货、待使用
                }
            }
            jpaRepository.save(orders);
            //执行物料包添加操作
            materialArtificerService.changePay(orders.getGoodsId(),orders.getUserId(),orders.getNumber());
            //公众号消息通知
            //userService.orderPay(orders.getUserId(), orders.getOrderNum(),orders.getPayMoney().toString(),orders.getCreateAt());
        }
        return ResultUtil.success();
    }

    /*
     * 读取返回结果
     */
    private static String read(InputStream is) throws IOException {
        StringBuffer sb = new StringBuffer();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line = null;
        while ((line = br.readLine()) != null) {
            line = new String(line.getBytes(), "utf-8");
            sb.append(line);
        }
        br.close();
        return sb.toString();
    }
}
