package com.house365.ws.interfaces.rest;

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

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 com.house365.beans.entity.CmCreditRecordEntity;
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.ICmCreditRecordService;
import com.house365.ws.service.interfaces.ICmUserService;
import com.house365.ws.system.ReturnAppResult;

@Component("getUserBillList")
public class GetUserBillListImpl implements IGetUserBillList {

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


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


    @Autowired
    ICmUserService<CmUserEntity> iCmUserService;

    @Autowired
    ICmCreditRecordService<CmCreditRecordEntity> iCmCreditRecordService;

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

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

        // 业务层统一处理
        try {
            House365RestObject<CmCreditRecordEntity> 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<CmCreditRecordEntity> doBusiness(Map<String, Object> map) throws ServiceRunException {
        // 返回Json对象
        House365RestObject<CmCreditRecordEntity> restObject = new House365RestObject<CmCreditRecordEntity>();
        try {
            String userId = ((String[]) map.get(CmConstant.USERID))[0];
            // 请求的页码
            Integer currentPage = Integer.parseInt(((String[]) map.get(CmConstant.PAGE))[0]);
            // 每页数据条数
            Integer pageSize = Integer.parseInt(((String[]) map.get(CmConstant.PAGESIZE))[0]);
            // 查询参数
            Integer useridType = Integer.parseInt(((String[]) map.get(CmConstant.USERID_TYPE))[0]);
            String cityKey = null;
            //如果不是用户中心的用户，则需要城市字段
            if (Objects.equals(CmConstant.USERID_TYPE_OTHER, useridType)) {
                cityKey = ((String[]) map.get(CmConstant.USER_CITY_KEY))[0];
            }
            CmUserEntity cmUser = iCmUserService.getUserByUserIdCityKeyUserType(userId, cityKey, useridType);
            if (cmUser == null) {
                throw new ServiceRunException("用户无积分信息!");
            }
            Map<String, Object> param1 = new HashMap<String, Object>();
            param1.put("EQ_userId", cmUser.getId());
            Page page = new Page();
            page.setCurrentPage(currentPage);
            page.setPageSize(pageSize);
            QueryParams<CmCreditRecordEntity> queryParam = new QueryParams<CmCreditRecordEntity>();
            queryParam.setSearchParams(param1);
            queryParam.setPaging(page);
            queryParam.setOrderColumn("id");
            queryParam.setOrderMode("desc");
            List<CmCreditRecordEntity> cmList = iCmCreditRecordService.queryByPage(queryParam);
            if (currentPage > page.getPages()) {
                restObject.setList(null);
            } else {
                restObject.setList(cmList);
            }
            restObject.setTotal(String.valueOf(page.getRecords()));
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            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

    }

}
