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

import com.google.common.base.Strings;
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.CmOrderEntity;
import com.house365.rest.context.Parameter;
import com.house365.rest.exception.IllegalServiceParameterException;
import com.house365.rest.exception.ServiceRunException;
import com.house365.ws.service.interfaces.ICmOrderService;
import com.house365.ws.system.ReturnAppResult;

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

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

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

    @Autowired
    private ICmOrderService<CmOrderEntity> orderService;

    @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);
            response.put("data", data);
            response.put("result", ReturnAppResult.APP_SUCCESS.getResultCode());
            response.put("msg", ReturnAppResult.APP_SUCCESS.getResultMessage());
        } 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 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 Map<String, Object> doBusiness(Map<String, Object> map) throws ServiceRunException {
        // 返回Json对象
        Map<String, Object> orderMap = new HashMap<String, Object>();
        try {
            String id = ((String[]) map.get(ID))[0];
            if (StringUtils.isNotBlank(id)) {
                //根据商品Id获取商品详情
                CmOrderEntity orderEntity = orderService.getById(Integer.valueOf(id));
                String createTime = null;
                String deliverTime = null;
                String receiveTime = null;

                if (null != orderEntity) {


                    if (null != orderEntity.getCreateTime()) {
                        createTime = parseDate(orderEntity.getCreateTime(), "yyyy-MM-dd HH:mm:ss");
                    }
                    if (null != orderEntity.getDeliverTime()) {
                        deliverTime = parseDate(orderEntity.getDeliverTime(), "yyyy-MM-dd HH:mm:ss");
                    }
                    if (null != orderEntity.getReceiveTime()) {
                        receiveTime = parseDate(orderEntity.getReceiveTime(), "yyyy-MM-dd HH:mm:ss");
                    }
                    orderMap.put("id", orderEntity.getId());
                    orderMap.put("createTime", createTime);
                    orderMap.put("userId", orderEntity.getUserId());
                    orderMap.put("userName", orderEntity.getUserName());
                    orderMap.put("userPhone", orderEntity.getUserPhone());
                    orderMap.put("deliverType", orderEntity.getDeliverType());

                    if ("自提".equals(orderEntity.getDeliverType())) {
                        orderMap.put("deliverType", "自提");
                        orderMap.put("oerderNumber", orderEntity.getOerderNumber());
                    }
                    if ("快递".equals(orderEntity.getDeliverType())) {
                        if (Strings.isNullOrEmpty(orderEntity.getExpressCompany())) {
                            orderMap.put("oerderNumber", "暂无");
                        } else {
                            orderMap.put("oerderNumber",
                                         orderEntity.getExpressCompany() + "[" + orderEntity.getOerderNumber() + "]");
                            if ("自提".equals(orderEntity.getExpressCompany())) {
                                orderMap.put("oerderNumber", orderEntity.getOerderNumber());
                            }
                        }
                    } else {
                        if (null != orderEntity.getDeliverTime()) {
                            deliverTime = parseDate(orderEntity.getDeliverTime(), "yyyy-MM-dd");
                        }
                        if (null != orderEntity.getReceiveTime()) {
                            receiveTime = parseDate(orderEntity.getReceiveTime(), "yyyy-MM-dd");
                        }
                        orderMap.put("oerderNumber", orderEntity.getOerderNumber());
                    }
                    orderMap.put("receiverName", orderEntity.getReceiverName());
                    orderMap.put("receiverPhone", orderEntity.getReceiverPhone());
                    orderMap.put("receiverArea", orderEntity.getReceiverArea());
                    orderMap.put("receiverDetailAddress", orderEntity.getReceiverDetailAddress());
                    orderMap.put("receiverZipCode", orderEntity.getReceiverZipCode());
                    orderMap.put("credits", orderEntity.getCredits());
                    orderMap.put("exchangedCount", orderEntity.getExchangedCount());
                    orderMap.put("totolSendedGoods", orderEntity.getTotolSendedGoods());
                    orderMap.put("orderStatus", orderEntity.getOrderStatus());
                    orderMap.put("expressCompany", orderEntity.getExpressCompany());

                    orderMap.put("cityId", orderEntity.getCityId());
                    orderMap.put("cityName", orderEntity.getCityName());
                    orderMap.put("isDeleted", orderEntity.getIsDeleted());
                    orderMap.put("isSeckill", orderEntity.getIsSeckill());
                    orderMap.put("goodsId", orderEntity.getGoodsId());
                    orderMap.put("goodsName", orderEntity.getGoodsName());
                    orderMap.put("goodsAmount", orderEntity.getGoodsAmount());
                    orderMap.put("goodsPicture", orderEntity.getGoodsPicture());
                    orderMap.put("goodsType", orderEntity.getGoodsType());
                    orderMap.put("goodsCreditAmount", orderEntity.getGoodsCreditAmount());
                    orderMap.put("goodsTotalCreditAmount", orderEntity.getGoodsTotalCreditAmount());
                    orderMap.put("deliverTime", deliverTime);
                    orderMap.put("receiveTime", receiveTime);
                }
            }
            return orderMap;
        } catch (Exception ex) {
            ex.printStackTrace();
            LOGGER.error("历史订单详情异常(Get HistoryOrderDetails 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() {

    }
}
