package com.xxfc.platform.activity.biz;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.util.process.ResultCode;
import com.xxfc.platform.activity.entity.Coupon;
import com.xxfc.platform.activity.vo.ActivityRuleVo;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xxfc.platform.activity.entity.ActivityRule;
import com.xxfc.platform.activity.mapper.ActivityRuleMapper;
import com.github.wxiaoqi.security.common.biz.BaseBiz;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;

/**
 * 通用活动规则表
 *
 * @author zjw
 * @email 18178966185@163.com
 * @date 2019-07-16 14:04:22
 */
@Service
public class ActivityRuleBiz extends BaseBiz<ActivityRuleMapper,ActivityRule> {


    @Autowired
    CouponBiz couponBiz;


     //获取最新的生效的活动
    public  ActivityRule getActity(){
        Example example=new Example(ActivityRule.class);
        example.createCriteria().andEqualTo("status",1).andEqualTo("isDel",0);
        example.setOrderByClause("id desc");
        List<ActivityRule> list=mapper.selectByExample(example);
        if(list.size()>0){
          return  list.get(0);
        }
        return  null;
    }

    //获取最新活动的H5页面
    public ObjectRestResponse getActivityH5(){
        ActivityRule activityRule=getActity();
        if (activityRule==null){
            return  ObjectRestResponse.createFailedResult(ResultCode.NULL_CODE,"无有效的活动");
        }
        ActivityRuleVo ruleVo=new ActivityRuleVo();
        try {
            BeanUtils.copyProperties(ruleVo, activityRule);
            String value=activityRule.getValue();
            JSONObject json=JSONObject.parseObject(value);
            if(json!=null){
                Integer type=json.getInteger("type");
                if(type==1){
                    JSONArray array=json.getJSONArray("value");
                    List<Coupon> coupons=new ArrayList<>();
                    if(array.size()>0){
                        for(int i=0;i<array.size();i++){
                            Integer id=array.getJSONObject(i).getInteger("id");
                            coupons.add(couponBiz.selectById(id));
                        }
                    }
                    ruleVo.setCoupons(coupons);
                }
            }
            return  ObjectRestResponse.succ(ruleVo);
        }catch (Exception e){
            e.printStackTrace();
            return ObjectRestResponse.createDefaultFail();
        }



    }
}