package com.iamberry.wechat.service.ism;

import com.github.pagehelper.PageHelper;
import com.iamberry.wechat.core.entity.admin.ShopSystemRule;
import com.iamberry.wechat.core.entity.ism.IntegralConfig;
import com.iamberry.wechat.core.entity.ism.IntegralLog;
import com.iamberry.wechat.core.entity.member.Member;
import com.iamberry.wechat.core.entity.order.Order;
import com.iamberry.wechat.core.entity.page.PageRequest;
import com.iamberry.wechat.core.entity.page.PagedResult;
import com.iamberry.wechat.face.cart.CartService;
import com.iamberry.wechat.face.ism.IntegralLogService;
import com.iamberry.wechat.face.order.AdminOrderService;
import com.iamberry.wechat.service.PageUtil;
import com.iamberry.wechat.service.mapper.IntegralConfigMapper;
import com.iamberry.wechat.service.mapper.IntegralLogMapper;
import com.iamberry.wechat.service.mapper.MemberMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 *  积分记录表接口
 * @author Administrator
 * @Date 2019-11-10
 */
@Service
public class IntegralLogServiceImpl  implements IntegralLogService {
    Logger logger = LoggerFactory.getLogger(IntegralLogServiceImpl.class);
    @Autowired
    private IntegralLogMapper integralLogMapper;
    @Autowired
    private IntegralConfigMapper integralConfigMapper;
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private IntegralLogService integralLogService;
    @Autowired
    private AdminOrderService adminOrderService;
    @Autowired
    private CartService cartService;
    /**
     * 获取集合
     * @param  integralLog
     * @return List
     */
    @Override
    public List<IntegralLog> getIntegralLogList(IntegralLog integralLog){
        return  integralLogMapper.getIntegralLogList(integralLog);
    }

    @Override
    public List<IntegralLog> getIntegralLogListByAccoUser(IntegralLog integralLog) {
        return  integralLogMapper.getIntegralLogListByAccoUser(integralLog);
    }

    @Override
    public PagedResult<IntegralLog> listIntegralLog(PageRequest<IntegralLog> pageRequest) {
        PageHelper.startPage(pageRequest.getPageNO(), pageRequest.getPageSize(), pageRequest.isPageTotal());
        List<IntegralLog> detedctList = integralLogMapper.getIntegralLogListByAccoUser(pageRequest.getData());
        return PageUtil.getPage(detedctList);
    }

    @Override
    public List<IntegralLog> getIntegralLogListByWaitUser() {
        return  integralLogMapper.getIntegralLogListByWaitUser();
    }

    /**
     * 查询单条数据
     * @param  id
     * @return  integralLog
     */
    @Override
    public IntegralLog getIntegralLogById(Integer  id){
        return  integralLogMapper.getIntegralLogById(id);
    }
    /**
     * 增加数据
     * @param  integralLog
     * @return Integer
     */
    @Override
    public  Integer  save(IntegralLog integralLog){
        return  integralLogMapper.save(integralLog);
    }
    /**
     * 修改数据
     * @param  integralLog
     * @return Integer
     */
    @Override
    public  Integer  update(IntegralLog integralLog){
        return  integralLogMapper.update(integralLog);
    }
    /**
     * 删除数据
     * @param  id
     * @return Integer
     */
    @Override
    public  Integer  delete(Integer  id){
        return  integralLogMapper.delete(id);
    }

    /**
     * 订单结算只能获得待入账积分
     * @param orderId
     * @return
     */
    @Override
    @Transactional
    public Integer addOrderChangIntegra(String orderId,Integer integraConfigId) {
        Integer flag = 0;
        Order order = new Order();
        order.setSalesOrderid(orderId);
        order = cartService.selectOrderInfoById(order);

        Format f = new SimpleDateFormat("MM-dd");
        Member member = memberMapper.getMemberByUserOpenId(order.getSalesOpenid());
        String date1 = f.format(member.getUserBirthDate());
        String date2 = f.format(new Date());

        IntegralConfig integralConfig = null;
        if(date1.equals(date2)){
            //生日当天订单结算获取积分X*0.3
            integralConfig = integralConfigMapper.getIntegralConfigById(3);
        }else{
            //订单结算获取积分 按照传入的值计算
            integralConfig = integralConfigMapper.getIntegralConfigById(integraConfigId);
        }
        if(integralConfig == null || integralConfig.getInteConfCalculation()==null || "".equals(integralConfig.getInteConfCalculation())){
            return flag;
        }
        Double num = Double.valueOf(integralConfig.getInteConfCalculation());
        num = num*(order.getSalesYetAmount()/100);
        return integralLogService.changeIntegral(order.getSalesOpenid(),integralConfig.getInteConfId(),num.intValue(),
                3,orderId,"",integralConfig.getInteConfDesc());
    }

    /**
     * 订单结算使用积分
     * @param order
     * @return
     */
    @Override
    @Transactional
    public Integer muOrderChangIntegra(Order order) {
        IntegralConfig integralConfig = integralConfigMapper.getIntegralConfigById(4);
        Integer num = order.getSalesIntegralNum();   //setSalesIntegralNum
        return integralLogService.changeIntegral(order.getSalesOpenid(),integralConfig.getInteConfId(),num.intValue(),2,
                "",order.getSalesOrderid(),integralConfig.getInteConfDesc());
    }

    /**
     * 添加&&使用积分 - 简洁版
     * @param  openId
     * @param inteConfId 积分配置id
     * @param inteLogType  积分类型 1:添加积分2:使用积分3:待入账积分
     * @return
     */
    @Override
    @Transactional
    public Integer updateIntegral(String openId,Integer inteConfId,Integer inteLogType){
        Integer flag = 0;
        IntegralConfig integralConfig = integralConfigMapper.getIntegralConfigById(inteConfId);
        if(integralConfig == null || integralConfig.getInteConfCalculation()==null || "".equals(integralConfig.getInteConfCalculation())){
            return flag;
        }
        Integer num = Integer.valueOf(integralConfig.getInteConfCalculation());
        return integralLogService.changeIntegral(openId,inteConfId,num,inteLogType,"","",integralConfig.getInteConfDesc());
    }

    /**
     * 取消订单-减去积分
     * @param  orderId
     * @return
     */
    @Override
    @Transactional
    public Integer cancelSurplusIntegral(String orderId){
        Integer flag = 0;

        Order order = new Order();
        order.setSalesOrderid(orderId);
        order = cartService.selectOrderInfoById(order);

        if(order.getSalesStatus() != 0 ){   //取消订单
            throw  new RuntimeException("该订单未取消");
        }

        //退回使用积分
        IntegralLog usedintegralLog = new IntegralLog();
        usedintegralLog.setInteLogUseOrderId(orderId);
        List<IntegralLog> usedintegralLogList = integralLogService.getIntegralLogList(usedintegralLog);
        if(usedintegralLogList!=null && usedintegralLogList.size() > 0){
            usedintegralLog = usedintegralLogList.get(0);
            IntegralLog newusedintegralLog = new IntegralLog();
            newusedintegralLog.setInteLogId(usedintegralLog.getInteLogId());
            newusedintegralLog.setInteLogStatus(2);
            newusedintegralLog.setInteLogDesc(usedintegralLog.getInteLogDesc()+"===订单取消");
            flag = integralLogService.update(newusedintegralLog);
            if(flag < 1){
                throw  new RuntimeException("取消订单退回积分-使用积分取消");
            }

            Member member = memberMapper.getMemberByUserOpenId(usedintegralLog.getUserOpenId());
            Member newMember = new Member();
            newMember.setUserOpenid(member.getUserOpenid());
            newMember.setUserSurplusIntegral(member.getUserSurplusIntegral() + usedintegralLog.getInteLogChangeNum());
            newMember.setUserUseIntegral(member.getUserUseIntegral() - usedintegralLog.getInteLogChangeNum());
            flag = memberMapper.nowUpdateUserByOpenId(newMember);
            if(flag < 1){
                throw  new RuntimeException("取消订单待入账更改失败-变更用户积分失败");
            }
            return flag;
        }
        return 1;
    }

    /**
     * 积分操作 - 核心入口
     * @param  openId 必填 *
     * @param inteConfId 必填 * 积分配置id
     * @param inteLogType  必填 * 积分类型 1:添加积分2:使用积分3:待入账积分
     * @param waitingOrderId 订单支付获得积分，待入账需要订单编号
     * @param useOrderId 订单支付使用积分/积分商城下单使用积分都需要订单编号
     * @param remake 备注
     * @return
     */
    @Override
    @Transactional
    public Integer changeIntegral(String openId, Integer inteConfId,Integer integralNum, Integer inteLogType,
                                  String waitingOrderId,String useOrderId,String remake) {
        Integer flag = 0;

        IntegralConfig integralConfig = integralConfigMapper.getIntegralConfigById(inteConfId);

        if(integralNum <= 0){
            throw  new RuntimeException("需要添加/减少的积分为0");
        }
        Member member = memberMapper.getMemberByUserOpenId(openId);

        Member newMember = new Member();
        newMember.setUserOpenid(member.getUserOpenid());
        IntegralLog integralLog = new IntegralLog();
        integralLog.setUserOpenId(openId);
        integralLog.setInteConfId(inteConfId);
        integralLog.setInteLogType(inteLogType);
        integralLog.setInteLogStatus(1);
        if(inteLogType == 1 || inteLogType == 2){
            integralLog.setInteLogChangeNum(integralNum);
            integralLog.setInteLogBeforeNum(member.getUserIntegral());

            if(inteLogType == 1){
                integralLog.setInteLogAfterNum(member.getUserIntegral()+integralNum);
                integralLog.setInteLogDesc(remake+"--积分新增："+integralNum);
                newMember.setUserIntegral(member.getUserIntegral()+integralNum);
                newMember.setUserSurplusIntegral(member.getUserSurplusIntegral()+integralNum);
            }else{
                Integer num = member.getUserIntegral()-integralNum;
                if(num < 0){
                    throw  new RuntimeException("积分不足");
                }
                integralLog.setInteLogAfterNum(num);
                integralLog.setInteLogDesc(remake+"--积分使用："+integralNum);
                if(useOrderId != null && !"".equals(useOrderId)){
                    integralLog.setInteLogUseOrderId(useOrderId);
                }
                newMember.setUserSurplusIntegral(member.getUserSurplusIntegral()-integralNum);
                newMember.setUserUseIntegral(member.getUserUseIntegral()+integralNum);
            }
        }else if(inteLogType == 3){
            if(member.getUserPendIntegral() == null){
                member.setUserPendIntegral(0);
            }
            integralLog.setInteLogChangeNum(integralNum);
            integralLog.setInteLogBeforeNum(member.getUserPendIntegral());
            integralLog.setInteLogAfterNum(member.getUserPendIntegral()+integralNum);

            ShopSystemRule shopSystemRule = adminOrderService.getReluByRid(102);
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DATE, shopSystemRule.getRuleNum().intValue());  //待入账
            integralLog.setInteLogWaitingDate(calendar.getTime()); //inteLogWaitingDate //待入账时间

            if(waitingOrderId == null || "".equals(waitingOrderId)){
                throw  new RuntimeException("待入账没有订单编号");
            }
            integralLog.setInteLogWaitingOrderId(waitingOrderId);
            integralLog.setInteLogDesc(remake+"--待入账："+integralNum+"，关联订单ID："+waitingOrderId);
            newMember.setUserPendIntegral(member.getUserPendIntegral()+integralNum);
        }else{
            throw  new RuntimeException("inteLogType积分类型不正确");
        }

        logger.info("积分调整-类型："+integralConfig.getInteConfName()+";数量："+integralLog.getInteLogChangeNum()+";userOpenId:"+integralLog.getUserOpenId());

        integralLog.setInteLogName(integralConfig.getInteConfName());
        flag = integralLogMapper.save(integralLog);
        if(flag < 1){
            throw  new RuntimeException("添加积分记录失败");
        }

        flag = memberMapper.nowUpdateUserByOpenId(newMember);
        if(flag < 1){
            throw  new RuntimeException("变更用户积分失败");
        }
        return flag;
    }

    /**
     * 待入账转入-积分从待入账转为已入账
     * @param  integralLog
     * @return
     */
    @Override
    @Transactional
    public Integer waitUser(IntegralLog integralLog) {
        //0：校验订单状态
        //1.给用户减去待入账积分
        //2.添加一条新纪录，添加剩余积分和总积分
        //3.将该积分记录置位删除标志
        Integer flag = 0;

        Order order = new Order();
        order.setSalesOrderid(integralLog.getInteLogWaitingOrderId());
        order = cartService.selectOrderInfoById(order);
        if(order.getSalesStatus() == 0 ){
            //状态  0：取消订单
            //cancelSurplusIntegral(order.getSalesOrderid());  理论不存在
        }else if(order.getSalesStatus() == 1 || order.getSalesStatus() == 2){
            //状态 1：待支付 2：已支付、待发货
            throw  new RuntimeException("订单异常-订单状态未支付，或代发货-待入账转为已入账任务");
        }else if(order.getSalesStatus() == 4 || order.getSalesStatus() == 8){
             //8：订单退货，订单关闭  4：已退款  -- 退款退货，直接结束这个待入账积分
            //将该积分记录置位删除标志-并且减去待入账 - 订单退货/退款
            IntegralLog newIntegralLog = new IntegralLog();
            newIntegralLog.setInteLogId(integralLog.getInteLogId());
            newIntegralLog.setInteLogStatus(2);
            newIntegralLog.setInteLogDesc(integralLog.getInteLogDesc()+"===订单退货/退款");
            flag = integralLogService.update(newIntegralLog);
            if(flag < 1){
                throw  new RuntimeException("删除以前的待入账积分失败-待入账转为已入账任务");
            }
            Member member = memberMapper.getMemberByUserOpenId(integralLog.getUserOpenId());
            if((member.getUserPendIntegral()-integralLog.getInteLogChangeNum())<0){
                throw  new RuntimeException("删除以前的待入账积分不足-请核查用户信息-待入账转为已入账任务");
            }
            Member newMember = new Member();
            newMember.setUserOpenid(member.getUserOpenid());
            newMember.setUserPendIntegral(member.getUserPendIntegral()-integralLog.getInteLogChangeNum());
            flag = memberMapper.nowUpdateUserByOpenId(newMember);
            if(flag < 1){
                throw  new RuntimeException("删除以前的待入账积分失败-变更用户积分失败");
            }
        }else if(order.getSalesStatus() == 3 || order.getSalesStatus() == 6 || order.getSalesStatus() == 7
                || order.getSalesStatus() == 9  || order.getSalesStatus() == 11){
            //3：退款申请中   6：申请退货中  7：退货中  9：换货中  11：申请换货中
            throw  new RuntimeException("订单处于退款/退货/换货处理中，请快速处理-待入账转为已入账任务");
        }else if(order.getSalesStatus() == 5 || order.getSalesStatus() == 12 || order.getSalesStatus() == 10){
            //   5：已发货   12：订单完成  10：换货完成

            //1.给用户减去待入账积分
            Member member = memberMapper.getMemberByUserOpenId(integralLog.getUserOpenId());
            if((member.getUserPendIntegral()-integralLog.getInteLogChangeNum())<0){
                throw  new RuntimeException("待入账积分不足-请核查用户信息-待入账转为已入账任务");
            }
            Member newMember = new Member();
            newMember.setUserOpenid(member.getUserOpenid());
            newMember.setUserPendIntegral(member.getUserPendIntegral()-integralLog.getInteLogChangeNum());
            flag = memberMapper.nowUpdateUserByOpenId(newMember);
            if(flag < 1){
                throw  new RuntimeException("变更用户待入账积分失败-待入账转为已入账任务");
            }

            //2.添加一条新纪录，添加剩余积分和总积分
            String remake = integralLog.getInteLogDesc()+"原待入账LogId为："+ integralLog.getInteLogId();
            flag = integralLogService.changeIntegral(integralLog.getUserOpenId(),6,integralLog.getInteLogChangeNum(),1,
                    "","",remake);
            if(flag < 1){
                throw  new RuntimeException("添加入账积分记录失败-待入账转为已入账任务");
            }

            //3.将该积分记录置位删除标志
            IntegralLog newIntegralLog = new IntegralLog();
            newIntegralLog.setInteLogId(integralLog.getInteLogId());
            newIntegralLog.setInteLogStatus(2);
            newIntegralLog.setInteLogDesc(integralLog.getInteLogDesc()+"===已将待入账转为已入账，故删除");
            flag = integralLogService.update(newIntegralLog);
            if(flag < 1){
                throw  new RuntimeException("删除以前的待入账-待入账转为已入账任务");
            }

        }else{
            throw  new RuntimeException("订单异常状态异常-请核查订单详情-待入账转为已入账任务");
        }
        return flag;
    }

}