package com.house365.ws.interfaces.rest;

import com.google.common.base.Strings;
import com.house365.beans.entity.BaseAttachment;
import com.house365.beans.entity.EvaluateUserCustomerLogEntity;
import com.house365.beans.po.EvaluateUserCustomerLogPo;
import com.house365.beans.system.Page;
import com.house365.beans.system.QueryParams;
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.web.util.DateTimeUtils;
import com.house365.web.util.StringUtils;
import com.house365.ws.service.interfaces.IAttachmentService;
import com.house365.ws.service.interfaces.IEvaluateUserCustomerLogService;
import com.house365.ws.system.ReturnAppResult;
import com.house365.ws.util.Constant;
import net.sf.json.JSONObject;
import org.apache.commons.collections.map.HashedMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * <p>Title: 获取直销人员带看评价列表</p>
 * <p>Description: </p>
 * <p>Date: 16/9/15</p>
 *
 * @author XN
 * @version 1.0
 */
@Service("getEvaluatesByCity")
public class GetEvluatesByCityImpl implements IGetEvaluatesByCity {

    private static final Logger LOGGER = LoggerFactory.getLogger(GetEvluatesByCityImpl.class);

    @Autowired
    private IEvaluateUserCustomerLogService<EvaluateUserCustomerLogEntity> evaluateService;
    @Autowired
    private IAttachmentService attachmentService;

    @Override
    public Object rollback() {
        return null;
    }

    @Override
    public void commit() {

    }

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

    /**
     * 业务层统逻辑处理
     */
    private House365RestObject<EvaluateUserCustomerLogPo> doBusiness(Map<String, Object> map) throws Exception {
        // 返回Json对象
        House365RestObject<EvaluateUserCustomerLogPo> restObject = new House365RestObject<>();
        String cityCode = getMapValueByKey(Constant.CITY_CODE, map, "");
        String currentPage = getMapValueByKey("currentPage", map, "");
        String pageSize = getMapValueByKey("pageSize", map, "");

        Map<String, Object> queryMap = new HashMap<>(10);
        queryMap.put("EQ_city", cityCode);
        queryMap.put("EQ_checkStatus", 1);//审核通过
        queryMap.put("EQ_isDeleted", 0);//且未删除的

        Page page = new Page();
        page.setCurrentPage(Integer.valueOf(StringUtils.isBlank(currentPage) ? "1" : currentPage));
        page.setPageSize(Integer.valueOf(StringUtils.isBlank(pageSize) ? "20" : pageSize));

        QueryParams userParams = new QueryParams();
        userParams.setPaging(page);
        userParams.setOrderColumn("a.id");
        userParams.setOrderMode("desc");
        userParams.setSearchParams(queryMap);

        List<EvaluateUserCustomerLogEntity> evaluates = evaluateService.queryByPage(userParams);

        List<EvaluateUserCustomerLogPo> evaluateUserCustomerLogPos = new ArrayList<>();
        for (EvaluateUserCustomerLogEntity evaluate : evaluates) {
            EvaluateUserCustomerLogPo evaluatePo = new EvaluateUserCustomerLogPo();
            evaluatePo.setId(evaluate.getId());
            evaluatePo.setUserId(evaluate.getUserId());

            List<BaseAttachment> headImg = attachmentService.queryByResourceIdAndResouceType(String.valueOf(evaluate.getUserId()), "hgs_user_headImg");

            if (headImg != null && headImg.size() != 0) {
                evaluatePo.setHeadImgURL(headImg.get(0).getRemotePath());
            } else {
                evaluatePo.setHeadImgURL("http://img33.house365.com/M00/1B/86/rBEBp1pu2JyAIp4jAAAGEjOUX2M365.jpg");
            }

            evaluatePo.setUserName(evaluate.getUserName());
            evaluatePo.setProjectId(evaluate.getProjectId());
            evaluatePo.setProjectName(evaluate.getProjectName());
            evaluatePo.setCustomerName(evaluate.getCustomerName());
            evaluatePo.setScore(evaluate.getScore());
            evaluatePo.setContent(evaluate.getContent());
            evaluatePo.setCreateTime(evaluate.getCreateTime());
            evaluatePo.setCreateTimeStr(DateTimeUtils.parseDate(evaluate.getCreateTime(), "yyyy年MM月dd日"));
            evaluatePo.setEvaluateTime(evaluate.getEvaluateTime());
            evaluatePo.setChannel(evaluate.getChannel());

            evaluateUserCustomerLogPos.add(evaluatePo);
        }

        restObject.setList(evaluateUserCustomerLogPos);

        restObject.setTotal(String.valueOf(page.getRecords()));
        return restObject;
    }

    /**
     * 获取map中的值
     *
     * @param key          key
     * @param map          map
     * @param defaultValue 默认值
     * @return value
     */
    private String getMapValueByKey(String key, Map<String, Object> map, String defaultValue) {
        String value = "";
        if (map.containsKey(key) && map.get(key) != null && !Strings.isNullOrEmpty(((String[]) map.get(key))[0])) {
            value = ((String[]) map.get(key))[0];
        }

        if (Strings.isNullOrEmpty(value)) {
            value = defaultValue;
        }
        return value;
    }

    /**
     * 业务层统校验自己所需参数是否存在
     * 所有参数都要存在
     *
     * @author hqc
     */
    protected void checkInterfaceParameter(
            Map<String, Object> map, String[] checkParams
    ) throws IllegalServiceParameterException {
        // 方法所需参数
        for (String str : checkParams) {
            // 如果不存在跳出 同时抛出相应异常
            if (!map.containsKey(str)) {
                throw new IllegalServiceParameterException("业务入口参数异常：" + str + "参数为空!");
            }
        }
    }

    @Override
    public boolean isControlService() {
        return false;
    }

    @Override
    public boolean isLogService() {
        return false;
    }

    @Override
    public boolean isMonitorService() {
        return false;
    }
}
