package com.house365.ws.interfaces.rest;

import com.google.common.base.Strings;
import com.house365.beans.entity.CmCreditGoodsEntity;
import com.house365.beans.entity.CmSeckillRemindEntity;
import com.house365.beans.entity.CmUserEntity;
import com.house365.beans.system.Page;
import com.house365.beans.system.QueryParams;
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.dao.interfaces.ICmSeckillRemindDao;
import com.house365.ws.service.interfaces.ICmCreditGoodsService;
import com.house365.ws.service.interfaces.ICmPromotionProductService;
import com.house365.ws.service.interfaces.ICmPromotionService;
import com.house365.ws.service.interfaces.ICmUserService;
import com.house365.ws.system.ReturnAppResult;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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

@Component("getGoodsList")
public class GetGoodsListImpl implements IGetGoodsList {

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

    @Autowired
    RedisUtilsInterface redisUtils;
    @Autowired
    ICmPromotionProductService promotionProductService;
    @Autowired
    ICmPromotionService promotionService;
    @Autowired
    ICmUserService cmUserService;

    /**
     * 参数列表
     */
    private static final String[] PARAMS = {CmConstant.PAGESIZE, CmConstant.PAGE};

    @Autowired
    ICmCreditGoodsService<CmCreditGoodsEntity> cmCreditGoodsService;

    @Autowired
    private ICmSeckillRemindDao<CmSeckillRemindEntity> secKillRemindDao;

    @Override
    public Object exectue(Parameter parameter) throws ServiceRunException {
        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        House365RestResponse<CmCreditGoodsEntity> response = new House365RestResponse<CmCreditGoodsEntity>();

        // 业务校验统一入口
        try {
            checkInterfaceParameter(map);
        } catch (IllegalServiceParameterException e) {
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg(e.getMessage());
            return JSONObject.fromObject(response).toString();
        }

        // 业务层统一处理
        try {
            House365RestObject<CmCreditGoodsEntity> 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年5月6日]
     * @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 统一返回参数
     * @author nizhengjia
     * @version [v1.0.0, 2015年5月6日]
     * @since [产品/模块版本](可选)
     */
    protected House365RestObject<CmCreditGoodsEntity> doBusiness(Map<String, Object> map) throws ServiceRunException {
        // 返回Json对象
        House365RestObject<CmCreditGoodsEntity> restObject = new House365RestObject<CmCreditGoodsEntity>();
        try {
            // 请求的页码
            Integer currentPage = Integer.parseInt(((String[]) map.get(CmConstant.PAGE))[0]);
            // 每页数据条数
            Integer pageSize = Integer.parseInt(((String[]) map.get(CmConstant.PAGESIZE))[0]);
            // 分页表达式
            // Integer page = (currentPage - 1) * pageSize;
            // 查询参数
            Map<String, Object> param = new HashMap<String, Object>();
            if (map.get("activeOnly") != null) {
                Integer activeOnly = Integer.parseInt(((String[]) map.get("activeOnly"))[0]);
                param.put("EQ_activeOnly", activeOnly);
            }
            //用户积分数
            if (map.get(CmConstant.USERCREDITS) != null) {
                Integer userCredits = Integer.parseInt(((String[]) map.get(CmConstant.USERCREDITS))[0]);
                param.put("LTE_creditsNeeded", userCredits);
            }
            //用户城市
            if (map.get(CmConstant.CITY_KEY) != null) {
                String cityKey = ((String[]) map.get(CmConstant.CITY_KEY))[0];
                param.put("EQ_cityKey", cityKey);
                //同时要包含总部
                param.put("EQ_headquartersKey", CmConstant.ZONGBU);
            }
            //积分区间，最小值
            if (map.get(CmConstant.MIN_CREDITS) != null) {
                Integer min = Integer.parseInt(((String[]) map.get(CmConstant.MIN_CREDITS))[0]);
                param.put("GTE_minCredits", min);
            }
            //积分区间，最大值
            if (map.get(CmConstant.MAX_CREDITS) != null) {
                Integer max = Integer.parseInt(((String[]) map.get(CmConstant.MAX_CREDITS))[0]);
                param.put("LTE_maxCredits", max);
            }
            //只显示已上架商品
            param.put("EQ_status", 0);
            param.put("EQ_avilableonly", 1);

            Page paging = new Page();
            paging.setCurrentPage(currentPage);
            paging.setPageSize(pageSize);

            QueryParams<CmCreditGoodsEntity> queryParam = new QueryParams<CmCreditGoodsEntity>();
            queryParam.setSearchParams(param);
            queryParam.setPaging(paging);
            //排序
            if (map.get(CmConstant.ORDER_FIELD) != null) {
                String orderField = ((String[]) map.get(CmConstant.ORDER_FIELD))[0];
                queryParam.setOrderColumn(orderField);
                if (map.get(CmConstant.ORDER_DESC_OR_ACS) != null) {
                    String ascOrDesc = ((String[]) map.get(CmConstant.ORDER_DESC_OR_ACS))[0];
                    queryParam.setOrderMode(ascOrDesc);
                }
            } else {
                queryParam.setOrderColumn("sort_value desc,");
                queryParam.setOrderMode("order_number desc, seckill_start_time asc");
            }

            String userID = "";
            if (null != map.get(CmConstant.USERID)) {
                userID = ((String[]) map.get(CmConstant.USERID))[0];
            }
            param.put("EQ_inSoldOutRange", "1");
            List<CmCreditGoodsEntity> cmList = cmCreditGoodsService.queryByPage(queryParam);
            //是否已经被抢光
            for (CmCreditGoodsEntity goodEntity : cmList) {
                if (goodEntity.getIsSeckill() != null && goodEntity.getIsSeckill() == 1) {
                    //获取jedis链接
                    Long listSize = redisUtils.getListSize(CmConstant.SECKILL_LEFT_STOCK_LIST + goodEntity.getId());
                    if (listSize == null || listSize <= 0) {
                        goodEntity.setIsLooted(1);
                    } else {
                        goodEntity.setIsLooted(0);
                    }
                }

                //商品可用的促销信息
                HashMap<String, HashMap> promotions = promotionProductService.getProductHitPromotions(
                    goodEntity.getId());
                if (null != promotions) {
                    //用户是否命中新人专享
                    promotionProductService.checkUserIsHitNewUserPromotion(promotions, userID);
                    goodEntity.setPromotions(promotions);
                }

            }

            //我可兑换商品列表过滤新用户专享商品
            if (map.containsKey(CmConstant.USERCREDITS) && map.get(CmConstant.USERCREDITS) != null) {
                CmUserEntity userEntity = null;
                if (!Strings.isNullOrEmpty(userID)) {
                    userEntity = cmUserService.getUserByUserIdCityKeyUserType(userID, "", 1);
                    if (userEntity == null) {
                        throw new ServiceRunException("该用户不存在!");
                    }
                }

                if (null != userEntity) {
                    for (Iterator<CmCreditGoodsEntity> iter = cmList.iterator(); iter.hasNext(); ) {
                        CmCreditGoodsEntity item = iter.next();
                        HashMap<String, HashMap> promotions = item.getPromotions();
                        if (promotions != null && !promotions.isEmpty()) {
                            if (promotions.containsKey("1")) {
                                //用户是否命中新人专享
                                HashMap config = promotions.get("1");
                                if ("0".equalsIgnoreCase(String.valueOf(config.get("canUse")))) {
                                    iter.remove();
                                }
                            }
                        }
                    }
                }
            }

            //查询是否提醒过
            if (!Strings.isNullOrEmpty(userID)) {
                for (CmCreditGoodsEntity goodEntity : cmList) {
                    if (goodEntity.getIsSeckill() == null || goodEntity.getIsSeckill() != 1) {
                        goodEntity.setIsReminded(0);
                        continue;
                    }
                    QueryParams<CmSeckillRemindEntity> queryParams = new QueryParams<CmSeckillRemindEntity>();
                    Map<String, Object> map1 = new HashMap<String, Object>();
                    map1.put("EQ_userId", userID);
                    map1.put("EQ_goodId", goodEntity.getId());
                    queryParams.setSearchParams(map1);
                    List<CmSeckillRemindEntity> listEntity = secKillRemindDao.queryAll(queryParams);
                    if (listEntity != null && listEntity.size() > 0) {
                        goodEntity.setIsReminded(1);
                    } else {
                        goodEntity.setIsReminded(0);
                    }

                }
            }
            restObject.setList(cmList);
            restObject.setTotal(String.valueOf(cmCreditGoodsService.getTotalCount(queryParam)));
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            throw new ServiceRunException("网络不给力，请刷新重试");
        }
        return restObject;
    }


    @Override
    public boolean isControlService() {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public boolean isLogService() {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public boolean isMonitorService() {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public Object rollback() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void commit() {
        // TODO Auto-generated method stub

    }

}
