/*
 * Copyright (C), 2002-2015, 江苏三六五网络股份有限公司
 * FileName: ExchangeUserLoginInterfaceImpl.java
 * Author:   Administrator
 * Date:     2015年5月5日 下午2:57:41
 * Description: //模块目的、功能描述      
 * History: //修改记录
 * <author>      <time>      <version>    <desc>
 * 修改人姓名             修改时间            版本号                  描述
 */
package com.house365.ws.interfaces.rest;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.house365.ws.service.interfaces.ICmPromotionProductService;
import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.house365.beans.entity.CmCreditGoodsEntity;
import com.house365.beans.entity.CmSeckillBookedEntity;
import com.house365.beans.entity.CmSeckillRemindEntity;
import com.house365.beans.system.QueryParams;
import com.house365.rest.context.Parameter;
import com.house365.rest.exception.IllegalServiceParameterException;
import com.house365.rest.exception.ServiceRunException;
import com.house365.ws.dao.interfaces.ICmCreditGoodsDao;
import com.house365.ws.dao.interfaces.ICmSeckillBookedDao;
import com.house365.ws.dao.interfaces.ICmSeckillRemindDao;
import com.house365.ws.system.ReturnAppResult;

/**
 * 〈一句话功能简述〉<br>
 * 〈功能详细描述〉
 *
 * @author Administrator
 * @version [版本号, 2015年5月5日]
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
@Component("secKillRemindInterface")
public class SecKillRemindInterfaceImpl implements ISecKillRemindInterface {
    static int killCount;
    
/*    static int iiCount=0;
    
    public static synchronized int increaseCount(){
        return iiCount++;
    }*/

    /**
     * 日志记录器
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(SecKillRemindInterfaceImpl.class);


    /**
     * 接口参数手机号码
     */
    private static final String USERPHONE = "userPhone";

    /**
     * 商品Id
     */
    private static final String GOODSID = "goodsId";

    /**
     * 用户Id
     */
    private static final String USERID = "userId";

    /**
     * 提醒类型remindType
     */
    private static final String REMINDTYPE = "remindType";


    /**
     * 周期内最多订单数, 默认2次
     */
    @Value("#{system.orderLimitCount}")
    private Integer ORDER_LIMIT_COUNT = 0;

    /**
     * 定义常量
     */
    public static final String[] CreditGoodsDetails = {};

    @Autowired
    private ICmSeckillBookedDao<CmSeckillBookedEntity> secKillBoockedDao;

    @Autowired
    private ICmSeckillRemindDao<CmSeckillRemindEntity> secKillRemindDao;

    @Autowired
    private ICmCreditGoodsDao<CmCreditGoodsEntity> cmCreditGoodsDao;

    @Autowired
    ICmPromotionProductService promotionProductService;

    @Override
    public Object exectue(Parameter parameter) throws ServiceRunException {
        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        Map<String, Object> response = new HashMap<String, Object>();
        // 业务校验统一入口
        try {
            checkInterfaceParameter(map);
        } catch (IllegalServiceParameterException e) {
            response.put("result", ReturnAppResult.APP_FAIL.getResultCode());
            response.put("msg", e.getMessage());
            return JSONObject.fromObject(response).toString();
        }
        // 业务层统一处理
        try {
            Map<String, Object> data = doBusiness(map);
            Integer orderCode = Integer.parseInt(data.get("code").toString());
            if (orderCode > 0) {
                response.put("data", data);
                response.put("result", ReturnAppResult.APP_SUCCESS.getResultCode());
                response.put("msg", ReturnAppResult.APP_SUCCESS.getResultMessage());
            } else {
                response.put("result", ReturnAppResult.APP_FAIL.getResultCode());
                response.put("msg", data.get("msg").toString());
            }
        } catch (ServiceRunException e) {
            response.put("result", ReturnAppResult.APP_FAIL.getResultCode());
            response.put("msg", e.getMessage());
        }

        return JSONObject.fromObject(response).toString();
    }

    /**
     * 业务层统校验自己所需参数是否存在
     *
     * @param map 请求参数封装成Map对象
     * @return 统一返回参数
     * @author charmyin
     * @version [v1.0.0, 2015年7月1日]
     * @since [产品/模块版本](可选)
     */
    protected void checkInterfaceParameter(Map<String, Object> map) throws IllegalServiceParameterException {
        // 方法所需参数
        for (String str : CreditGoodsDetails) {
            // 如果不存在跳出 同时抛出相应异常
            if (!map.containsKey(str)) {
                LOGGER.error("业务入口参数异常：" + str + "参数为空!");
                throw new IllegalServiceParameterException("业务入口参数异常：" + str + "参数为空!");
            }

        }
    }

    /**
     * 业务层统逻辑处理
     *
     * @param
     * @return 统一返回参数
     * @throws ServiceRunException
     * @author nizhengjia
     * @version [v1.0.0, 2015年8月18日]
     * @since [产品/模块版本](可选)
     */
    @SuppressWarnings("null")
    protected Map<String, Object> doBusiness(Map<String, Object> map) throws ServiceRunException {
        // 返回Json对象
        Map<String, Object> resultMap = new HashMap<String, Object>();

        /**
         * 入参：用户Id,用户手机,购买商品Id,购买商品数据,手机验证码,
         * 抢单数量达到库存后，直接排除其他用户（用户id需要唯一，不给重复刷单）
         * 返回系统时间
         * 如果抢单成功：抢单数量加1，返回抢单成功，当前系统时间，记录抢单人~
         * 如果抢单失败：返回当前系统时间
         */
        try {
            CmSeckillRemindEntity entity = new CmSeckillRemindEntity();
            String phone = ((String[]) map.get(USERPHONE))[0];
            Integer goodsId = Integer.parseInt(((String[]) map.get(GOODSID))[0]);
            String userId = ((String[]) map.get(USERID))[0];
            String remindType = ((String[]) map.get(REMINDTYPE))[0];
            //获取提醒时间
            CmCreditGoodsEntity goods = cmCreditGoodsDao.getById(goodsId);
            entity.setRemindTime(goods.getSeckillStartTime());
            //同一个用户，如果时间已经存在，则不重复入库
            QueryParams<CmSeckillRemindEntity> queryParams = new QueryParams<CmSeckillRemindEntity>();
            Map<String, Object> searchParams = new HashMap<String, Object>();
            searchParams.put("EQ_goodId", goodsId);
            searchParams.put("EQ_userId", userId);
            queryParams.setSearchParams(searchParams);
            List<CmSeckillRemindEntity> list = secKillRemindDao.queryAll(queryParams);

            if (remindType.equals("cancel")) {
                for (CmSeckillRemindEntity et : list) {
                    secKillRemindDao.delete(et.getId());
                }
                resultMap.put("code", "3");//抢单成功
                resultMap.put("msg", "取消成功!");//抢单成功
                return resultMap;
            }

            if (list != null && list.size() > 0) {
                resultMap.put("code", "2");
                resultMap.put("msg", "设定成功!");
                return resultMap;
            }

            //商品可用的促销信息
            HashMap<String, HashMap> promotions = promotionProductService.getProductHitPromotions(goodsId);
            if (null != promotions && promotions.containsKey("1")) {
                //用户是否命中新人专享
                boolean canUse = promotionProductService.checkUserIsHitNewUserPromotion(promotions, userId);
                if (!canUse) {
                    resultMap.put("code", "-1");
                    resultMap.put("msg", promotions.get("1").get("msg"));
                    return resultMap;
                }
            }

            entity.setUserPhone(phone);
            entity.setUserId(userId);
            entity.setGoodId(goodsId);

            secKillRemindDao.save(entity);
            resultMap.put("code", "1");//抢单成功
            resultMap.put("msg", "设定成功!");//抢单成功
            return resultMap;
        } catch (Exception ex) {
            LOGGER.error("提交订单接口异常(OrderSubmit Error)！", ex);
            throw new ServiceRunException("提交数据异常!");
        }
    }


    /**
     * 判断服务是否具有控制逻辑
     *
     * @return 是否判断
     */
    public boolean isControlService() {

        return false;
    }

    /**
     * 判断服务是否需要记录日志
     *
     * @return 是否判断
     */
    public boolean isLogService() {

        return false;
    }

    /**
     * 判断服务是否需要监控
     *
     * @return 是否判断
     */
    public boolean isMonitorService() {

        return false;
    }

    /**
     * 事务回滚
     *
     * @return 事务回滚预留结果，暂无用途
     */
    public Object rollback() {

        return null;
    }

    /**
     * 事务提交
     */
    public void commit() {

    }
}
