package com.house365.ws.interfaces.rest;

import com.google.common.base.Strings;
import com.house365.beans.entity.UserEntity;
import com.house365.beans.entity.UserEvaluateEntity;
import com.house365.beans.system.Page;
import com.house365.beans.system.QueryParams;
import com.house365.rest.context.IService;
import com.house365.rest.context.Parameter;
import com.house365.rest.exception.ServiceRunException;
import com.house365.rest.parameter.House365RestObject;
import com.house365.rest.parameter.House365RestResponse;
import com.house365.ws.beans.request.DepartmentListRequest;
import com.house365.ws.service.interfaces.IUserService;
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.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("getEvaluationList")
public class GetEvaluationListImpl implements IGetEvaluationList {

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

    @Autowired
    private IUserService<UserEntity> userService;

    private static final int pageSize = 20;

    @Override
    public Object exectue(Parameter parameter) throws ServiceRunException {
        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        House365RestResponse<UserEvaluateEntity> response = new House365RestResponse<>();
        // 业务层统一处理
        try {
            House365RestObject<UserEvaluateEntity> 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 UserEntity getUserEntity(String phone) {
        UserEntity user = null;
        Map<String, Object> qm = new HashMap<>();
        qm.put("EQ_mobile", phone);
        QueryParams queryParams = new QueryParams(qm);
        List<UserEntity> userEntities = userService.queryAll(queryParams);
        if (userEntities != null && !userEntities.isEmpty()) {
            user = userEntities.get(0);
        }
        return user;
    }

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

    @Override
    public void commit() {

    }

    /**
     * 业务层统逻辑处理
     */
    private House365RestObject<UserEvaluateEntity> doBusiness(Map<String, Object> map) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 返回Json对象
        House365RestObject<UserEvaluateEntity> restObject = new House365RestObject<>();
        String checkStatus = getMapValueByKey("checkStatus", map, "");
        String phone = getMapValueByKey("phone", map, "");
        Integer page = Integer.valueOf(getMapValueByKey("page", map, ""));
        Integer startPage = 0;
        if(page>0){
            startPage = (page-1) * pageSize;
        }
        UserEntity ue = getUserEntity(phone);
        Integer userId= ue.getId();
        UserEvaluateEntity uee = new UserEvaluateEntity();
        uee.setUserId(userId);
        uee.setCheckStatus(checkStatus);//0:待审核,1：审核通过;2：审核不通过;
        uee.setIsDeleted("0");//删除标记 0：未删除；1：已删除；
        uee.setPageSize(pageSize);
        uee.setStartPage(startPage);
        uee.setIsEvaluated("1");
        List<UserEvaluateEntity> uueList = userService.queryEvaluateListById(uee);
        if(uueList!=null && uueList.size()>0){
            for(int i=0;i<uueList.size();i++){
                UserEvaluateEntity tempUee = uueList.get(i);
                Date evaluateTime = tempUee.getEvaluateTime();
                if(evaluateTime!=null){
                    String evaTime = sdf.format(evaluateTime);
                    uueList.get(i).setEvaTime(evaTime);
                }
                //评价标签分割
                String contentTags = tempUee.getContentTags();
                if(contentTags != null && !"".equals(contentTags)){
                    String[] tagsArr = contentTags.split(" ");
                    tempUee.setTagsArr(tagsArr);
                }
            }
        }

        restObject.setList(uueList);
        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;
    }
    @Override
    public boolean isControlService() {
        return false;
    }

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

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