package com.house365.ws.interfaces.rest;

import com.google.common.base.Strings;
import com.house365.beans.entity.DepartmentEntity;
import com.house365.beans.entity.MessageLogEntity;
import com.house365.beans.entity.UserEntity;
import com.house365.rest.context.Parameter;
import com.house365.rest.exception.ServiceRunException;
import com.house365.rest.parameter.House365RestResponse;
import com.house365.web.util.DateTimeUtils;
import com.house365.web.util.MemoryPropertyPlaceholderConfigurer;
import com.house365.ws.dao.mapper.DepartMapper;
import com.house365.ws.dao.mapper.MessageLogMapper;
import com.house365.ws.dao.mapper.UserMapper;
import com.house365.ws.service.impl.SendMsgImpl;
import com.house365.ws.system.ReturnAppResult;
import com.house365.ws.util.HttpUtil;
import net.sf.json.JSONObject;
import org.apache.commons.collections4.CollectionUtils;
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.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.house365.web.util.DateTimeUtils.DEFAULT_DATE_FORMAT_PATTERN_SHORT;

/**
 * 发送推广宝企业微信信息接口
 *
 * @author Created by 365 on 2020/11/24.
 */
@Service("sendWxMs")
public class SendWxImpl implements ISendWxInteface {

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

    private final String AGENTID = MemoryPropertyPlaceholderConfigurer.getContextProperty("WECHAT.AGENTID");

    @Autowired
    private DepartMapper departMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private MessageLogMapper logMapper;

    /**
     * 发送企业微信卡片通知接口
     *
     * @param parameter 参数
     * @return
     * @throws ServiceRunException
     */
    @Override
    public Object exectue(Parameter parameter) throws ServiceRunException {
        House365RestResponse<Map<String, Object>> response = new House365RestResponse<>();
        response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
        response.setMsg("推送成功");
        Map<String, Object> map = parameter.getArgs();
        String result = "";
        try {
            String data = getMapValueByKey("data", map, "");
            if (!Strings.isNullOrEmpty(data)) {
                JSONObject objectData = JSONObject.fromObject(data);
                String city = getJsonValueByKey("city", objectData, "");
                String position = getJsonValueByKey("position", objectData, "");
                String title = getJsonValueByKey("title", objectData, "");
                String message = getJsonValueByKey("message", objectData, "");

                if (StringUtils.isBlank(title) || StringUtils.isBlank(message) || StringUtils.isBlank(city)) {
                    response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
                    response.setMsg("请求参数不能为空");
                    return JSONObject.fromObject(response).toString();
                }
                Map<String, Object> searchMap = new HashMap<>(10);
                searchMap.put("descripition", city);
                List<DepartmentEntity> list = departMapper.queryByConditions(searchMap);
                if (CollectionUtils.isEmpty(list)) {
                    response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
                    response.setMsg("所传城市不存在");
                    return JSONObject.fromObject(response).toString();
                } else {
                    StringBuilder builder = new StringBuilder();
                    String urlPath = list.get(0).getUrlPath();
                    Map<String, Object> queryMap = new HashMap<>(10);
                    //1:安家顾问,3:新房房博士6二手房房博士  7 客服 10 租房房博士 20 平台人员
                    if (StringUtils.isNotBlank(position)) {
                        String identityTypes = "1,3,6,7,10,20";
                        if(!identityTypes.contains(position)){
                            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
                            response.setMsg("身份参数不对，无法匹配");
                            return JSONObject.fromObject(response).toString();
                        }
                        queryMap.put("identityType", position);
                    }
                    queryMap.put("deptUrlPath", urlPath);
                    List<UserEntity> userList = userMapper.queryByConditions(queryMap);
                    if (CollectionUtils.isEmpty(userList)) {
                        response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
                        response.setMsg("所传参数查询不到人员");
                        return JSONObject.fromObject(response).toString();
                    } else {
                        userList.forEach(u -> builder.append(u.getId()).append("|"));
                        String toUser = builder.toString();
                        String date = DateTimeUtils.getCurrentDateString(DEFAULT_DATE_FORMAT_PATTERN_SHORT);
                        String content = title + "\n" + date + "\n\n" + message;
                        String secret = MemoryPropertyPlaceholderConfigurer.getContextProperty("WECHAT.SECRET");
                        String token = HttpUtil.getToken(secret);
                        String url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?";
                        url += "access_token=" + token;
                        JSONObject jsonObject = new JSONObject();
                        JSONObject text = new JSONObject();
                        text.put("content", content);
                        jsonObject.put("agentid", AGENTID);
                        jsonObject.put("msgtype", "text");
                        jsonObject.put("touser", toUser);
                        jsonObject.put("text", text);
                        jsonObject.put("safe", "0");
                        jsonObject.put("enable_id_trans", "0");
                        jsonObject.put("enable_duplicate_check", "0");

                        result = HttpUtil.postWithJson(jsonObject, url, token);
                        MessageLogEntity logEntity = new MessageLogEntity();
                        Date now = new Date();
                        if (StringUtils.isNotBlank(result)) {
                            JSONObject json = JSONObject.fromObject(result);
                            Number code = (Number) json.get("errcode");
                            if (code.intValue() == 0) {
                                logEntity.setSendStatus(0);
                            } else {
                                logEntity.setSendStatus(1);
                            }
                        } else {
                            logEntity.setSendStatus(1);
                            logger.error("发送推广宝通知失败");
                            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
                            response.setMsg((ReturnAppResult.APP_FAIL.getResultMessage() + ":" + "发送推广宝通知失败"));
                        }
                        logEntity.setRelateId(0);
                        logEntity.setSender("");
                        logEntity.setReceiver(toUser);
                        logEntity.setMessageTime(now);
                        logEntity.setMobile("");
                        logEntity.setSendTime(now);
                        String mes = city + "," + position + "," + title + "," + message;
                        logEntity.setMessageInfo(mes);
                        logMapper.save(logEntity);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("发送推广宝通知失败", e);
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg((ReturnAppResult.APP_FAIL.getResultMessage() + ":" + e.getMessage()));
        }
        return JSONObject.fromObject(response).toString();
    }

    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;
    }

    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;
    }

    @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() {

    }
}
