package com.dxhy.erp.service;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.dxhy.common.constant.DbConstant;
import com.dxhy.common.datasource.config.DynamicContextHolder;
import com.dxhy.common.enums.ReturnCodeEnum;
import com.dxhy.common.util.pojo.Authorize;
import com.dxhy.common.util.pojo.GlobalInfo;
import com.dxhy.common.utils.DateUtils;
import com.dxhy.erp.dao.SignedDao;
import com.dxhy.erp.dao.SysDeptDao;
import com.dxhy.erp.entity.*;
import com.dxhy.erp.model.GatherData;
import com.dxhy.erp.model.InvoiceDetailInfo;
import com.dxhy.erp.model.InvoiceInfoYl;
import com.dxhy.erp.model.ReturnStateInfo;
import com.dxhy.erp.utils.CheckUtils;
import com.dxhy.erp.utils.HmacSHA1Util;
import com.fasterxml.jackson.databind.ObjectMapper;

import cn.hutool.core.codec.Base64;
import lombok.extern.slf4j.Slf4j;

/**
 *
 * @Title CollectService.java 采集接口与状态更新接口
 * @Package com.dx.project.service
 * @author X Yang
 * @date 2017年6月6日 下午7:48:47
 * @version 1.0
 */
@SuppressWarnings({"AlibabaUndefineMagicConstant", "AlibabaMethodTooLong"})
@Service("signedService")
@Slf4j

public class SignedService {

    @Resource
    private SignedDao signedDao;

    @Resource
    private SysDeptDao sysDeptDao;

    @Value("${pro.yl.secretKey}")
    private String secretKey;

    @Value("${pro.yl.gfTaxNo}")
    private String yLgfTaxNo;
    @Value("${dxhy.datasource.dxhy_admin:dxhy_admin}")
    private String dxhyAdmin;

    /**
     * 采集数据查询
     *
     * @throws Exception
     * @author X Yang
     * @date 2017年6月6日 下午7:50:34
     */
    @Transactional(rollbackFor = Exception.class)
    public List<RecordInvoice> selectByCollect(String currentDateBegin, String currentDateEnd, String gfTaxNo)
        throws Exception {
        Date startDate = new SimpleDateFormat("yyyyMMddHHmmss").parse(currentDateBegin);
        Date endDate = new SimpleDateFormat("yyyyMMddHHmmss").parse(currentDateEnd);
        return signedDao.selectByCollect(startDate, endDate, gfTaxNo, dxhyAdmin);
    }

    /**
     *
     * 统计采集数量
     *
     * @param currentDateBegin
     * @param currentDateEnd
     * @param gfTaxNo
     * @throws Exception
     * @author X Yang
     * @date 2017年6月6日 下午7:52:02
     */
    @Transactional(rollbackFor = Exception.class)
    public Integer selectByCount(String currentDateBegin, String currentDateEnd, String gfTaxNo) throws Exception {
        Date startDate = new SimpleDateFormat("yyyyMMddHHmmss").parse(currentDateBegin);
        Date endDate = new SimpleDateFormat("yyyyMMddHHmmss").parse(currentDateEnd);
        return signedDao.selectByCount(startDate, endDate, gfTaxNo, dxhyAdmin);
    }

    /**
     *
     * 校验数据项
     *
     * @author X Yang
     * @throws Exception
     * @date 2017年6月7日 上午9:34:20
     */
    public ReturnStateInfo getCheck(YlCollectData data) throws Exception {
        ReturnStateInfo run = new ReturnStateInfo();
        if (CheckUtils.isNullOrEmpty(data.getBuyerTaxNo())) {
            run.setReturnCode("2006");
            run.setReturnMessage("纳税人识别号不能为空");
            return run;
        }
        if (CheckUtils.isNullOrEmpty(data.getSignedDateBegin())
            || (!CheckUtils.stringLength(data.getSignedDateBegin(), 14))) {
            run.setReturnCode("2007");
            run.setReturnMessage("当前起始日期不能为空并且为14位");
            return run;
        }
        if (CheckUtils.isNullOrEmpty(data.getSignedDateEnd())
            || (!CheckUtils.stringLength(data.getSignedDateEnd(), 14))) {
            run.setReturnCode("2010");
            run.setReturnMessage("当前结束日期不能为空并且为14位");
            return run;
        }
        if (CheckUtils.check(data.getSignedDateBegin(), data.getSignedDateEnd(), 2400000)) {
            run.setReturnCode("2008");
            run.setReturnMessage("当前起始日期至当前结束日期已超过40分钟");
            return run;
        }
        return run;
    }

    /**
     *
     * 校验数据项
     *
     * @author X Yang
     * @throws Exception
     * @date 2017年6月7日 上午9:34:20
     */
    public ReturnStateInfo getCheckAmount(YlCollectData data) throws Exception {
        ReturnStateInfo run = new ReturnStateInfo();
        if (CheckUtils.isNullOrEmpty(data.getBuyerTaxNo())) {
            run.setReturnCode("2006");
            run.setReturnMessage("纳税人识别号不能为空");
            return run;
        }
        if (CheckUtils.isNullOrEmpty(data.getSignedDateBegin())
            || (!CheckUtils.stringLength(data.getSignedDateBegin(), 14))) {
            run.setReturnCode("2007");
            run.setReturnMessage("当前起始日期不能为空并且为14位");
            return run;
        }
        if (CheckUtils.isNullOrEmpty(data.getSignedDateEnd())
            || (!CheckUtils.stringLength(data.getSignedDateEnd(), 14))) {
            run.setReturnCode("2010");
            run.setReturnMessage("当前结束日期不能为空并且为14位");
            return run;
        }
        return run;
    }

    /**
     *
     * 实体类转换
     *
     * @param detail
     * @author X Yang
     * @date 2017年6月7日 下午2:40:03
     */
    public InvoiceDetailInfo getInvoiceDetailInfo(RecordInvoiceDetail detail) {
        InvoiceDetailInfo detailInfo = new InvoiceDetailInfo();
        detailInfo.setDetailNo(detail.getDetailNo() + "");
        detailInfo.setGoodsName(detail.getGoodsName());
        if (detail.getModel() == null || "".equals(detail.getModel())) {
            detailInfo.setSpecificationModel("");
        } else {
            detailInfo.setSpecificationModel(detail.getModel());
        }
        if (detail.getNum() == null || "".equals(detail.getNum())) {
            detailInfo.setNum("0");
        } else {
            detailInfo.setNum(detail.getNum());
        }
        detailInfo.setUnit(detail.getUnit());
        if (detail.getUnitPrice() == null) {
            detailInfo.setUnitPrice("");
        } else {
            detailInfo.setUnitPrice(detail.getUnitPrice());
        }
        if (detail.getDetailAmount() == null) {
            detailInfo.setDetailAmount("");
        } else {
            detailInfo.setDetailAmount(detail.getDetailAmount());
        }
        if (detail.getTaxRate() == null) {
            detailInfo.setTaxRate("");
        } else {
            detailInfo.setTaxRate(detail.getTaxRate());
        }
        if (detail.getTaxAmount() == null) {
            detailInfo.setTaxAmount("");
        } else {
            detailInfo.setTaxAmount(detail.getTaxAmount());
        }
        return detailInfo;
    }

    public InvoiceInfoYl getInvoiceInfo(RecordInvoice invoice) {
        InvoiceInfoYl info = new InvoiceInfoYl();
        info.setInvoiceCode(invoice.getInvoiceCode());
        info.setInvoiceNo(invoice.getInvoiceNo());
        info.setInvoiceDate(new SimpleDateFormat("yyyyMMdd").format(invoice.getInvoiceDate()));
        info.setBuyerAcount(invoice.getGfBankAndNo());
        info.setBuyerAddressPhone(invoice.getGfAddressAndPhone());
        info.setBuyerName(invoice.getGfName());
        info.setBuyerTaxNo(invoice.getGfTaxNo());
        info.setSalerAcount(invoice.getXfBankAndNo());
        info.setSalerAddressPhone(invoice.getXfAddressAndPhone());
        info.setSalerName(invoice.getXfName());
        info.setSalerTaxNo(invoice.getXfTaxNo());
        info.setInvoiceAmount(invoice.getInvoiceAmount() == null ? "" : invoice.getInvoiceAmount().toString());
        info.setTaxAmount(invoice.getTaxAmount() == null ? "" : invoice.getTaxAmount().toString());
        info.setTotalAmount(invoice.getTotalAmount() == null ? "" : invoice.getTotalAmount().toString());
        info.setRemark(invoice.getRemark());
        if (invoice.getConfirmDate() == null) {
            info.setLegalizeDate("");
        } else {
            info.setLegalizeDate(new SimpleDateFormat("yyyyMMdd").format(invoice.getConfirmDate()));
        }
        info.setLegalizeState(invoice.getRzhYesorno());
        info.setInvoiceStatus(invoice.getInvoiceStatus());
        info.setInvoiceType(invoice.getInvoiceType());
        if ("10".equals(info.getInvoiceType()) || "08".equals(info.getInvoiceType())) {
            info.setVendorId(invoice.getVendorId());
            info.setRequestId(invoice.getRequestId());
        }
        String date = new SimpleDateFormat("yyyyMMddHHmmss").format(invoice.getQsDate());
        info.setSignDate(date);
        info.setScanName(invoice.getUserName());
        info.setScanDate(DateUtils.dateToStrLong(invoice.getCreateDate()));
        return info;
    }

    /**
     *
     * 采集接口
     *
     * @param request
     * @param response
     * @author X Yang
     * @date 2017年6月7日 下午6:13:30
     */
    public String get(GlobalInfo globalInfo, Map<String, String> map, ObjectMapper mapper, HttpServletRequest request,
        HttpServletResponse response) throws IOException {
        ReturnStateInfo run = new ReturnStateInfo();
        List<RecordInvoice> list = null;
        List<RecordInvoiceDetail> detailList = null;
        List<InvoiceInfoYl> infos = new ArrayList<>();
        String globalJson = "";
        String runJson = "";
        try {
            globalJson = JSONObject.toJSONString(globalInfo);
            YlCollectData data = mapper.readValue(map.get("data"), YlCollectData.class);
            // 校验data项
            run = getCheck(data);
            if (run.getReturnCode() != null) {
                runJson = JSONObject.toJSONString(run);
                response.setCharacterEncoding("UTF-8");
                response.setContentType("application/json; charset=utf-8");
                return "{\"globalInfo\":" + globalJson + ",\"returnStateInfo\":" + runJson + "}";
            }
            DynamicContextHolder.push(DbConstant.BASICS_READ);
            SysDeptEntity deptEntity = sysDeptDao.getOrg(data.getBuyerTaxNo());
            String dbName = null;
            if (deptEntity != null && deptEntity.getDbName() != null) {
                dbName = deptEntity.getDbName();
            } else {

                run.setReturnCode(ReturnCodeEnum.JTSHBF.getFhzDm());
                run.setReturnMessage(ReturnCodeEnum.JTSHBF.getFhzMc(ReturnCodeEnum.JTSHBF.getIndex()));
                runJson = JSONObject.toJSONString(run);
                response.setCharacterEncoding("UTF-8");
                response.setContentType("application/json; charset=utf-8");
                return "{\"globalInfo\":" + globalJson + ",\"returnStateInfo\":" + runJson + "}";
            }
            DynamicContextHolder.push(dbName + DbConstant.BUSINESS_READ);
            list = this.selectByCollect(data.getSignedDateBegin(), data.getSignedDateEnd(), data.getBuyerTaxNo());
            log.debug("================" + list);
            for (RecordInvoice record : list) {
                List<InvoiceDetailInfo> detailInfos = new ArrayList<>();
                InvoiceInfoYl invoiceInfo;
                invoiceInfo = this.getInvoiceInfo(record);
                log.debug("-------------------" + invoiceInfo);
                if ("01".equals(record.getInvoiceType()) || "08".equals(record.getInvoiceType())) {
                    try {
                        DynamicContextHolder.push(dbName + DbConstant.DETAIL_READ);
                        detailList = signedDao.selectDetails(record.getInvoiceCode() + record.getInvoiceNo());
                        log.debug("============" + detailList);
                        if (detailList.size() > 0) {
                            for (RecordInvoiceDetail invoiceDetail : detailList) {
                                detailInfos.add(this.getInvoiceDetailInfo(invoiceDetail));
                            }
                            invoiceInfo.setDetailList(detailInfos);
                        }
                    } catch (Exception e) {
                        log.error("没有明细信息", e);
                    }

                }
                infos.add(invoiceInfo);
            }
            DynamicContextHolder.push(dbName + DbConstant.BUSINESS_READ);
            Integer count =
                this.selectByCount(data.getSignedDateBegin(), data.getSignedDateEnd(), data.getBuyerTaxNo());
            GatherData gatherData = new GatherData();
            gatherData.setContentRows(infos.size());
            gatherData.setTotalRows(count);
            gatherData.setInvoices(infos);
            run.setReturnCode("0000");
            run.setReturnMessage("处理成功");
            runJson = JSONObject.toJSONString(run);
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            return "{\"globalInfo\":" + globalJson + ",\"returnStateInfo\":" + runJson + ",\"data\":\""
                + Base64.encode(JSONObject.toJSONString(gatherData)) + "\"}";
        } catch (Exception e1) {
            run.setReturnCode("2011");
            run.setReturnMessage("其他异常");
            log.error("异常信息为", e1);
            runJson = JSONObject.toJSONString(run);
            globalJson = JSONObject.toJSONString(globalInfo);
        }
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        return "{\"globalInfo\":" + globalJson + ",\"returnStateInfo\":" + runJson + "}";
    }

    /**
     * 百度检查密钥是否合法
     *
     * @param requestParam
     * @return
     */
    public int validParams(Map<String, String> requestParam) {
        try {
            // 拼接签名的前半部分字符串
            StringBuilder strB = new StringBuilder();
            strB.append("post");
            strB.append("/YLinvoice/dii");
            strB.append("?");

            // 拼接签名的后半部分字符串
            StringBuilder strB2 = new StringBuilder();
            Authorize authorize =
                JSONObject.parseObject(requestParam.get("authorize"), new TypeReference<Authorize>() {});
            strB2.append("authorize=").append("{\"appSecId\":\"").append(authorize.getAppSecId()).append("\"}");
            strB2.append("&globalInfo=").append(requestParam.get("globalInfo"));
            strB2.append("&data=").append(Base64.encode(requestParam.get("data")));

            // 总拼接
            strB.append(strB2.toString());
            String str = strB.toString();
            log.info("签权的字符串：{}", str);
            String hmacsha1 = HmacSHA1Util.hmacsha2(str, secretKey);
            log.info("加密之后：{}", hmacsha1);
            // 验证签名
            log.info("客户端传过来的签权字符串：{}", authorize.getAppSec());
            if (!authorize.getAppSec().equals(hmacsha1)) {
                return 1;
            }
        } catch (Exception ignored) {

        }
        return 0;
    }

    /**
     * @Methods:getGlobalInfo : 通用报文头信息
     * @author JLY
     * @date 2017年6月9日下午3:35:55
     * @param requestParam
     * @return 头信息实体
     * @throws Exception
     */
    public GlobalInfo getGlobalInfo(Map<String, String> requestParam) throws Exception {
        return JSONObject.parseObject(requestParam.get("globalInfo"), new TypeReference<GlobalInfo>() {});
    }

    /**
     * @Methods:getSignFailure : 签权失败返回报文getSignFailure
     * @date 2017年6月15日下午4:41:27
     * @param globalInfo
     * @return
     * @throws Exception
     */
    public String getSignFailure(HttpServletResponse response, GlobalInfo globalInfo) throws Exception {
        ReturnStateInfo returnStateInfo = new ReturnStateInfo();
        returnStateInfo.setReturnCode("2002");
        returnStateInfo.setReturnMessage("授权信息错误");
        String json = JSONObject.toJSONString(returnStateInfo);
        String global = JSONObject.toJSONString(globalInfo);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        return "{\"globalInfo\":" + global + ",\"returnStateInfo\":" + json + "}";
    }

    /**
     * @Methods:getInterfaceCodeError : 返回接口编码不存在
     * @author JLY
     * @date 2017年6月12日上午11:53:22
     * @param globalInfo
     * @return
     */
    public String getInterfaceCodeError(HttpServletResponse response, GlobalInfo globalInfo) throws Exception {
        ReturnStateInfo returnStateInfo = new ReturnStateInfo();
        returnStateInfo.setReturnCode("2005");
        returnStateInfo.setReturnMessage("接口代码不存在");
        String json = JSONObject.toJSONString(returnStateInfo);
        String global = JSONObject.toJSONString(globalInfo);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        return "{\"globalInfo\":" + global + ",\"returnStateInfo\":" + json + "}";
    }

    /**
     * @Methods:getDealWithFailure : 处理失败
     * @author JLY
     * @date 2017年6月14日上午10:00:37
     * @param globalInfo
     * @return 失败报文
     * @throws IOException
     */
    public String getDealWithFailure(HttpServletResponse response, GlobalInfo globalInfo) {
        ReturnStateInfo returnStateInfo = new ReturnStateInfo();
        returnStateInfo.setReturnCode("9999");
        returnStateInfo.setReturnMessage("处理失败");
        String global = "";
        String json = "";
        try {
            json = JSONObject.toJSONString(returnStateInfo);
            global = JSONObject.toJSONString(globalInfo);
        } catch (Exception e) {
            log.error("异常信息为", e);
        }
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        return "{\"globalInfo\":" + global + ",\"returnStateInfo\":" + json + "}";
    }

    public String getSola(GlobalInfo globalInfo, Map<String, String> map, ObjectMapper mapper,
        HttpServletRequest request, HttpServletResponse response) throws IOException {
        ReturnStateInfo run = new ReturnStateInfo();
        RecordInvoice record = null;
        InvoiceInfoYl invoiceInfo = null;
        List<RecordInvoiceDetail> details = null;
        String globalJson = "";
        String runJson = "";
        try {
            globalJson = JSONObject.toJSONString(globalInfo);
            ElectronLog data = mapper.readValue(map.get("data"), ElectronLog.class);
            // 校验data项
            run = getCheckElectron(data);
            if (run.getReturnCode() != null) {
                runJson = JSONObject.toJSONString(run);
                response.setCharacterEncoding("UTF-8");
                response.setContentType("application/json; charset=utf-8");
                return "{\"globalInfo\":" + globalJson + ",\"returnStateInfo\":" + runJson + "}";
            }
            DynamicContextHolder.push(DbConstant.BASICS_READ);
            SysDeptEntity deptEntity = sysDeptDao.getOrg(yLgfTaxNo);
            String dbName = null;
            if (deptEntity != null && deptEntity.getDbName() != null) {
                dbName = deptEntity.getDbName();
            } else {

                run.setReturnCode(ReturnCodeEnum.JTSHBF.getFhzDm());
                run.setReturnMessage(ReturnCodeEnum.JTSHBF.getFhzMc(ReturnCodeEnum.JTSHBF.getIndex()));
                runJson = JSONObject.toJSONString(run);
                response.setCharacterEncoding("UTF-8");
                response.setContentType("application/json; charset=utf-8");
                return "{\"globalInfo\":" + globalJson + ",\"returnStateInfo\":" + runJson + "}";
            }
            DynamicContextHolder.push(dbName + DbConstant.BUSINESS_READ);
            record = selectByRecordInvoice(data.getInvoiceNo(), data.getInvoiceCode());
            if (record != null) {
                invoiceInfo = getInvoiceInfo(record);
                try {
                    DynamicContextHolder.push(dbName + DbConstant.DETAIL_READ);
                    details = signedDao.selectDetails(data.getInvoiceCode() + data.getInvoiceNo());
                    log.info("----------" + details);
                    if (details.size() > 0) {

                        List<InvoiceDetailInfo> li = new ArrayList<>();
                        for (RecordInvoiceDetail detail : details) {
                            li.add(getInvoiceDetailInfo(detail));
                        }
                        invoiceInfo.setDetailList(li);
                    }
                } catch (Exception e) {
                    log.error("没有明细数据", e);
                }
            }
            run.setReturnCode("0000");
            run.setReturnMessage("处理成功");
            runJson = JSONObject.toJSONString(run);
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            return "{\"globalInfo\":" + globalJson + ",\"returnStateInfo\":" + runJson + ",\"data\":\""
                + Base64.encode(JSONObject.toJSONString(invoiceInfo)) + "\"}";

        } catch (Exception e) {
            run.setReturnCode("2011");
            run.setReturnMessage("其他异常");
            log.error("异常信息为", e);
            runJson = JSONObject.toJSONString(run);
            globalJson = JSONObject.toJSONString(globalInfo);
        }
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        return "{\"globalInfo\":" + globalJson + ",\"returnStateInfo\":" + runJson + "}";
    }

    public ReturnStateInfo getCheckElectron(ElectronLog data) {
        ReturnStateInfo run = new ReturnStateInfo();
        if (CheckUtils.isNullOrEmpty(data.getInvoiceNo())) {
            run.setReturnCode("2012");
            run.setReturnMessage("发票号码不能为空");
            return run;
        }
        if (CheckUtils.isNullOrEmpty(data.getInvoiceCode())) {
            run.setReturnCode("2013");
            run.setReturnMessage("发票代码不能为空");
            return run;
        }
        return run;
    }

    public RecordInvoice selectByRecordInvoice(String invoiceNo, String invoiceCode) {
        return signedDao.selectByRecordInvoice(invoiceNo, invoiceCode, dxhyAdmin);
    }

    /**
     * @Methods:getAmount :获取总数
     * @author JLY
     * @date 2017年9月15日上午11:03:37
     */
    public String getAmount(GlobalInfo globalInfo, Map<String, String> map, ObjectMapper mapper,
        HttpServletRequest request, HttpServletResponse response) throws IOException {
        ReturnStateInfo run = new ReturnStateInfo();
        String globalJson = "";
        String runJson = "";
        try {
            globalJson = JSONObject.toJSONString(globalInfo);
            YlCollectData data = mapper.readValue(map.get("data"), YlCollectData.class);
            // 校验data项
            run = getCheckAmount(data);
            if (run.getReturnCode() != null) {
                runJson = JSONObject.toJSONString(run);
                response.setCharacterEncoding("UTF-8");
                response.setContentType("application/json; charset=utf-8");
                return "{\"globalInfo\":" + globalJson + ",\"returnStateInfo\":" + runJson + "}";
            }
            DynamicContextHolder.push(DbConstant.BASICS_READ);
            SysDeptEntity deptEntity = sysDeptDao.getOrg(data.getBuyerTaxNo());
            String dbName = null;
            if (deptEntity != null && deptEntity.getDbName() != null) {
                dbName = deptEntity.getDbName();
            } else {

                run.setReturnCode(ReturnCodeEnum.JTSHBF.getFhzDm());
                run.setReturnMessage(ReturnCodeEnum.JTSHBF.getFhzMc(ReturnCodeEnum.JTSHBF.getIndex()));
                runJson = JSONObject.toJSONString(run);
                response.setCharacterEncoding("UTF-8");
                response.setContentType("application/json; charset=utf-8");
                return "{\"globalInfo\":" + globalJson + ",\"returnStateInfo\":" + runJson + "}";
            }
            DynamicContextHolder.push(dbName + DbConstant.BUSINESS_READ);

            Integer count =
                this.selectByCount(data.getSignedDateBegin(), data.getSignedDateEnd(), data.getBuyerTaxNo());
            run.setReturnCode("0000");
            run.setReturnMessage("处理成功");
            runJson = JSONObject.toJSONString(run);
            String totalRows = "{\"totalRows\":" + count + "}";
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            return "{\"globalInfo\":" + globalJson + ",\"returnStateInfo\":" + runJson + ",\"data\":\""
                + Base64.encode(totalRows) + "\"}";
        } catch (Exception e1) {
            run.setReturnCode("2011");
            run.setReturnMessage("其他异常");
            log.error("异常信息为", e1);
            runJson = JSONObject.toJSONString(run);
            globalJson = JSONObject.toJSONString(globalInfo);
        }
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        return "{\"globalInfo\":" + globalJson + ",\"returnStateInfo\":" + runJson + "}";
    }

}
