package com.house365.ws.service.impl;

import com.google.common.base.Strings;
import com.house365.beans.entity.DepartmentEntity;
import com.house365.beans.entity.UserEntity;
import com.house365.commons.system.HttpClientUtil;
import com.house365.web.util.MemoryPropertyPlaceholderConfigurer;
import com.house365.ws.service.interfaces.IWechatService;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>Title: </p>
 * <p>Description: </p>
 * <p>Date: 2017/3/25</p>
 *
 * @author XN
 * @version 1.0
 */
@Service("wechatService")
public class WechatService implements IWechatService {

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

    private final String WE_CHAT_SERVICE = MemoryPropertyPlaceholderConfigurer.getContextProperty("WECHAT.SERVICE.URL");
    private final String WE_CHAT_COMPANY_ID = MemoryPropertyPlaceholderConfigurer.getContextProperty(
            "WECHAT.COMPANYID");
    private final String CROP_ID = MemoryPropertyPlaceholderConfigurer.getContextProperty("WECHAT.CROP_ID");
    private final String SECRET = MemoryPropertyPlaceholderConfigurer.getContextProperty("WECHAT.SECRET");
    private final String AGENTID = MemoryPropertyPlaceholderConfigurer.getContextProperty("WECHAT.AGENTID");
    private final String USER_SECRET = MemoryPropertyPlaceholderConfigurer.getContextProperty("WECHAT.USER.SECRET");
    private final String env = MemoryPropertyPlaceholderConfigurer.getContextProperty("system.env");


    @Override
    public void callWechatUserAPI(UserEntity entity, String url) {
        if (("production").equals(env)) {
            List<NameValuePair> params = warpParams(entity);
            params.add(new BasicNameValuePair("corpId", CROP_ID));
            params.add(new BasicNameValuePair("secret", USER_SECRET));
            params.add(new BasicNameValuePair("companyid", WE_CHAT_COMPANY_ID));
            String result = null;
            try {
                result = HttpClientUtil.doPost(WE_CHAT_SERVICE + url, params);
            } catch (IOException e) {
                LOGGER.error(e.getMessage());
            }
            LOGGER.debug("Wechat - callWechatUserAPI ,rul[{}], result[{}]", url, result);
        }
    }

    @Override
    public void deleteWechatUser(Integer id) {
        if (("production").equals(env)) {
            List<NameValuePair> params = new ArrayList<>();
            params.add(new BasicNameValuePair("corpId", CROP_ID));
            params.add(new BasicNameValuePair("secret", USER_SECRET));
            params.add(new BasicNameValuePair("userid", id.toString()));
            params.add(new BasicNameValuePair("companyid", WE_CHAT_COMPANY_ID));
            String result = null;
            try {
                result = HttpClientUtil.doPost(WE_CHAT_SERVICE + "/enterprise/user/delete", params);
            } catch (IOException e) {
                LOGGER.error(e.getMessage());
            }
            LOGGER.debug("Wechat - deleteWechatUser ,rul[{}], result[{}]", WE_CHAT_SERVICE + "/enterprise/user/delete",
                    result);
        }
    }

    @Override
    public void sendTextMessage(String touser, String content) {
        if ("test".equalsIgnoreCase(MemoryPropertyPlaceholderConfigurer.getContextProperty("system.env"))) {
            return;
        }
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("corpId", CROP_ID));
        params.add(new BasicNameValuePair("secret", SECRET));
        params.add(new BasicNameValuePair("agentid", AGENTID));
        params.add(new BasicNameValuePair("msgtype", "text"));
        params.add(new BasicNameValuePair("touser", touser));
        params.add(new BasicNameValuePair("content", content));

        String result = null;
        try {
            result = HttpClientUtil.doPost(WE_CHAT_SERVICE + "/message/send", params);
        } catch (IOException e) {
            LOGGER.error(e.getMessage());
        }

        LOGGER.info("Wechat - sendTextMessage ,[{}], result[{}]", WE_CHAT_SERVICE + "/message/send", result);
    }

    @Override
    public void sendCardTextMessage(String touser, String title, String description, String url, String btntxt) {
        //添加判断，touser 为空，则不调用发送信息接口
        if (StringUtils.isBlank(touser)) {
            return;
        }
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("corpId", CROP_ID));
        params.add(new BasicNameValuePair("secret", SECRET));
        params.add(new BasicNameValuePair("agentid", AGENTID));
        params.add(new BasicNameValuePair("msgtype", "textcard"));
        params.add(new BasicNameValuePair("touser", touser));
        params.add(new BasicNameValuePair("title", title));
        params.add(new BasicNameValuePair("description", description));
        params.add(new BasicNameValuePair("url", url));
        params.add(new BasicNameValuePair("btntxt", btntxt));
        LOGGER.info("------corpId------"+CROP_ID);
        LOGGER.info("------SECRET------"+SECRET);
        LOGGER.info("------AGENTID------"+AGENTID);
        LOGGER.info("------touser------"+touser);
        LOGGER.info("------url------"+url);
        String result = null;
        try {
            result = HttpClientUtil.doPost(WE_CHAT_SERVICE + "/message/send", params);
        } catch (IOException e) {
            LOGGER.error(e.getMessage());
        }

        LOGGER.info("Wechat - sendCardTextMessage ,[{}], result[{}]", WE_CHAT_SERVICE + "/message/send", result);
    }

    private List<NameValuePair> warpParams(UserEntity entity) {
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("userid", "" + entity.getId()));
        params.add(new BasicNameValuePair("name", entity.getRealName()));
        params.add(new BasicNameValuePair("department", entity.getDeptId().toString()));
        params.add(new BasicNameValuePair("position", entity.getPosition()));
        params.add(new BasicNameValuePair("mobile", entity.getMobile()));
        params.add(new BasicNameValuePair("enable", entity.getEnabled() ? "1" : "0"));

        if (!Strings.isNullOrEmpty(entity.getGender())) {
            params.add(new BasicNameValuePair("gender", entity.getGender()));
        }
        if (!Strings.isNullOrEmpty(entity.getGender())) {
            params.add(new BasicNameValuePair("email", entity.getEmail()));
        }
        if (!Strings.isNullOrEmpty(entity.getGender())) {
            params.add(new BasicNameValuePair("weixinid", entity.getWeiXinId()));
        }
        if (!Strings.isNullOrEmpty(entity.getGender())) {
            params.add(new BasicNameValuePair("avatar_mediaid", entity.getMediaId()));
        }
        if (!Strings.isNullOrEmpty(entity.getGender())) {
            params.add(new BasicNameValuePair("extattr", entity.getExtattr()));
        }
        return params;
    }


    @Override
    public void callWechatDepartmentAPI(DepartmentEntity department, String url) throws IOException {
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("corpId", CROP_ID));
        params.add(new BasicNameValuePair("secret", SECRET));
        params.add(new BasicNameValuePair("id", department.getId().toString()));
        params.add(new BasicNameValuePair("name", department.getName()));
        params.add(new BasicNameValuePair("parentid", department.getParentId() == null ? null : String.valueOf(
                department.getParentId())));
        params.add(new BasicNameValuePair("companyid", WE_CHAT_COMPANY_ID));
        params.add(new BasicNameValuePair("order", department.getOrderNum() == null ? "0" : String.valueOf(
                department.getOrderNum())));
        String result = "";
        try {
            result = HttpClientUtil.doPost(WE_CHAT_SERVICE + url, params);
        } catch (IOException e) {
            LOGGER.error(e.getMessage());
        }

        LOGGER.debug("Wechat - callWechatDepartmentAPI ,rul[{}], result[{}]", "/enterprise/department/create", result);
    }

    @Override
    public void deleteWechatDepartment(Integer id) {
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("corpId", CROP_ID));
        params.add(new BasicNameValuePair("secret", SECRET));
        params.add(new BasicNameValuePair("id", id.toString()));
        params.add(new BasicNameValuePair("companyid", WE_CHAT_COMPANY_ID));
        String result = "";
        try {
            result = HttpClientUtil.doPost(WE_CHAT_SERVICE + "/enterprise/department/delete", params);
        } catch (IOException e) {
            LOGGER.error(e.getMessage());
        }
        LOGGER.debug("Wechat - deleteWechatDepartment ,rul[{}], result[{}]", "/enterprise/department/delete", result);
    }
}
