package com.house365.ws.interfaces.rest;

import com.google.common.base.Strings;
import com.house365.beans.entity.YxMessageEntity;
import com.house365.rest.context.Parameter;
import com.house365.rest.exception.ServiceRunException;
import com.house365.rest.parameter.House365RestResponse;
import com.house365.ws.dao.mapper.YxMessageMapper;
import com.house365.ws.system.ReturnAppResult;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
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.Map;

/**
 * 同步yxMessage到全链条
 * Created by Administrator on 2018/11/19.
 */
@Service("saveMessage")
public class SaveMessageImpl implements ISaveMessage{

    private static final Logger logger = LoggerFactory.getLogger(SaveMessageImpl.class);

    @Autowired
    private YxMessageMapper mapper;


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

            String messageEntity = getMapValueByKey("messageEntity", map, "");
            if (!Strings.isNullOrEmpty(messageEntity)) {
                JSONObject message = JSONObject.fromObject(messageEntity);
                String eventType = getJsonValueByKey("eventType", message, "");
                String convType = getJsonValueByKey("convType", message, "");
                String to = getJsonValueByKey("to", message, "");
                String fromAccount = getJsonValueByKey("fromAccount", message, "");
                String fromClientType = getJsonValueByKey("fromClientType", message, "");
                String fromDeviceId = getJsonValueByKey("fromDeviceId", message, "");
                String fromNick = getJsonValueByKey("fromNick", message, "");
                String msgTimestamp = getJsonValueByKey("msgTimestamp", message, ""); //时间需要转换

                String msgType = getJsonValueByKey("msgType", message, "");
                String body = getJsonValueByKey("body", message, "");
                String attach = getJsonValueByKey("attach", message, "");
                String msgidClient = getJsonValueByKey("msgidClient", message, "");
                String msgidServer = getJsonValueByKey("msgidServer", message, ""); //要转换成long
                String resendFlag = getJsonValueByKey("resendFlag", message, ""); //转成int

                String customSafeFlag = getJsonValueByKey("customSafeFlag", message, "");//转成int
                String customApnsText = getJsonValueByKey("customApnsText", message, "");
                String tMembers = getJsonValueByKey("tMembers", message, "");
                String ext = getJsonValueByKey("ext", message, "");
                String antispam = getJsonValueByKey("antispam", message, "");
                String yidunRes = getJsonValueByKey("yidunRes", message, "");
                String relateId = getJsonValueByKey("id", message, "");
                //把时间转换为date类型
                Long timeLong = Long.parseLong(msgTimestamp);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//要转换的时间格式
                Date date;
                date = sdf.parse(sdf.format(timeLong));

                YxMessageEntity entity = new YxMessageEntity();
                entity.setEventType(eventType);
                entity.setConvType(convType);
                entity.setInfo(to);
                entity.setFromAccount(fromAccount);
                entity.setFromClientType(fromClientType);
                entity.setFromDeviceId(fromDeviceId);
                entity.setFromNick(fromNick);
                entity.setMsgTimestamp(Long.valueOf(msgTimestamp));
                entity.setMsgType(msgType);
                entity.setBody(body);
                entity.setAttach(attach);
                entity.setMsgidClient(msgidClient);
                if(StringUtils.isNotBlank(msgidServer)) {
                    entity.setMsgidServer(Long.valueOf(msgidServer));
                }else {
                    entity.setMsgidServer(0);
                }
                if(StringUtils.isNotBlank(resendFlag)) {
                    entity.setResendFlag(Integer.valueOf(resendFlag));
                }else {
                    entity.setResendFlag(0);
                }
                if(StringUtils.isNotBlank(customSafeFlag)) {
                    entity.setCustomSafeFlag(Integer.valueOf(customSafeFlag));
                }else {
                    entity.setCustomSafeFlag(0);
                }

                entity.setCustomApnsText(customApnsText);
                entity.settMembers(tMembers);
                entity.setExt(ext);
                entity.setAntispam(antispam);
                entity.setYidunRes(yidunRes);
                entity.setRelateId(Integer.valueOf(relateId));
                entity.setCreateTime(date);
                mapper.save(entity);
                response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
                response.setMsg("同步yxMessage成功");
            }else {
                response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
                response.setMsg("messageEntity参数不能为空");
            }

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("同步YX信息失败");
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg((ReturnAppResult.APP_FAIL.getResultMessage() + ":" + e.getMessage()));
        }
        return JSONObject.fromObject(response).toString();
    }

    private String getJsonValueByKey(String key, JSONObject obj, String defaultValue) {
        String value = "";
        if (obj.containsKey(key) && obj.get(key) != null && !Strings.isNullOrEmpty(String.valueOf(obj.get(key)))) {
            value = String.valueOf(obj.get(key));
        }

        if (Strings.isNullOrEmpty(value)) {
            value = 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;
    }

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

    @Override
    public void commit() {

    }
}
