/**
 * Description: 权限WS接口
 * Copyright:   Copyright (c)2016
 * Company:     江苏三六五网络股份有限公司
 *
 * @author: 江苏三六五网络股份有限公司
 * @version: 1.0
 * Create at:   2016-09-14 下午 17:27:18
 * <p>
 * Modification History:
 * Date         Author      Version     Description
 * ------------------------------------------------------------------
 * 2016-09-14   江苏三六五网络股份有限公司   1.0         Initial
 */
package com.house365.ws.interfaces.impl;

import com.house365.beans.entity.WeChatPermissionEntity;
import com.house365.beans.system.QueryParams;
import com.house365.commons.system.HttpClientUtil;
import com.house365.rest.context.Parameter;
import com.house365.rest.exception.ServiceRunException;
import com.house365.ws.beans.request.WeChatPermissionListRequest;
import com.house365.ws.beans.request.WeChatPermissionRequest;
import com.house365.ws.beans.response.WeChatPermissionListResponse;
import com.house365.ws.beans.response.WeChatPermissionResponse;
import com.house365.ws.interfaces.server.IWeChatPermission;
import com.house365.ws.service.interfaces.IWeChatPermissionService;
import com.house365.ws.system.ReturnResult;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

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

/**
 * 权限WS接口<br>
 *
 * @author 江苏三六五网络股份有限公司
 * @version 1.0, 2016-09-14
 * @see
 * @since 1.0
 */
@Service("weChatPermission")
public class WeChatPermissionImpl implements IWeChatPermission {
    /**
     * 日志记录器
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(WeChatPermissionImpl.class);
    /**
     * 权限服务对象
     */
    @Autowired
    IWeChatPermissionService<WeChatPermissionEntity> weChatPermissionService;
    @Value("${WECHAT.SERVICE.URL}")
    private String WE_CHAT_SERVICE;
    @Value("${WECHAT.CROP_ID}")
    private String CORP_ID;
    @Value("${WECHAT.SECRET}")
    private String SECRET;
    @Value("${WECHAT.AGENTID}")
    private String AGENT_ID;


    /**
     * 权限列表查询
     *
     * @param request 权限列表查询请求
     * @return 权限列表查询响应
     */
    @Override
    public WeChatPermissionListResponse getPermissionList(WeChatPermissionListRequest request) {
        WeChatPermissionListResponse response = new WeChatPermissionListResponse();
        try {
            QueryParams<WeChatPermissionEntity> queryParams = new QueryParams<>(request.getSearchParams());
            queryParams.setPaging(request.getPaging());
            queryParams.setOrderColumn(request.getOrderColumn());
            queryParams.setOrderMode(request.getOrderMode());
            List<WeChatPermissionEntity> permissions = weChatPermissionService.queryByPage(queryParams);
            response.setPaging(queryParams.getPaging());
            response.setObjectList(permissions);
            response.setResultCode(ReturnResult.SUCCESS.getResultCode());
            response.setResultMessage(ReturnResult.SUCCESS.getResultMessage());
        } catch (Exception ex) {
            LOGGER.error(ex.getMessage(), ex);
            response.setResultCode(ReturnResult.FAIL.getResultCode());
            response.setResultMessage(ex.getMessage());
        }
        return response;
    }

    /**
     * 保存权限
     *
     * @param request 权限请求
     * @return 保存权限响应
     */
    @Override
    public WeChatPermissionResponse addPermission(WeChatPermissionRequest request) {
        WeChatPermissionResponse response = new WeChatPermissionResponse();
        try {
            WeChatPermissionEntity entity = request.getEntity();
            weChatPermissionService.save(entity);
            response.setEntity(entity);

            changePermission();
            response.setResultCode(ReturnResult.SUCCESS.getResultCode());
            response.setResultMessage(ReturnResult.SUCCESS.getResultMessage());
        } catch (Exception ex) {
            LOGGER.error(ex.getMessage(), ex);
            response.setResultCode(ReturnResult.FAIL.getResultCode());
            response.setResultMessage(ex.getMessage());
        }
        return response;
    }

    /**
     * 删除权限通过唯一标识
     *
     * @param id 唯一标识
     * @return 删除权限响应
     */
    @Override
    public WeChatPermissionResponse deletePermissionById(Integer id) {
        WeChatPermissionResponse response = new WeChatPermissionResponse();
        try {
            weChatPermissionService.delete(id);

            changePermission();
            response.setResultCode(ReturnResult.SUCCESS.getResultCode());
            response.setResultMessage(ReturnResult.SUCCESS.getResultMessage());
        } catch (Exception ex) {
            LOGGER.error(ex.getMessage(), ex);
            response.setResultCode(ReturnResult.FAIL.getResultCode());
            response.setResultMessage(ex.getMessage());
        }
        return response;
    }

    /**
     * 修改权限
     *
     * @param request 修改权限请求
     * @return 修改权限响应
     */
    @Override
    public WeChatPermissionResponse updatePermission(WeChatPermissionRequest request) {
        WeChatPermissionResponse response = new WeChatPermissionResponse();
        try {
            weChatPermissionService.update(request.getEntity());

            changePermission();
            response.setResultCode(ReturnResult.SUCCESS.getResultCode());
            response.setResultMessage(ReturnResult.SUCCESS.getResultMessage());
        } catch (Exception ex) {
            LOGGER.error(ex.getMessage(), ex);
            response.setResultCode(ReturnResult.FAIL.getResultCode());
            response.setResultMessage(ex.getMessage());
        }
        return response;
    }

    /**
     * 通过ID获取权限
     *
     * @param id 唯一标识
     * @return 通过ID获取权限响应
     */
    @Override
    public WeChatPermissionResponse getPermissionById(Integer id) {
        WeChatPermissionResponse response = new WeChatPermissionResponse();
        try {
            WeChatPermissionEntity entity = weChatPermissionService.getById(id);
            response.setEntity(entity);

            response.setResultCode(ReturnResult.SUCCESS.getResultCode());
            response.setResultMessage(ReturnResult.SUCCESS.getResultMessage());
        } catch (Exception ex) {
            LOGGER.error(ex.getMessage(), ex);
            response.setResultCode(ReturnResult.FAIL.getResultCode());
            response.setResultMessage(ex.getMessage());
        }
        return response;
    }

    /**
     * 创建微信应用号菜单
     */
    String createMenu(String button) throws IOException {
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("corpId", CORP_ID));
        params.add(new BasicNameValuePair("secret", SECRET));
        params.add(new BasicNameValuePair("agentid", AGENT_ID));
        params.add(new BasicNameValuePair("button", button));
        return HttpClientUtil.doPost(WE_CHAT_SERVICE + "/enterprise/menu/create", params);
    }

    /**
     * 清除微信应用号菜单
     */
    String deleteMenu() throws IOException {
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("corpId", CORP_ID));
        params.add(new BasicNameValuePair("secret", SECRET));
        params.add(new BasicNameValuePair("agentid", AGENT_ID));
        return HttpClientUtil.doPost(WE_CHAT_SERVICE + "/enterprise/menu/delete", params);
    }

    @Override
    public void changePermission() throws IOException {
        List<WeChatPermissionEntity> permissions = weChatPermissionService
                .getPermissionsByParentId(0);
        JSONObject buttonObject = new JSONObject();
        JSONArray buttonArray = getWeChatPermission(permissions);
        buttonObject.put("button", buttonArray);
//        String button = "{\"button\":[{\"type\":\"click\",\"name\":\"今日歌曲\",\"key\":\"V1001_TODAY_MUSIC\"}," +
//                "{\"name\":\"菜单\",\"sub_button\":[{\"type\":\"view\",\"name\":\"搜索\",\"url\":\"http://www.soso.com/\"}," +
//                "{\"type\":\"click\",\"name\":\"赞一下我们\",\"key\":\"V1001_GOOD\"}]}]}";
        deleteMenu();
        createMenu(buttonObject.toString());
    }

    private JSONArray getWeChatPermission(List<WeChatPermissionEntity> permissions) {
        JSONArray buttonArray = new JSONArray();
        for (WeChatPermissionEntity permission : permissions) {
            JSONObject button = new JSONObject();
            button.put("name", permission.getName());
            List<WeChatPermissionEntity> childrenPermissions = weChatPermissionService
                    .getPermissionsByParentId(permission.getId());
            if (childrenPermissions != null && childrenPermissions.size() != 0) {
                JSONArray subButtonArray = new JSONArray();
                for (WeChatPermissionEntity childPermission : childrenPermissions) {
                    JSONObject childButton = new JSONObject();
                    getPermissionType(childButton, childPermission.getHierarchy(), childPermission.getResource(), childPermission.getCode());
                    childButton.put("name", childPermission.getName());
                    subButtonArray.add(childButton);
                }
                button.put("sub_button", subButtonArray);
            } else {
                getPermissionType(button, permission.getHierarchy(), permission.getResource(), permission.getCode());
            }
            buttonArray.add(button);
        }
        return buttonArray;
    }

    private void getPermissionType(JSONObject object, Integer type, String source, String key) {
        switch (type) {
            case 0:
                object.put("type", "click");
                object.put("key", key);
                break;
            case 1:
                object.put("type", "view");
                object.put("url", source);
                break;
            case 2:
                break;
            default:
                break;
        }
    }

    /**
     * 以下均为自动生成
     */

    @Override
    public Object exectue(Parameter parameter) throws ServiceRunException {
        // TODO Auto-generated method stub
        return null;
    }

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