package com.teemlink.kujiale.util;

import cn.myapps.common.util.FileWriteUtil;
import cn.myapps.common.util.PropertyUtil;
import cn.myapps.common.util.StringUtil;
import cn.myapps.util.ftp.FTPTools;
import cn.myapps.util.http.RequestFileUtil;
import cn.myapps.util.http.RequestUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.digest.DigestUtils;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;

/**
 * 酷家乐工具类
 */
public class KujialeUtil {

    public KujialeUtil(){
        PropertyUtil.reload("kujiale");
        openapi_url = PropertyUtil.get("openapi_url");
        design_url = PropertyUtil.get("design_url");
        appkey = PropertyUtil.get("appkey");
        appsecret = PropertyUtil.get("appsecret");

        PropertyUtil.reload("ftp");
        user = PropertyUtil.get("ftp.user");
        password = PropertyUtil.get("ftp.password");
        server = PropertyUtil.get("ftp.server");
        port = PropertyUtil.get("ftp.port") != null? Integer.valueOf(PropertyUtil.get("ftp.port")):21;
    }

    private String openapi_url;

    private String design_url;

    private String appkey;

    private String appsecret;

    private int port;

    private String user;

    private String password;

    private String server;


    /**
     * 获取token
     * @param appuid
     *      影子用户id
     * @return
     * @throws Exception
     */
    public String getToken(String appuid) throws Exception{
        String timestamp = new Date().getTime()+"";
        String sign = getMD5(appsecret+appkey+appuid+timestamp);
        return getToken(appuid, timestamp, sign);
    }

    /**
     * 获取token
     * @param appuid
     *      影子用户id
     * @param timestamp
     *      时间戳
     * @param sign
     *      md加密信息
     * @return
     * @throws Exception
     */
    public String getToken(String appuid, String timestamp, String sign) throws Exception{
        String url = openapi_url + "/v2/sso/token?appuid="+appuid+"&sign="+sign+"&dest=4&timestamp="+timestamp+"&appkey="+appkey;
        JSONObject result = RequestUtils.post(url, null);
        if("0".equals(result.getString("c"))){
            return result.getString("d");
        } else {
            String msg = handleErrorMsg(result);
            throw new Exception(msg);
        }

    }

    /**
     * 获取设计url
     * @param appuid
     *      影子用户id
     * @param email
     *      邮箱
     * @return
     */
    public String getDesignUrl(String name, String email, String appuid) throws Exception{
        return getDesignUrl(name,null, email, appuid);
    }

    /**
     * 获取设计url
     * @param appuid
     *      影子用户id
     * @param designId
     *      设计方案id
     * @param email
     *      邮箱
     * @return
     */
    public String getDesignUrl(String name, String designId, String email, String appuid) throws Exception{
        String timestamp = new Date().getTime()+"";
        String sign = getMD5(appsecret+appkey+appuid+timestamp);
        //注册
        boolean isRegister = isRegister(appuid, timestamp, sign);
        if(!isRegister){
            register(name, email, appuid, timestamp, sign);
        }
        //获取token
        String token = getToken(appuid, timestamp, sign);
        String url = design_url + "/v/auth?accesstoken="+token;
        if(StringUtil.isBlank(designId)){
            url+= "&dest=4";
        } else {
            url+= "&dest=1&designid="+designId;
        }
        return url;
    }

    /**
     * 注册
     * @param appuid
     *      影子用户id
     * @param email
     *      邮箱
     * @return
     */
    public void register(String name, String email, String appuid) throws Exception{
        String timestamp = new Date().getTime()+"";
        String sign = getMD5(appsecret+appkey+appuid+timestamp);
        register(name, email, appuid, timestamp, sign);
    }

    /**
     * 注册
     * @param appuid
     *      影子用户id
     * @param email
     *      邮箱
     * @param timestamp
     *      时间戳
     * @param sign
     *      md加密信息
     * @throws Exception
     */
    public void register(String name, String email, String appuid, String timestamp, String sign) throws Exception{
        String url = openapi_url + "/v2/register?appuid="+appuid+"&sign="+sign+"&timestamp="+timestamp+"&appkey="+appkey;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name", name);
        jsonObject.put("email", email);
        jsonObject.put("avatar", "");
        jsonObject.put("type", 0);
        jsonObject.put("maxChildrenCount", 5);
        jsonObject.put("defaultPassword", "123456");
        jsonObject.put("creator", "");
        JSONObject result = RequestUtils.post(url, jsonObject.toString());
        if(!"0".equals(result.getString("c"))){
            String msg = handleErrorMsg(result);
            throw new Exception(msg);
        }
    }

    /**
     * 判断是否已经注册
     * @param appuid
     *      影子用户id
     * @return
     */
    public boolean isRegister(String appuid) throws Exception{
        String timestamp = new Date().getTime()+"";
        String sign = getMD5(appsecret+appkey+appuid+timestamp);
        return isRegister(appuid, timestamp, sign);
    }

    /**
     * 判断是否已经注册
     * @param appuid
     *      影子用户id
     * @param timestamp
     *      时间戳
     * @param sign
     *      md加密信息
     * @throws Exception
     */
    public boolean isRegister(String appuid, String timestamp, String sign) throws Exception{
        String url = openapi_url + "/v2/user/info?appuid="+appuid+"&sign="+sign+"&timestamp="+timestamp+"&appkey="+appkey;
        JSONObject result = RequestUtils.get(url);
        if("0".equals(result.getString("c"))){
            return true;
        } else {
            return false;
        }
    }

    /**
     * 获取设计方案
     * @param appuid
     *      影子用户id
     * @param email
     *      邮箱
     * @throws Exception
     */
    public JSONObject getUserDesignList(String name, String email, String appuid) throws Exception{
        String timestamp = new Date().getTime()+"";
        String sign = getMD5(appsecret+appkey+appuid+timestamp);

        //注册
        boolean isRegister = isRegister(appuid, timestamp, sign);
        if(!isRegister){
            register(name, email, appuid, timestamp, sign);
        }

        String url = openapi_url + "/v2/design/list?appuid="+appuid+"&sign="+sign+"&timestamp="+timestamp+"&appkey="+appkey+"&num=50&start=0";
        JSONObject result = RequestUtils.get(url);
        if("0".equals(result.getString("c"))){
            return result.getJSONObject("d");
        } else {
            String msg = handleErrorMsg(result);
            throw new Exception(msg);
        }
    }

    /**
     * 获取方案的渲染图
     * @param designId
     *      设计方案id
     * @throws Exception
     */
    public JSONObject getUserDesignRenderpicList(String designId) throws Exception{
        String timestamp = new Date().getTime()+"";
        String sign = getMD5(appsecret+appkey+timestamp);
        String url = openapi_url + "/v2/renderpic/list?sign="+sign+"&timestamp="+timestamp+"&appkey="+appkey+"&num=50&start=0&design_id="+designId;
        JSONObject result = RequestUtils.get(url);
        if("0".equals(result.getString("c"))){
            return result.getJSONObject("d");
        } else {
            String msg = handleErrorMsg(result);
            throw new Exception(msg);
        }
    }

    /**
     * 获取审核方案列表
     * @param designId
     *      设计方案id
     * @throws Exception
     */
    public JSONObject getUserDesignAuditPlanList(String designId) throws Exception{
        String timestamp = new Date().getTime()+"";
        String sign = getMD5(appsecret+appkey+timestamp);
        String url = openapi_url + "/v2/cus/audit/design/"+designId+"?sign="+sign+"&timestamp="+timestamp+"&appkey="+appkey+"&num=50&start=0&isOrderV2=true";
        JSONObject result = RequestUtils.get(url);
        if("0".equals(result.getString("c"))){
            return result.getJSONObject("d");
        } else {
            String msg = handleErrorMsg(result);
            throw new Exception(msg);
        }
    }

    /**
     * 获取审核单列表
     * @param appuid
     *      影子用户id
     * @param type
     *      查询类型，type=0为。当前appuid已经认领的审核单列表，type=1为所有已被认领的审核单列表，type=2为所有未被认领的审核单列表
     * @param email
     *      邮箱
     * @return
     * @throws Exception
     */
    public JSONObject getUserAuditList(String name, int type, String email, String appuid) throws Exception{
        String timestamp = new Date().getTime()+"";
        String sign = getMD5(appsecret+appkey+appuid+timestamp);

        //注册
        boolean isRegister = isRegister(appuid, timestamp, sign);
        if(!isRegister){
            register(name, email, appuid, timestamp, sign);
        }

        String url = openapi_url + "/v2/customization-order/audit/list?type="+type+"&appuid="+appuid+"&sign="+sign+"&timestamp="+timestamp+"&appkey="+appkey+"&num=50&start=0";
        JSONObject result = RequestUtils.get(url);
        if("0".equals(result.getString("c"))){
            return result.getJSONObject("d");
        } else {
            String msg = handleErrorMsg(result);
            throw new Exception(msg);
        }
    }

    /**
     * 获取审核单列表
     * @param appuid
     *      影子用户id
     * @param email
     *      邮箱
     * @return
     * @throws Exception
     */
    public JSONObject getUserAuditList(String name, String email, String appuid) throws Exception{
        return getUserAuditList(name, 0, email, appuid);
    }

    /**
     * 获取用户的全屋漫游图
     * @param appuid
     *      影子用户id
     * @return
     * @throws Exception
     */
    public JSONObject getUserRenderpic(String appuid) throws Exception{
        String timestamp = new Date().getTime()+"";
        String sign = getMD5(appsecret+appkey+appuid+timestamp);
        String url = openapi_url + "/v2/renderpic/pano?appuid="+appuid+"&sign="+sign+"&timestamp="+timestamp+"&appkey="+appkey+"&num=50&start=0";
        JSONObject result = RequestUtils.get(url);
        if("0".equals(result.getString("c"))){
            return result.getJSONObject("d");
        } else {
            String msg = handleErrorMsg(result);
            throw new Exception(msg);
        }
    }

    /**
     * 获取指定审核方案路径
     * @param appuid
     *      影子用户
     * @param designid
     *      方案id。
     * @param obsorderdesignid
     *      审核方案id
     * @param type
     *      工具线类型。0橱柜1衣柜2门窗
     * @param levelid
     *      楼层标识id，用于进入审核方案的入参id。
     * @param email
     *      邮箱
     * @return
     * @throws Exception
     */
    public String getAuditDesignUrl(String name, String designid, int designtype, int customtype, String obsorderdesignid, String email, String appuid) throws Exception{
        String timestamp = new Date().getTime()+"";
        String sign = getMD5(appsecret+appkey+appuid+timestamp);
        //注册
        boolean isRegister = isRegister(appuid, timestamp, sign);
        if(!isRegister){
            register(name, email, appuid, timestamp, sign);
        }
        //获取token
        String token = getToken(appuid, timestamp, sign);
        String url = design_url + "/v/auth?accesstoken="+token+"&dest=11&designid="+designid+"&obsorderdesignid="+obsorderdesignid+"&customtype="+customtype+"&designtype="+designtype;
        return url;
    }

    /**
     * 执行订单自定义事件
     * @param appuid
     *      影子用户id
     * @param templatekey
     *      订单模板key
     * @param orderreadableid
     *      订单系统可读编号
     * @param eventkey
     *      事件key
     * @param body
     *      请求包体
     * @param email
     *      邮箱
     * @return
     * @throws Exception
     */
    public boolean executeUserEvent(String name, String templatekey, String orderreadableid, String eventkey, String body, String email, String appuid) throws Exception{
        String timestamp = new Date().getTime()+"";
        String sign = getMD5(appsecret+appkey+appuid+timestamp);

        //注册
        boolean isRegister = isRegister(appuid, timestamp, sign);
        if(!isRegister){
            register(name, email, appuid, timestamp, sign);
        }

        String url = openapi_url + "/v2/cus/order/event/execute?appuid="+appuid+"&templatekey="+templatekey+"&orderreadableid="+orderreadableid+"&eventkey="+eventkey+"&sign="+sign+"&timestamp="+timestamp+"&appkey="+appkey;
        JSONObject result = null;
        if(body == null){
            result = RequestUtils.post(url, null);
        } else {
            result = RequestUtils.post(url, body, "text/plain;charset=utf-8");
        }
        if("0".equals(result.getString("c"))){
            return result.getBoolean("d");
        } else {
            String msg = handleErrorMsg(result);
            throw new Exception(msg);
        }
    }

    /**
     * 获取存档列表（施工图）
     * @param designid
     *      方案id
     * @return
     */
    public JSONObject getArchiveList(String designid) throws Exception{
        String timestamp = new Date().getTime()+"";
        String sign = getMD5(appsecret+appkey+timestamp);
        String url = openapi_url + "/v2/archive/list?design_id="+designid+"&sign="+sign+"&timestamp="+timestamp+"&appkey="+appkey;
        JSONObject result = RequestUtils.get(url);
        if("0".equals(result.getString("c"))){
            return result.getJSONObject("d");
        } else {
            String msg = handleErrorMsg(result);
            throw new Exception(msg);
        }
    }

    /**
     * 获取CAD户型图/施工图
     * @param designid
     *      方案id
     * @return
     * @throws Exception
     */
    public JSONObject getCADBluePrint(String designid) throws Exception{
        String timestamp = new Date().getTime()+"";
        String sign = getMD5(appsecret+appkey+timestamp);
        String url = openapi_url + "/v2/design/"+designid+"/cd?sign="+sign+"&timestamp="+timestamp+"&appkey="+appkey;
        JSONObject result = RequestUtils.get(url);
        if("0".equals(result.getString("c"))){
            return result.getJSONObject("d");
        } else {
            String msg = handleErrorMsg(result);
            throw new Exception(msg);
        }
    }

    /**
     * 生成CAD户型图/施工图
     * @param designid
     *      方案id
     * @return
     * @throws Exception
     */
    public JSONObject createCADBluePrint(String designid, String body) throws Exception{
        String timestamp = new Date().getTime()+"";
        String sign = getMD5(appsecret+appkey+timestamp);
        String url = openapi_url + "/v2/design/"+designid+"/cd?sign="+sign+"&timestamp="+timestamp+"&appkey="+appkey;
        JSONObject result = RequestUtils.post(url, body);
        if("0".equals(result.getString("c"))){
            return result.getJSONObject("d");
        } else {
            String msg = handleErrorMsg(result);
            throw new Exception(msg);
        }
    }

    /**
     * 初始化清单
     * @param designid
     *      方案id
     * @return
     * @throws Exception
     */
    public JSONObject initDetailList(String designid) throws Exception{
        String timestamp = new Date().getTime()+"";
        String sign = getMD5(appsecret+appkey+timestamp);
        String url = openapi_url + "/v2/listing/init?design_id="+designid+"&sign="+sign+"&timestamp="+timestamp+"&appkey="+appkey;
        JSONObject result = RequestUtils.get(url);
        if("0".equals(result.getString("c"))){
            return result.getJSONObject("d");
        } else {
            String msg = handleErrorMsg(result);
            throw new Exception(msg);
        }
    }

    /**
     * 创建清单数据获取任务
     * @param appuid
     *      影子用户id
     * @param email
     *      邮箱
     * @return
     * @throws Exception
     */
    public String createDetailListTask(String name, String body, String email, String appuid) throws Exception{
        String timestamp = new Date().getTime()+"";
        String sign = getMD5(appsecret+appkey+appuid+timestamp);

        //注册
        boolean isRegister = isRegister(appuid, timestamp, sign);
        if(!isRegister){
            register(name, email, appuid, timestamp, sign);
        }

        String url = openapi_url + "/v2/cus/task/listing?appuid="+appuid+"&sign="+sign+"&timestamp="+timestamp+"&appkey="+appkey;
        JSONObject result = RequestUtils.get(url);
        if("0".equals(result.getString("c"))){
            JSONObject json = result.getJSONObject("d");
            return result.getString("d");
        } else {
            String msg = handleErrorMsg(result);
            throw new Exception(msg);
        }
    }

    /**
     * 创建方案数据获取任务
     * @param appuid
     *      影子用户id
     * @param email
     *      邮箱
     * @return
     * @throws Exception
     */
    public String createProjectListTask(String name, String body, String email, String appuid) throws Exception{
        String timestamp = new Date().getTime()+"";
        String sign = getMD5(appsecret+appkey+appuid+timestamp);

        //注册
        boolean isRegister = isRegister(appuid, timestamp, sign);
        if(!isRegister){
            register(name, email, appuid, timestamp, sign);
        }

        String url = openapi_url + "/v2/cus/task/design?appuid="+appuid+"&sign="+sign+"&timestamp="+timestamp+"&appkey="+appkey;
        JSONObject result = RequestUtils.post(url, body);
        if("0".equals(result.getString("c"))){
            return result.getString("d");
        } else {
            String msg = handleErrorMsg(result);
            throw new Exception(msg);
        }
    }

    /**
     * 获取任务状态
     * @param task_id
     *      任务id
     * @return
     * @throws Exception
     */
    public int getTaskStatus(String task_id) throws Exception{
        String timestamp = new Date().getTime()+"";
        String sign = getMD5(appsecret+appkey+timestamp);
        String url = openapi_url + "/v2/cus/task/status?task_id="+task_id+"&sign="+sign+"&timestamp="+timestamp+"&appkey="+appkey;
        JSONObject result = RequestUtils.get(url);
        if("0".equals(result.getString("c"))){
            return result.getIntValue("d");
        } else {
            String msg = handleErrorMsg(result);
            throw new Exception(msg);
        }
    }

    /**
     * 获取数据资源URL
     * @param task_id
     *      任务id
     * @return
     * @throws Exception
     */
    public String getTaskResult(String task_id) throws Exception{
        String timestamp = new Date().getTime()+"";
        String sign = getMD5(appsecret+appkey+timestamp);
        String url = openapi_url + "/v2/cus/task/result?task_id="+task_id+"&sign="+sign+"&timestamp="+timestamp+"&appkey="+appkey;
        JSONObject result = RequestUtils.get(url);
        if("0".equals(result.getString("c"))){
            return result.getString("d");
        } else {
            String msg = handleErrorMsg(result);
            throw new Exception(msg);
        }
    }

    /**
     * 获取方案数据
     * @param appuid
     *      影子用户id
     * @param email
     *      邮箱
     * @throws Exception
     */
    public String getProjectListTaskResult(String name, String designId, int type, int levelIndex, String auditDesignId, String orderDesignType, String quotationModeName, int wait, String fileName, String ftpFolderPath, String email, String appuid) throws Exception{
        JSONObject json = new JSONObject();
        json.put("designId", designId);
        json.put("type", type);
        json.put("isNewType", true);
        json.put("levelIndex", levelIndex);
        json.put("auditDesignId", auditDesignId);
        json.put("orderDesignType", orderDesignType);
        json.put("quotationModeName", quotationModeName);
        //创建方案数据获取任务
        String taskId = createProjectListTask(name, json.toString(), email, appuid);
        //记录次数
        int count = 0;
        //获取任务状态
        while(true){
            if(count > 100){
                break;
            }
            int status = getTaskStatus(taskId);
            if(status == 2){
                String jsonUrl = getTaskResult(taskId);
                if(StringUtil.isBlank(fileName)){
                    fileName = jsonUrl.substring(jsonUrl.lastIndexOf("/")+1);
                }
                String folderPath = File.separator+"uploads"+File.separator+"kujiale"+File.separator;
                String savePath = PropertyUtil.getPath()+folderPath+fileName;
                File folder = new File(PropertyUtil.getPath()+folderPath);
                if(!folder.exists()){
                    folder.mkdirs();
                }
                boolean result = RequestFileUtil.downLoadFromUrl(jsonUrl, savePath);
                if(result){
                    FTPTools.uploadFileForWindows(server, port, user, password, ftpFolderPath, savePath);

                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    JSONArray jsonArray = new JSONArray();
                    JSONObject fileItem = new JSONObject();
                    fileItem.put("name", fileName);
                    File file = new File(savePath);
                    fileItem.put("path", folderPath+fileName);
                    fileItem.put("size", file.length()+"");
                    fileItem.put("userName", "system");
                    fileItem.put("time", format.format(new Date()));
                    jsonArray.add(fileItem);
                    return jsonArray.toString();
                }
            }
            //等待时间
            Thread.sleep(wait);
            count++;
        }
        return "";
    }

    /**
     * 创建订单
     * @param appuid
     *      影子用户id
     * @param email
     *      邮箱
     * @return
     * @throws Exception
     */
    public String createCusOrder(String name, String body, String email, String appuid) throws Exception{
        String timestamp = new Date().getTime()+"";
        String sign = getMD5(appsecret+appkey+appuid+timestamp);

        //注册
        boolean isRegister = isRegister(appuid, timestamp, sign);
        if(!isRegister){
            register(name, email, appuid, timestamp, sign);
        }

        String url = openapi_url + "/v2/cus/order/create?appuid="+appuid+"&sign="+sign+"&timestamp="+timestamp+"&appkey="+appkey;
        JSONObject result = RequestUtils.post(url, body);
        if("0".equals(result.getString("c"))){
            return result.getString("d");
        } else {
            String msg = handleErrorMsg(result);
            throw new Exception(msg);
        }
    }

    /**
     * 查询订单详情
     * @param appuid
     *      影子用户id
     * @param orderreadableid
     *      订单系统可读编号
     * @param email
     *      邮箱
     * @return
     * @throws Exception
     */
    public String getOrderDetail(String name, String orderreadableid, String email, String appuid) throws Exception{
        String timestamp = new Date().getTime()+"";
        String sign = getMD5(appsecret+appkey+appuid+timestamp);

        //注册
        boolean isRegister = isRegister(appuid, timestamp, sign);
        if(!isRegister){
            register(name, email, appuid, timestamp, sign);
        }

        String url = openapi_url + "/v2/cus/order/detail?appuid="+appuid+"&orderreadableid="+orderreadableid+"&sign="+sign+"&timestamp="+timestamp+"&appkey="+appkey;
        JSONObject result = RequestUtils.get(url);
        if("0".equals(result.getString("c"))){
            return result.getString("d");
        } else {
            String msg = handleErrorMsg(result);
            throw new Exception(msg);
        }
    }

    /**
     * 获取审核附件信息
     * @param appuid
     *      影子用户id
     * @param orderreadableid
     *      订单系统可读编号
     * @param userName
     *      当前登录用户名称
     * @param email
     *      邮箱
     * @return
     * @throws Exception
     */
    public String getFileItem(String name, String orderreadableid, String userName, String email, String appuid) throws Exception{
        String orderDetail = getOrderDetail(name, orderreadableid, email, appuid);
        JSONObject orderDetailJson = JSONObject.parseObject(orderDetail);
        JSONArray attachmentList = orderDetailJson.getJSONArray("attachmentList");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 加上以当前年份命名的文件夹
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        String folderPath = File.separator+"uploads"+File.separator+"item"+File.separator+year+File.separator;

        if(attachmentList != null && attachmentList.size() > 0){
            JSONArray jsonArray = new JSONArray();
            for(Iterator iterator = attachmentList.iterator();iterator.hasNext();){
                JSONObject json = (JSONObject)iterator.next();
                String downloadUrl = json.getString("downloadUrl");
                String fileName = json.getString("fileName");
                long expire = json.getLong("expire");
                boolean flag = RequestFileUtil.downLoadFromUrl(downloadUrl, PropertyUtil.getPath()+folderPath+fileName);
                //生成文件任务
                FileWriteUtil.writeKmConvertTask(PropertyUtil.getPath(),fileName.substring(0,fileName.lastIndexOf(".")),PropertyUtil.getPath()+folderPath+fileName);
                if(flag){
                    JSONObject fileItem = new JSONObject();
                    fileItem.put("name", fileName);
                    File file = new File(PropertyUtil.getPath()+folderPath+fileName);
                    fileItem.put("path", folderPath+fileName);
                    fileItem.put("size", file.length()+"");
                    fileItem.put("userName", userName);
                    fileItem.put("time", format.format(new Date(expire)));
                    jsonArray.add(fileItem);
                }
            }
            return jsonArray.toString();
        }
        return "";
    }

    /**
     * 关联客户订单与设计方案
     * @param appuid
     *      影子用户id
     * @param orderreadableid
     *      订单系统可读编号
     * @param designidlist
     *      方案id列表，使用英文标点逗号作为分隔符，优先选择该字段，如: xx,xx\
     * @param email
     *      邮箱
     * @return
     * @throws Exception
     */
    public boolean associateCusOrderAndDesign(String name, String orderreadableid, String designidlist, String email, String appuid) throws Exception{
        String timestamp = new Date().getTime()+"";
        String sign = getMD5(appsecret+appkey+appuid+timestamp);

        //注册
        boolean isRegister = isRegister(appuid, timestamp, sign);
        if(!isRegister){
            register(name, email, appuid, timestamp, sign);
        }

        String url = openapi_url + "/v2/cus/order/customer/associate/design?appuid="+appuid+"&orderreadableid="+orderreadableid+"&designidlist="+designidlist+"&sign="+sign+"&timestamp="+timestamp+"&appkey="+appkey;
        JSONObject result = RequestUtils.post(url, null);
        if("0".equals(result.getString("c"))){
            return result.getBoolean("d");
        } else {
            String msg = handleErrorMsg(result);
            throw new Exception(msg);
        }
    }

    /**
     * 取消关联客户订单与设计方案
     * @param appuid
     *      影子用户id
     * @param orderreadableid
     *      订单系统可读编号
     * @param designidlist
     *      方案id列表，使用英文标点逗号作为分隔符，优先选择该字段，如: xx,xx\
     * @param email
     *      邮箱
     * @return
     * @throws Exception
     */
    public boolean cancelAssociateCusOrderAndDesign(String name, String orderreadableid, String designidlist, String email, String appuid) throws Exception{
        String timestamp = new Date().getTime()+"";
        String sign = getMD5(appsecret+appkey+appuid+timestamp);

        //注册
        boolean isRegister = isRegister(appuid, timestamp, sign);
        if(!isRegister){
            register(name, email, appuid, timestamp, sign);
        }

        String url = openapi_url + "/v2/cus/order/customer/disassociate/design?appuid="+appuid+"&orderreadableid="+orderreadableid+"&designidlist="+designidlist+"&sign="+sign+"&timestamp="+timestamp+"&appkey="+appkey;
        JSONObject result = RequestUtils.post(url, null);
        if("0".equals(result.getString("c"))){
            return result.getBoolean("d");
        } else {
            String msg = handleErrorMsg(result);
            throw new Exception(msg);
        }
    }

    /**
     * 解除关联客户订单与设计方案
     * @param appuid
     *      影子用户id
     * @param orderreadableid
     *      订单系统可读编号
     * @param designidlist
     *      方案id列表，使用英文标点逗号作为分隔符，优先选择该字段，如: xx,xx
     * @param email
     *      邮箱
     * @return
     * @throws Exception
     */
    public boolean disassociateCusOrderAndDesign(String name, String orderreadableid, String designidlist, String email, String appuid) throws Exception{
        String timestamp = new Date().getTime()+"";
        String sign = getMD5(appsecret+appkey+appuid+timestamp);

        //注册
        boolean isRegister = isRegister(appuid, timestamp, sign);
        if(!isRegister){
            register(name, email, appuid, timestamp, sign);
        }

        String url = openapi_url + "/v2/cus/order/customer/disassociate/design?appuid="+appuid+"&orderreadableid="+orderreadableid+"&designidlist="+designidlist+"&sign="+sign+"&timestamp="+timestamp+"&appkey="+appkey;
        JSONObject result = RequestUtils.post(url, null);
        if("0".equals(result.getString("c"))){
            return result.getBoolean("d");
        } else {
            String msg = handleErrorMsg(result);
            throw new Exception(msg);
        }
    }

    /**
     * 搜索订单
     * @param appuid
     *      影子用户id
     * @param templatekey
     *      订单模板key
     * @param orderreadableid
     *      订单系统可读编号
     * @param eventkey
     *      事件key
     * @param body
     *      请求包体
     * @param email
     *      邮箱
     * @return
     * @throws Exception
     */
    public JSONObject searchUserOrder(String name, String body, String email, String appuid) throws Exception{
        String timestamp = new Date().getTime()+"";
        String sign = getMD5(appsecret+appkey+appuid+timestamp);

        //注册
        boolean isRegister = isRegister(appuid, timestamp, sign);
        if(!isRegister){
            register(name, email, appuid, timestamp, sign);
        }

        String url = openapi_url + "/v2/cus/order/search?appuid="+appuid+"&sign="+sign+"&timestamp="+timestamp+"&appkey="+appkey;
        JSONObject result = RequestUtils.post(url, body.toString());
        if("0".equals(result.getString("c"))){
            JSONObject json = result.getJSONObject("d");
            return result.getJSONObject("d");
        } else {
            String msg = handleErrorMsg(result);
            throw new Exception(msg);
        }
    }

    /**
     * 获取设计方案和订单关联关系列表
     * @param appuid
     *      影子用户id
     * @param email
     *      邮箱
     * @return
     * @throws Exception
     */
    public JSONObject getUserOrderAndDesignAssociateList(String name, String email, String appuid) throws Exception{
        String timestamp = new Date().getTime()+"";
        String sign = getMD5(appsecret+appkey+appuid+timestamp);

        //注册
        boolean isRegister = isRegister(appuid, timestamp, sign);
        if(!isRegister){
            register(name, email, appuid, timestamp, sign);
        }

        String url = openapi_url + "/v2/cus/order/design/list?appuid="+appuid+"&sign="+sign+"&timestamp="+timestamp+"&appkey="+appkey+"&num=10000&start=0";
        JSONObject result = RequestUtils.get(url);
        if("0".equals(result.getString("c"))){
            JSONObject json = result.getJSONObject("d");
            return result.getJSONObject("d");
        } else {
            String msg = handleErrorMsg(result);
            throw new Exception(msg);
        }
    }

    /**
     * 从酷家乐获取订单已经关联的方案
     * @param appuid
     * @param orderreadableid
     * @param email
     *      邮箱
     * @return
     * @throws Exception
     */
    public String getAssociateDesignFromKujiale(String name, String orderreadableid, String email, String appuid) throws Exception{
        JSONObject associateJson = getUserOrderAndDesignAssociateList(name, email, appuid);
        JSONArray result = associateJson.getJSONArray("result");
        String designIds = "";
        for (Iterator iterator = result.iterator();iterator.hasNext();){
            JSONObject associate = (JSONObject)iterator.next();
            boolean orderAssociated = associate.getBoolean("orderAssociated");
            if(orderAssociated){
                String orderReadableId = associate.getString("orderReadableId");
                if(orderreadableid.equals(orderReadableId)){
                    String designId = associate.getString("designId");
                    if(designIds.equals("")){
                        designIds = designId;
                    } else {
                        designIds = designIds + "," + designId;
                    }
                }
            }
        }
        return designIds;
    }

    /**
     * 获取md加密信息（32位小写加密）
     * @param str
     * @return
     * @throws Exception
     */
    public String getMD5(String str) throws Exception{
        return DigestUtils.md5Hex(str);
    }

    /**
     * 处理错误返回信息
     * @param json
     * @return
     */
    private String handleErrorMsg(JSONObject json){
        String code = json.getString("c");
        String msg = json.getString("m");
        if("100001".equals(code)){
            msg = "用户未注册,请联系管理员!";
        }
        return msg;
    }
}
