package com.house365.ws.interfaces.rest;

import com.house365.beans.entity.CmOrderEntity;
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.service.interfaces.ICmOrderService;
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.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component("historyOrderListInterface")
public class HistoryOrderListInterfaceImpl implements IHistoryOrderListInterface {

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

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

    @Autowired
    ICmOrderService<CmOrderEntity> cmOrderService;

    @Autowired
    ICmUserService<CmUserEntity> iCmUserService;

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

    public static Date parseDate(String datestr, String format) {
        SimpleDateFormat df = new SimpleDateFormat(format);
        Date date = null;
        try {
            date = df.parse(datestr);
        } catch (java.text.ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

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

        // 业务校验统一入口
        try {
            checkInterfaceParameter(map);
        } catch (IllegalServiceParameterException e) {
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg(e.getMessage());
            return JSONObject.fromObject(response).toString();
        }
        // 业务层统一处理
        try {
            House365RestObject<CmOrderEntity> 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());
        }
        String result = JSONObject.fromObject(response).toString().replaceAll(" 00:00:00", "");
        return result;
    }

    /**
     * 业务层统校验自己所需参数是否存在
     *
     * @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日]
     * @modify wenjiaxin 2018.6.19 增加排序字段，返回报文按时间排序
     * @since [产品/模块版本](可选)
     */
    protected House365RestObject<CmOrderEntity> doBusiness(Map<String, Object> map) throws ServiceRunException {
        // 返回Json对象
        House365RestObject<CmOrderEntity> restObject = new House365RestObject<CmOrderEntity>();
        try {
            String cityKey = ((String[]) map.get(CmConstant.CITY_KEY))[0];
            // 请求的页码
            Integer currentPage = Integer.parseInt(((String[]) map.get(CmConstant.PAGE))[0]);
            // 每页数据条数
            Integer pageSize = Integer.parseInt(((String[]) map.get(CmConstant.PAGESIZE))[0]);
            Page page = new Page();
            if (null != currentPage) {
                page.setCurrentPage(currentPage);
            }
            if (null != pageSize) {
                page.setPageSize(pageSize);
            }

            String userId = ((String[]) map.get(CmConstant.USERID))[0];

            // 查询参数
            Integer useridType = Integer.parseInt(((String[]) map.get(CmConstant.USERID_TYPE))[0]);
            String userCityKey = null;
            //如果不是用户中心的用户，则需要城市字段
            if (CmConstant.USERID_TYPE_OTHER == useridType) {
                userCityKey = ((String[]) map.get(CmConstant.USER_CITY_KEY))[0];
            }
            CmUserEntity cmUser = iCmUserService.getUserByUserIdCityKeyUserType(userId, cityKey, useridType);
            if (cmUser == null) {
                throw new ServiceRunException("用户无积分信息!");
            }

            // 查询参数
            Map<String, Object> params = new HashMap<>();
            params.put("EQ_userId", cmUser.getId());
            params.put("EQ_cityKey", cityKey);
            params.put("EQ_headquartersKey", "zbu");
            QueryParams<CmOrderEntity> queryParams = new QueryParams<>(params);
            queryParams.setPaging(page);
            queryParams.setOrderColumn("create_time");
            queryParams.setOrderMode("desc");
            List<CmOrderEntity> cmList = cmOrderService.queryByPage(queryParams);
            for (CmOrderEntity orderEntity : cmList) {
                if (null != orderEntity.getCreateTime()) {
                    orderEntity.setCreateDateTime(parseDate(orderEntity.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
                    orderEntity.setCreateTime(null);
                }
                if (null != orderEntity.getDeliverTime()) {
                    orderEntity.setDeliverDateTime(parseDate(orderEntity.getDeliverTime(), "yyyy-MM-dd HH:mm:ss"));
                    orderEntity.setDeliverTime(null);
                }
                if (null != orderEntity.getReceiveTime()) {
                    orderEntity.setReceiveDateTime(parseDate(orderEntity.getReceiveTime(), "yyyy-MM-dd HH:mm:ss"));
                    orderEntity.setReceiveTime(null);
                }
            }
            restObject.setList(cmList);
            restObject.setTotal(String.valueOf(cmOrderService.getTotalCount(queryParams)));
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error(e.getMessage());
            throw new ServiceRunException(e.getMessage());
        }
        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

    }

}
