package com.xueyi.common.web.controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.google.common.collect.Lists;
import com.xueyi.common.web.constant.ResponseCode;
import com.xueyi.common.web.response.MyResponse;
import com.xueyi.system.api.device.domain.vo.DeviceTenantSourceMergeVo;
import com.xueyi.system.api.device.feign.RemoteDeviceTenantMergeService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Map;

public class BaseApiController {

    @Autowired
    protected Map<Integer, Map<String,String>> responseMessageMap;
    protected final static String EMPTY_STRING = "";

    protected final static String LANGUAGE_CHINESE = "zh";
    private MyResponse message = null;


    public DeviceTenantSourceMergeVo getDeviceTenantSourceMergeVo(String devId){
        return  remoteDeviceTenantMergeService.selectDeviceTenantSourceMerge(devId);
    }


    @Autowired
    private RemoteDeviceTenantMergeService remoteDeviceTenantMergeService;


    protected MyResponse outputSuccess(){
        return outputSuccess(null);
    }
    /**
     * 业务处理成功
     * @param data
     * @return
     */
    protected MyResponse outputSuccess(Object data){
        return output(ResponseCode.SUCCESS, EMPTY_STRING, data);
    }

    protected MyResponse output(final Integer code) {
        return output(code, EMPTY_STRING);
    }

    protected MyResponse output(final Integer code, final String replaceParameter) {
        return output(code, replaceParameter, null);
    }


    protected MyResponse output(final Integer code, final String replaceParameter, final Object data) {
        if (null == replaceParameter) {
            return output(code, Lists.newArrayList(EMPTY_STRING), data, null);
        }
        return output(code, Lists.newArrayList(replaceParameter), data, null);
    }

    protected MyResponse output(final Integer code, final List<String> replaceParameters, final Object data, final String errorMessage){
        if (ResponseCode.SUCCESS.equals(code)) {
            if (null == data) {
                message = new MyResponse(code);
            } else {
                message = new MyResponse(code, EMPTY_STRING,  data);
            }
        } else {
            String reponseText = StringUtils.isEmpty(errorMessage)? responseMessageMap.get(code).get(LANGUAGE_CHINESE) : errorMessage;
            if (null != replaceParameters && replaceParameters.size() > 0) {
                for (int i = 0; i < replaceParameters.size(); i++) {
                    reponseText = reponseText.replace("#p" + i + "#", replaceParameters.get(i));
                }
            }else{
                reponseText = reponseText.replace("#p0#", "");
            }
            if (null == data){
                message = new MyResponse(code, reponseText);
            }else{
                message = new MyResponse(code, reponseText, data);
            }
        }
        return message;
    }
}