/*
 * 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.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.house365.beans.entity.CmCreditGoodsEntity;
import com.house365.rest.context.CmConstant;
import com.house365.rest.context.Parameter;
import com.house365.rest.exception.IllegalServiceParameterException;
import com.house365.rest.exception.ServiceRunException;
import com.house365.rest.parameter.House365RestObject;
import com.house365.rest.parameter.House365RestResponse;
import com.house365.ws.cached.RedisUtilsInterface;
import com.house365.ws.service.interfaces.ICmCreditGoodsService;
import com.house365.ws.system.ReturnAppResult;

/**
 * 〈一句话功能简述〉<br>
 * 获取商品详情接口
 *
 * @author Administrator
 * @version [版本号, 2015年5月5日]
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
@Component("getCreditGoodsDetailsInterface")
public class GetCreditGoodsDetailsInterfaceImpl implements IGetCreditGoodsDetailsInterface {

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

    /**
     * ID
     */
    public static final String ID = "id";
    /**
     * 参数列表
     */
    private static final String[] PARAMS = {ID};

    @Autowired
    private ICmCreditGoodsService<CmCreditGoodsEntity> creditGoodsService;
    @Autowired
    ICmPromotionProductService promotionProductService;
    @Autowired
    ICmPromotionService promotionService;

    @Autowired
    RedisUtilsInterface redisUtils;

    @Override
    public Object exectue(Parameter parameter) throws ServiceRunException {
        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        House365RestResponse<Map<String, Object>> response = new House365RestResponse<Map<String, Object>>();
        // 业务校验统一入口
        try {
            checkInterfaceParameter(map);
        } catch (IllegalServiceParameterException e) {
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg(e.getMessage());
            return JSONObject.fromObject(response).toString();
        }
        // 业务层统一处理
        try {
            House365RestObject<Map<String, Object>> data = doBusiness(map);
            response.setData(data);
            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage());
        } catch (ServiceRunException e) {
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg(e.getMessage());
        }

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

    /**
     * 业务层统校验自己所需参数是否存在
     *
     * @param map 请求参数封装成Map对象
     * @return 统一返回参数
     * @author nizhengjia
     * @version [v1.0.0, 2015年7月1日]
     * @since [产品/模块版本](可选)
     */
    protected void checkInterfaceParameter(Map<String, Object> map) throws IllegalServiceParameterException {
        // 方法所需参数
        for (String str : PARAMS) {
            // 如果不存在跳出 同时抛出相应异常
            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("unused")
    protected House365RestObject<Map<String, Object>> doBusiness(Map<String, Object> map) throws ServiceRunException {
        // 返回Json对象
        House365RestObject<Map<String, Object>> restObject = new House365RestObject<Map<String, Object>>();
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        Map<String, Object> creditGoodsMap = new HashMap<String, Object>();
        try {
            String id = ((String[]) map.get(ID))[0];
            if (StringUtils.isNotBlank(id)) {
                //根据商品Id获取商品详情
                CmCreditGoodsEntity creditGoodsEntity = creditGoodsService.getById(Integer.valueOf(id));
                String startTime = null;
                String endTime = null;
                String createTime = null;
                String updateTime = null;
                if (null != creditGoodsEntity) {
                    if (null != creditGoodsEntity.getStartTime() && null != creditGoodsEntity.getEndTime()) {
                        startTime = parseDate(creditGoodsEntity.getStartTime(), "yyyy-MM-dd");
                        endTime = parseDate(creditGoodsEntity.getEndTime(), "yyyy-MM-dd");
                    }
                    if (null != creditGoodsEntity.getCreateTime()) {
                        createTime = parseDate(creditGoodsEntity.getCreateTime(), "yyyy-MM-dd HH:mm:ss");
                    }
                    if (null != creditGoodsEntity.getUpdateTime()) {
                        updateTime = parseDate(creditGoodsEntity.getUpdateTime(), "yyyy-MM-dd HH:mm:ss");
                    }
                    creditGoodsMap.put("id", creditGoodsEntity.getId());
                    creditGoodsMap.put("goodsName", creditGoodsEntity.getGoodsName());
                    creditGoodsMap.put("goodsId", creditGoodsEntity.getGoodsId());
                    creditGoodsMap.put("goodsType", creditGoodsEntity.getGoodsType());
                    creditGoodsMap.put("indexPicture", creditGoodsEntity.getIndexPicture());
                    creditGoodsMap.put("detailPicture", creditGoodsEntity.getDetailPicture());
                    creditGoodsMap.put("creditsNeeded", creditGoodsEntity.getCreditsNeeded());
                    creditGoodsMap.put("price", creditGoodsEntity.getPrice());
                    creditGoodsMap.put("stock", creditGoodsEntity.getStock());
                    creditGoodsMap.put("orderNumber", creditGoodsEntity.getOrderNumber());
                    creditGoodsMap.put("description", creditGoodsEntity.getDescription());
                    creditGoodsMap.put("usableRange", creditGoodsEntity.getUsableRange());
                    creditGoodsMap.put("listPicture", creditGoodsEntity.getListPicture());
                    creditGoodsMap.put("smallListPicture", creditGoodsEntity.getSmallListPicture());
                    creditGoodsMap.put("exchangeProcess", creditGoodsEntity.getExchangeProcess());
                    creditGoodsMap.put("announcement", creditGoodsEntity.getAnnouncement());
                    creditGoodsMap.put("startTime", startTime);
                    creditGoodsMap.put("endTime", endTime);
                    creditGoodsMap.put("status", creditGoodsEntity.getStatus());
                    creditGoodsMap.put("cityId", creditGoodsEntity.getCityId());
                    creditGoodsMap.put("cityName", creditGoodsEntity.getCityName());
                    creditGoodsMap.put("updateTime", updateTime);
                    creditGoodsMap.put("createTime", createTime);
                    creditGoodsMap.put("isDeleted", creditGoodsEntity.getIsDeleted());
                    creditGoodsMap.put("latestBatch", creditGoodsEntity.getLatestBatch());
                    creditGoodsMap.put("latestBatchName", creditGoodsEntity.getLatestBatchName());
                    creditGoodsMap.put("adLink", creditGoodsEntity.getAdLink());
                    creditGoodsMap.put("seckillEndTime", creditGoodsEntity.getSeckillEndTime());
                    creditGoodsMap.put("seckillStartTime", creditGoodsEntity.getSeckillStartTime());
                    creditGoodsMap.put("isSeckill", creditGoodsEntity.getIsSeckill());
                    creditGoodsMap.put("isBuyLimit", creditGoodsEntity.getIsBuyLimit());
                    creditGoodsMap.put("thirdLink", creditGoodsEntity.getThirdLink());
                    if (creditGoodsEntity.getIsSeckill() == 1) {
                        //获取jedis链接
                        //Jedis jedisClient = redisConnectionPool.getResource();

                        Long listSize = redisUtils.getListSize(
                            CmConstant.SECKILL_LEFT_STOCK_LIST + creditGoodsEntity.getId());
                        if (listSize == null || listSize <= 0) {
                            creditGoodsEntity.setIsLooted(1);
                        } else {
                            creditGoodsEntity.setIsLooted(0);
                        }

                        creditGoodsMap.put("isLooted", creditGoodsEntity.getIsLooted());
                    }

                    String userID = "";
                    if (null != map.get(CmConstant.USERID)) {
                        userID = ((String[]) map.get(CmConstant.USERID))[0];
                    }
                    //商品可用的促销信息
                    HashMap<String, HashMap> promotions = promotionProductService.getProductHitPromotions(
                        creditGoodsEntity.getId());
                    if (null != promotions) {
                        //用户是否命中新人专享
                        promotionProductService.checkUserIsHitNewUserPromotion(promotions, userID);
                        creditGoodsMap.put("promotions", promotions);
                    }

                    list.add(creditGoodsMap);
                }
            }
            if (null != list && list.size() != 0) {
                restObject.setTotal(list.size() + "");
                restObject.setList(list);
            } else {
                restObject.setTotal("0");
            }
            return restObject;
        } catch (Exception ex) {
            ex.printStackTrace();
            LOGGER.error("查询商品详情异常(Get GetCreditGoodsDetails Error)！");
            throw new ServiceRunException("网络不给力，请刷新重试");

        }
    }

    public static String parseDate(Date date, String format) {
        SimpleDateFormat dateformat = new SimpleDateFormat(format);
        return dateformat.format(date);
    }


    /**
     * 判断服务是否具有控制逻辑
     *
     * @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() {

    }
}
