package com.iamberry.wechat.service.activity;

import com.iamberry.app.tool.log.RatFWLogger;
import com.iamberry.wechat.core.entity.activity.Activity;
import com.iamberry.wechat.core.entity.activity.ActivityHelp;
import com.iamberry.wechat.core.entity.coupon.CouponItem;
import com.iamberry.wechat.core.entity.member.Member;
import com.iamberry.wechat.face.activity.ActivityService;
import com.iamberry.wechat.face.coupon.CouponItemService;
import com.iamberry.wechat.service.mapper.ActivityHelpMapper;
import com.iamberry.wechat.service.mapper.ActivityMapper;
import com.iamberry.wechat.service.mapper.CouponItemMapper;
import com.iamberry.wechat.service.mapper.MemberMapper;
import com.iamberry.wechat.tools.ResultInfo;
import com.iamberry.wechat.tools.SendMessageUtil;
import com.iamberry.wechat.tools.StrUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 *  活动助力参与接口
 * @author w
 * @Date 2018-06-07
 */
@Service
public class ActivityServiceImpl  implements ActivityService {
    @Autowired
    private ActivityMapper activityMapper;
    @Autowired
    private ActivityHelpMapper activityHelpMapper;
    @Autowired
    private CouponItemMapper couponItemMapper;
    @Autowired
    private SendMessageUtil sendMessageUtil;
    @Autowired
    private RatFWLogger logger;
    @Autowired
    private MemberMapper memberMapper;

    /**
     * 获取集合
     * @param  activity
     * @return List
     */
    @Override
    public List<Activity> getActivityList(Activity  activity){
        return  activityMapper.getActivityList(activity);
    }
    /**
     * 查询单条数据
     * @param  id
     * @return  activity
     */
    @Override
    public  Activity  getActivityById(Integer  id){
        return  activityMapper.getActivityById(id);
    }

    @Override
    public Activity getActivityCouponId(String couponId) {
        return  activityMapper.getActivityCouponId(couponId);
    }

    /**
     * 增加数据
     * @param  activity
     * @return Integer
     */
    @Override
    public  Integer  save(Activity  activity){
        return  activityMapper.save(activity);
    }

    /**
     * 修改数据
     * @param  activity
     * @return Integer
     */
    @Override
    @Transactional
    public  Integer  update(Activity  activity){
        CouponItem couponItem = new CouponItem();
        couponItem.setCouponId(20000);
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.YEAR,1);
        couponItem.setCouponUseEndDate(calendar.getTime());//领取后一年有效
        couponItem.setCouponReceiveDate(new Date());
        couponItem.setCouponItemUseropenid(activity.getUserOpenId());
        couponItem.setCouponUseStatus(1);
        couponItem.setCouponIsDonation(2);
        couponItem.setCouponItemRemark("新人优惠券");

        String uuidStr = StrUtils.getUUID();
        couponItem.setCouponItemId(uuidStr);
        Integer flag = couponItemMapper.insertCouponItem(couponItem);
        if(flag < 1){
            throw new RuntimeException("添加优惠券失败");
        }

        Activity newActivity = new Activity();
        newActivity.setActivityId(activity.getActivityId());
        newActivity.setActivityStatus(3);   //1：助力中 2：助力成功 3：已领取优惠券 4：取消
        newActivity.setActivityCoupon(uuidStr);
        flag = activityMapper.update(newActivity);
        if(flag < 1){
            throw new RuntimeException("修改状态失败");
        }
        return  flag;
    }

    /**
     * 好友助力
     * @param openId
     * @param activityOpenId  助力id  扫码人
     * @return  -1 自己扫的二维码
     *            0  失败
     *           -3  好友重复扫描
     */
    @Override
    @Transactional
    public  Integer  addActivityHelp(String openId,String activityOpenId){
        if(openId.equals(activityOpenId)){  //自己扫自己的二维码
            return -1;
        }
        boolean isHelp = false; //没有成功
        boolean isSendMsg = true;   //是否推送信息
        Member userMember = memberMapper.getMemberByUserOpenId(openId);
        Member activityMember = memberMapper.getMemberByUserOpenId(activityOpenId);
        if(userMember == null || activityMember == null){
            return -4;
        }
        Activity activity = new Activity();
        activity.setUserOpenId(openId);
        List<Activity> activityList = activityMapper.getActivityList(activity);
        if(activityList == null || activityList.size() < 1){
            return 0;
        }
        activity = activityList.get(0);

        ActivityHelp ahp = new ActivityHelp();
        ahp.setUserOpenId(activityOpenId);
        ahp.setActivityId(activity.getActivityId());
        List<ActivityHelp> activityHelpList = activityHelpMapper.getActivityHelpList(ahp);
       if(activityHelpList != null && activityHelpList.size()>0){
           return -3;
       }

        Activity ac = new Activity();
        ac.setActivityId(activity.getActivityId());
        //已有多少人助力
        Integer  activityAlreadyHelp = activity.getActivityAlreadyHelp() + 1;
        if(activityAlreadyHelp > activity.getActivityAllHelp()){
            isSendMsg = false;
        }
        if(activityAlreadyHelp == activity.getActivityAllHelp()){
            isHelp = true;     //已助力完成
            ac.setActivityStatus(2);
        }
        ac.setActivityAlreadyHelp(activityAlreadyHelp);
        Integer flag = activityMapper.update(ac);
        if(flag < 1){
            throw new RuntimeException("添加次数失败");
        }

        ActivityHelp activityHelp = new ActivityHelp();
        activityHelp.setActivityId(activity.getActivityId());
        activityHelp.setUserOpenId(activityOpenId);
        flag = activityHelpMapper.save(activityHelp);
        if(flag < 1){
            throw new RuntimeException("添加助力好友失败");
        }

        if(isSendMsg){
            //给用户发送消息
            String firstStr = "";
            String remStr = "";
            if(isHelp){ //助力完成
                firstStr = ResultInfo.HELP_SUCCESS.replaceAll("USER",userMember.getUserNickname());
                remStr = ResultInfo.HELP_REM_1;
            }else{
                firstStr = ResultInfo.HELP_FRIENDS.replaceAll("USER",activityMember.getUserNickname());
                remStr = ResultInfo.HELP_REM_2;
            }
            String numStr = activityAlreadyHelp + "人";
            try {
                sendMessageUtil.helpingSuccess(
                        firstStr,
                        ResultInfo.HELP_NAME,
                        numStr,
                        remStr,
                        openId,
                        ResultInfo.help_url
                );
            } catch (Exception e) {
                logger.info("============助力成功信息发送失败============");
                e.printStackTrace();
            }
        }
        return  flag;
    }

}