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

import com.sqx.modules.app.entity.UserMoney;
import com.sqx.modules.app.entity.UserMoneyDetails;
import com.sqx.modules.app.entity.UserSadDetails;
import com.sqx.modules.app.service.UserMoneyDetailsService;
import com.sqx.modules.app.service.UserMoneyService;
import com.sqx.modules.app.service.UserService;
import com.sqx.modules.shopping.dao.OrdersJpaRepository;
import com.sqx.modules.shopping.dao.OrdersRelationJpaRepository;
import com.sqx.modules.shopping.dao.OrdersRelationRepository;
import com.sqx.modules.shopping.entity.SelfOrderRelation;
import com.sqx.modules.shopping.entity.SelfOrders;
import com.sqx.modules.shopping.service.OrdersRelationService;
import com.sqx.modules.shopping.utils.AmountCalUtil;
import com.sqx.modules.shopping.utils.Result;
import com.sqx.modules.shopping.utils.ResultUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
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.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class OrdersRelationServiceImpl implements OrdersRelationService {
    @Autowired
    private OrdersRelationJpaRepository jpaRepository;
    @Autowired
    private OrdersRelationRepository repository;
    @Autowired
    private UserService userService;
    @Autowired
    private UserMoneyDetailsService userMoneyDetailsService;
    @Autowired
    private OrdersJpaRepository ordersJpaRepository;
    @Autowired
    private UserMoneyService userMoneyService;

    @Override
    public Result findAll(Integer page, Integer size, Long userId, String phone, Integer status, Integer moneyFrom) {
        //根据时间排序
        Pageable pageable = PageRequest.of(page, size, Sort.by(new Sort.Order(Sort.Direction.DESC, "createAt")));
        // 构造自定义查询条件
        Specification<SelfOrderRelation> queryCondition = new Specification<SelfOrderRelation>() {
            @Override
            public Predicate toPredicate(Root<SelfOrderRelation> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicateList = new ArrayList<>();
                if (userId != null) {
                    predicateList.add(criteriaBuilder.equal(root.get("userId"), userId));
                }
                if (StringUtils.isNotEmpty(phone)) {
                    predicateList.add(criteriaBuilder.equal(root.get("phone"), phone));
                }
                if (status != 0) {
                    predicateList.add(criteriaBuilder.equal(root.get("status"), status));
                }
                if (moneyFrom != 0) {
                    predicateList.add(criteriaBuilder.equal(root.get("moneyFrom"), moneyFrom));
                }
                return criteriaBuilder.and(predicateList.toArray(new Predicate[predicateList.size()]));
            }
        };
        return ResultUtil.success(jpaRepository.findAll(queryCondition, pageable));
    }

    /**
     * 保存订单
     * @param entity
     * @return
     */
    @Override
    public Result saveBody(SelfOrderRelation entity) {
        entity.setCreateAt(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); //创建时间
        SelfOrderRelation save = jpaRepository.save(entity);
        //虚拟商品分销立即到账
        SelfOrders o = ordersJpaRepository.findById(save.getOrderId()).orElse(null);
        if (o.getIsExpress() == 2){
            this.addMoney(save);
        }
        return ResultUtil.success(save);
    }

    @Override
    public Result updateBody(SelfOrderRelation entity) {
        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();
    }

    @Override
    public List<SelfOrderRelation> findByOrdersId(Long ordersId) {
        // 构造自定义查询条件
        Specification<SelfOrderRelation> queryCondition = new Specification<SelfOrderRelation>() {
            @Override
            public Predicate toPredicate(Root<SelfOrderRelation> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicateList = new ArrayList<>();
                if (ordersId != null) {
                    predicateList.add(criteriaBuilder.equal(root.get("orderId"), ordersId));
                }
                return criteriaBuilder.and(predicateList.toArray(new Predicate[predicateList.size()]));
            }
        };
        return jpaRepository.findAll(queryCondition);
    }

    @Override
    public List<SelfOrderRelation> findAllByStatus() {
        return repository.findAllByStatus();
    }

    /**
     * 佣金零钱到账
     * @param s
     */
    @Override
    public void addMoney(SelfOrderRelation s) {
        //1.用户零钱增加
        userMoneyService.updateMoney(1,s.getUserId(),s.getCommissionPrice());
        //2.用户零钱明细增加
        UserMoneyDetails userMoneyDetails=new UserMoneyDetails();
        //查询用户当前余额
        UserMoney userNowMoney = userMoneyService.selectUserMoneyByUserId(s.getUserId());
        //插入余额
        userMoneyDetails.setBalance(userNowMoney.getMoney());
        //插入操作类型为已操作用户余额
        userMoneyDetails.setManipulateType(2);
        userMoneyDetails.setMoney(BigDecimal.valueOf(s.getCommissionPrice()));
        userMoneyDetails.setUserId(s.getUserId());
        if(s.getMoneyFrom().equals(1)){
            userMoneyDetails.setTitle("【直属佣金】商品分佣");
        }else if(s.getMoneyFrom().equals(2)){
            userMoneyDetails.setTitle("【商城佣金】商品分佣");
        }else{
            userMoneyDetails.setTitle("【非直属佣金】商品分佣");
        }
        userMoneyDetails.setContent("佣金到账金额："+s.getCommissionPrice());
        userMoneyDetails.setType(1);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        userMoneyDetails.setCreateTime(simpleDateFormat.format(new Date()));
        userMoneyDetailsService.insert(userMoneyDetails);
        //3.修改分销记录为已到账
        s.setStatus(2); //已到账
        this.updateBody(s);
        //4.订单设置未不可退款状态
        Long orderId = s.getOrderId();
        SelfOrders order = ordersJpaRepository.getOne(orderId);
        order.setIsRefund(2); //不可退款
        ordersJpaRepository.save(order);

    }

    /**
     * 我的佣金统计：已到账佣金、未到账佣金、本月佣金
     * @param userId
     * @return
     */
    @Override
    public Result statistaical(Long userId) {
        String month = new SimpleDateFormat("yyyy-MM").format(new Date());
        String sum1 = repository.sumByUserIdStatus1(userId, month);
        String sum2 = repository.sumByUserIdStatus2(userId, month);
        Map<String, Double> map = new HashMap<>();
        map.put("sum1", AmountCalUtil.moneySum(sum1)); //本月未到账
        map.put("sum2", AmountCalUtil.moneySum(sum2)); //本月已到账
        return ResultUtil.success(map);
    }

    /**
     * 团队佣金统计
     * @param userId
     * @return
     */
    @Override
    public Result tuanStatistaical(Long userId) {
        String month = new SimpleDateFormat("yyyy-MM").format(new Date());
        String sum1 = repository.sumByUserIdStatus1Tuan(userId, month);
        String sum2 = repository.sumByUserIdStatus2Tuan(userId, month);
        Map<String, Double> map = new HashMap<>();
        map.put("sum1", AmountCalUtil.moneySum(sum1)); //本月未到账
        map.put("sum2", AmountCalUtil.moneySum(sum2)); //本月已到账
        return ResultUtil.success(map);
    }

    @Override
    public Result tuanSum(Long userId) {
        return ResultUtil.success(AmountCalUtil.moneySum(repository.tuanSum(userId)));
    }



}
