package com.ruoyi.web.controller.system;

import com.alibaba.druid.support.json.JSONUtils;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.Global;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.Ztree;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.file.FileException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ZipUtil;
import com.ruoyi.common.utils.file.WordToPdf;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.redis.RedisUtil;
import com.ruoyi.common.utils.security.Md5Utils;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.framework.web.domain.server.Sys;
import com.ruoyi.system.domain.GtgsYwUser;
import com.ruoyi.system.domain.Gtgsyw;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.mapper.GtgsywMapper;
import com.ruoyi.system.service.IGtgsYwUserService;
import com.ruoyi.system.service.IGtgsywService;
import freemarker.template.Configuration;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpURL;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.aspectj.weaver.loadtime.Aj;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import sun.misc.BASE64Encoder;

import javax.activation.MimeType;
import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 待审核Controller
 *
 * @author xu
 * @date 2019-08-22
 */
@Controller
@RequestMapping("/system/gtgsyw")
public class GtgsywController extends BaseController
{
    private String prefix = "system/gtgsyw";
    @Autowired
    private IGtgsywService gtgsywService;

    @Autowired
    private GtgsywMapper gtgsywMapper;

    @Autowired
    private IGtgsYwUserService gtgsYwUserService;
    @Resource
    private RedisUtil redisUtil;

    //待审核
    @RequiresPermissions("system:gtgsyw:view")
    @GetMapping()
    public String gtgsyw(Model model)
    {
        //查询申请来源字典
        List<String>applyDiction=gtgsywService.selectDiction();
        model.addAttribute("diction", applyDiction);
        //待审核的状态为0
        model.addAttribute("state",0);
        return prefix + "/gtgsyw";
    }
    //审核中
    @GetMapping("/gtgsShz")
    public String gtgsShz(Model model)
    {
        //查询申请来源字典
        List<String>applyDiction=gtgsywService.selectDiction();
        model.addAttribute("diction", applyDiction);
        System.err.println("审核中");
        //审核中的状态为3
        model.addAttribute("state",3);
        return prefix + "/gtgsyw";
    }
    //完成审核
    @GetMapping("/gtgsWin")
    public String gtgsWin(Model model)
    {
        //查询申请来源字典
        List<String>applyDiction=gtgsywService.selectDiction();
        model.addAttribute("diction", applyDiction);
        model.addAttribute("listMonth",gtgsywService.selectByMonth());
        System.err.println("完成审核");
        //完成审核状态为1
        model.addAttribute("state",1);
        return prefix + "/check";
    }
    //审核不通过
    @GetMapping("/gtgsNotGo")
    public String gtgsNotGO(Model model)
    {
        //查询申请来源字典
        List<String>applyDiction=gtgsywService.selectDiction();
        model.addAttribute("diction", applyDiction);
        //审核退回状态为2
        model.addAttribute("state",2);
        return prefix + "/auditth";
    }
    /**
     *
     * @param flg 状态
     * @param gtgsyw 查询参数
     * @param codename 搜索个体工商户名称参数
     * @return 审核列表
     */
    @PostMapping("/list/{flg}")
    @ResponseBody
    public TableDataInfo auditlist1(@PathVariable("flg") Long flg,Gtgsyw gtgsyw,String codename)
    {
        //当前登录管理员的id
        Long userId=ShiroUtils.getUserId();
        gtgsyw.setId(userId);
        gtgsyw.setFlg(flg);
//        if(flg==2){
//            //当前审核状态为2(退回) 退回单独一个表
//            startPage();
//            List<auditTh>list= gtgsywService.selectauditTh(gtgsyw,codename);
//            return getDataTable(list);
//        }
        List<Gtgsyw> list = gtgsywService.selectGtgsywList(gtgsyw);
        for (Gtgsyw gt:list){
            //个体工商户名称 由四个字段组合
            if(!gt.getZwzh().equals("***")){
                gt.setNsxzq(gt.getNsxzq()+gt.getZwzh()+gt.getMingchenghangye()+gt.getZuzhixingshi());
            }else{
                gt.setNsxzq("***");
            }

            //判断所搜个体工商户名称参数是否为空或null
            if(codename!=null && !codename.equals("")){
                List<Gtgsyw> listgt=new ArrayList<>();
                //判断个体工商户名称是否包含搜索参数个体工商户名称
                if(gt.getNsxzq().contains(codename)){
                    listgt.add(gt);
                }
                return getDataTable(listgt);
            }
        }
        return getDataTable(list);
    }
    /**
     * 导出待审核列表
     */
    @RequiresPermissions("system:gtgsyw:export")
    @PostMapping("/export/{flg}")
    @ResponseBody
    public AjaxResult export(@PathVariable("flg")Long flg,  Gtgsyw gtgsyw)
    {
        gtgsyw.setFlg(flg);
        SysUser sysUser= ShiroUtils.getSysUser();

        if(!sysUser.isAdmin()){
            gtgsyw.setShenherenname(sysUser.getUserName());
            gtgsyw.setShenherenid(String.valueOf(sysUser.getUserId()));
        }
        List<Gtgsyw> list = gtgsywService.selectGtgsywAllList(gtgsyw);
        for (Gtgsyw li:list
             ) {
            li.setGtgsmc();
        }
        ExcelUtil<Gtgsyw> util = new ExcelUtil<Gtgsyw>(Gtgsyw.class);
        return util.exportExcel(list, "gtgsyw");

    }
    /**
     * 新增待审核
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }
    /**
     * 新增保存待审核
     */
    @RequiresPermissions("system:gtgsyw:add")
    @Log(title = "待审核", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(Gtgsyw gtgsyw)
    {
        return toAjax(gtgsywService.insertGtgsyw(gtgsyw));
    }
    /**
     * 修改待审核
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        Gtgsyw gtgsyw = gtgsywService.selectGtgsywById(id);
        mmap.put("gtgsyw", gtgsyw);
        return prefix + "/edit";
    }
    /**
     * 详细审核页面
     * @param id 要查看详细的id
     * @param model
     * @return
     *
     */
    @GetMapping("/audit/{id}")
    public String audit(@PathVariable("id") Long id, Model model)
    {
        System.err.println("id:"+id);
        //当前登录管理员的id
        Long userId= ShiroUtils.getUserId();
        //根据id修改状态为审核中
        gtgsywService.updateFlg(id,userId);
        Gtgsyw gtgsyw = gtgsywService.selectGtgsywById(id);


        //查询身份证照片
        List<Map> list=gtgsywService.selectPhotosByBsid(gtgsyw.getBsid());
        for (Map li:list) {
            if(!li.isEmpty()&&li.get("CailiaoName").equals("身份证扫描件")){
                //身份证正面(0为正面,1为反面)
                if(gtgsyw.getStatusFront()==null||gtgsyw.getStatusFront().isEmpty()){
                    gtgsyw.setStatusFront(String.valueOf(li.get("FilePath")));
                }else {
                    gtgsyw.setStatusFan(String.valueOf(li.get("FilePath")));
                }
            }else if(li.get("CailiaoName").equals("网络平台店铺经营证明")){
                model.addAttribute("typeSrc",String.valueOf(li.get("FilePath")));
            }
        }

        //判断是否为党员
        if(gtgsyw.getIsdy()!=null){
            if(gtgsyw.getIsdy()==0){
                gtgsyw.setDangyuan("否");
            }else if (gtgsyw.getIsdy()==1){
                gtgsyw.setDangyuan("是");
            }
        }
        //判断是否为军产
        if(gtgsyw.getIsjc()!=null){
            if(gtgsyw.getIsjc()==0){
                gtgsyw.setJunchan("否");
            }else if (gtgsyw.getIsdy()==1){
                gtgsyw.setJunchan("是");
            }
        }
        //是否打印正文
        gtgsyw.setRzduibishenhe(gtgsyw.getIsprint().toString());
        //是否打印副文
        gtgsyw.setRzduibistatus(gtgsyw.getIsprint_F().toString());
        //  gtgsyw.setOflg(gtgsyw.getFlg().toString());
        System.err.println("详细页面:"+gtgsyw.getOflg());
        //个体工商户名称四个字段组成
        gtgsyw.setCodeName(gtgsyw.getNsxzq()+gtgsyw.getZwzh()+gtgsyw.getMingchenghangye()+gtgsyw.getZuzhixingshi());
        //行业总称
        gtgsyw.setHangye(gtgsyw.getHangye()+","+gtgsyw.getHangye1()+","+gtgsyw.getHangye2()+","+gtgsyw.getHangye3());

        model.addAttribute("gtgsyw",gtgsyw);
        //行业分类数据
//        List<Ztree> ztrees = gtgsywService.selectTradeTree();
        //审核人的id
        model.addAttribute("shenheid",gtgsyw.getShenherenid());
        //登录管理员的id
        model.addAttribute("userid",userId);
        model.addAttribute("jycssy",gtgsyw.getJycssy());
//        model.addAttribute("ztree",ztrees);
        return prefix + "/audit";
    }
    /**
     * 修改保存个体工商户信息
     */
    @Log(title = "待审核", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(Gtgsyw gtgsyw,String zwzh,String sex)
    {
        //性别1为男 2为女
        if(gtgsyw.getXingbie()!=null &&gtgsyw.getXingbie().equals("1")){
            gtgsyw.setXingbie("男");
        }else if(gtgsyw.getXingbie()!=null && gtgsyw.getXingbie().equals("2")){
            gtgsyw.setXingbie("女");
        }
        System.err.println("行业:"+gtgsyw.getHangye());
        //行业用","分成数组
        String []hangye =gtgsyw.getHangye().split(",");
        System.err.println("行业.length:"+hangye.length);
        //分别赋值给行业1,2,3
        if(hangye.length==4){
            gtgsyw.setHangye(hangye[0]);
            gtgsyw.setHangye1(hangye[1]);
            gtgsyw.setHangye2(hangye[2]);
            gtgsyw.setHangye3(hangye[3]);
        }
        System.err.println("gtgsyw:"+gtgsyw.getShenqingdate());
        //更新时间
        return toAjax(gtgsywService.updateGtgsyw(gtgsyw));
    }
    /**
     * 删除待审核
     */
    @Log(title = "待审核", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(gtgsywService.deleteGtgsywByIds(ids));
    }
    /**
     * 审核通过  操作
     */
    @PostMapping( "{flg}/pass/{id}")
    @ResponseBody
    public String edit(@PathVariable("id") Long id,@PathVariable("flg") Long flg)
    {
        System.err.println("id:"+id);
        gtgsywService.updateById(id,flg);
        return prefix;
    }
    /**
     * 不予受理
     */
    @GetMapping( "/sendback/{id}")
    public String send(@PathVariable("id")String id,Model model)
    {
        System.err.println("退回:"+id);
        //查询退回便捷语
        model.addAttribute("easy", gtgsywService.selecteasy());
        model.addAttribute("id", id);
        return prefix+"/sendback.html";
    }
    /**
     * 保存不予受理
     * @param id 不予受理的id
     * @param returnReason 不予受理原因
     * @return
     */
    @PostMapping( "/send/{id}")
    @ResponseBody
    public AjaxResult returnSend(@PathVariable("id") String id ,String returnReason) throws Exception {
        System.err.println("post:"+id);
        System.err.println("退回:"+id);
        System.err.println("String returnReason:"+ returnReason);
        //当前登录管理员的id
        Long userId= ShiroUtils.getUserId();
        int i=gtgsywService.updateThContent(id,returnReason,userId);

        Gtgsyw gtgsyw=gtgsywService.selectGtgsywById(Long.valueOf(id));
        String stt=null;
        if(!gtgsyw.getZwzh().equals("***")){
            stt=gtgsyw.getNsxzq()+gtgsyw.getZwzh()+gtgsyw.getMingchenghangye()+gtgsyw.getZuzhixingshi();
        }else{
            stt="***";
        }
//        HttpUtils.sendGet("http://192.168.28.155:33080/common/send","name="+gtgsyw.getJingyingren()+"&phone="+ gtgsyw.getJingyingrenphone()+"&gtname="+stt+"&sendback="+returnReason);
//        interfaceUtil("http://192.168.28.155:33080/common/send?"+"name="+URLEncoder.encode(gtgsyw.getJingyingren(),"utf-8")+"&phone="+URLEncoder.encode(gtgsyw.getJingyingrenphone(),"utf-8")+"&gtname="+URLEncoder.encode(stt,"utf-8")+"&sendback="+URLEncoder.encode(returnReason,"utf-8"),"");

        sendMessage(gtgsyw.getJingyingren(),gtgsyw.getJingyingrenphone(),stt,returnReason);
        System.err.println("i:"+i);
        return toAjax(i);
    }
    /**
     * 审核通过
     * @param id 审核通过id
     * @param model
     * @param xycode 社会信用代码
     * @return 审核通过页面
     */
    @GetMapping( "/auditpass/{id}")
    public String auditpass(@PathVariable("id")String id,Model model,String xycode)
    {
        System.err.println("通过:"+id);
        //注册日期(默认当前时间)
        Date date =new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String dateString = formatter.format(date);

        model.addAttribute("date",dateString);
        model.addAttribute("id", id);
        return prefix+"/auditpass.html";
    }
    /**
     * 信用贷代码失去焦点事件后显示二维码
     */
    @PostMapping( "/auditpass")
    @ResponseBody
    public String ajax(Model model,String xycode,HttpServletResponse response,HttpServletRequest request)
    {
        //判断信用代码是否为空或null
        if(xycode!=null && !xycode.equals("")){
            System.err.println("xycode:"+xycode);
            /*String QRcode=GetImageStr("D:/二维码/licence.png");*/
            String url=Global.getConfig("ruoyi.gsdz")+":8005/gtdj/licence.do?method=toTowDimCode&appNo=&uniScid="+xycode+"&certTypeId=41";
            String QRcode=  getImg(url);
            System.err.println("QRcode:"+QRcode);
            model.addAttribute("xycode", QRcode);
            return QRcode;
        }
        return "";
    }
    /**
     * 审核通过保存
     * @return
     */
    @PostMapping( "/pass/{id}")
    @ResponseBody
    public AjaxResult pass(Gtgsyw gt) throws Exception {

       /* String QRcode=GetImageStr("D:/二维码/licence.png");
        /*System.err.println("二维码:"+qrcode);*/
        String url=Global.getConfig("ruoyi.gsdz")+":8005/gtdj/licence.do?method=toTowDimCode&appNo=&uniScid="+gt.getXinyongcode()+"&certTypeId=41";
        String QRcode=  getImg(url);
        /* String QRcode=QRcode(xycode);*/
        System.err.println("QRcode:"+QRcode);
        Long userId= ShiroUtils.getUserId();
        String userName = gtgsywMapper.selectUserName(userId);
        gt.setShenherenid(String.valueOf(userId));
        gt.setShenherenname(userName);
        gt.setErweimabase64(QRcode);
        gt.setFlg(1L);
        Gtgsyw gtgsyw=gtgsywService.selectGtgsywById(Long.valueOf(gt.getId()));

        gt.setUpdateTime(new Date());
        //保存通过审核
        int p=gtgsywService.updateGtgsyw(gt);
        if(p==1){
            String stt=null;
            if(!gtgsyw.getZwzh().equals("***")){
                stt=gtgsyw.getNsxzq()+gtgsyw.getZwzh()+gtgsyw.getMingchenghangye()+gtgsyw.getZuzhixingshi();
                //进行redis存储
                String key = gtgsyw.getHangye() + ":" + ToPinyin(gtgsyw.getZwzh().replace("", "-").trim());
                System.err.println(key);
                redisUtil.set(key,gtgsyw.getZwzh() , 60*60*24);

            }else{
                stt="***";
            }
//           System.err.println("http://192.168.28.155:33080/common/send"+"?name="+gtgsyw.getJingyingren()+"&phone="+ gtgsyw.getJingyingrenphone()+"&gtname="+stt+"&sendback=");
//           HttpUtils.sendGet("http://192.168.28.155:33080/common/send","name="+gtgsyw.getJingyingren()+"&phone="+ gtgsyw.getJingyingrenphone()+"&gtname="+stt);
//           interfaceUtil("http://192.168.28.155:33080/common/send?"+"name="+URLEncoder.encode(gtgsyw.getJingyingren(),"utf-8")+"&phone="+URLEncoder.encode(gtgsyw.getJingyingrenphone(),"utf-8")+"&gtname="+URLEncoder.encode(stt,"utf-8"),"");
            sendMessage(gtgsyw.getJingyingren(),gtgsyw.getJingyingrenphone(),stt,null);
        }
        return toAjax(1);
    }

    /**
     * 汉字转为拼音
     * @param chinese
     * @return
     */
    public static String ToPinyin(String chinese){
        String pinyinStr = "";
        char[] newChar = chinese.toCharArray();
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        for (int i = 0; i < newChar.length; i++) {
            if (newChar[i] > 128) {
                try {
                    pinyinStr += PinyinHelper.toHanyuPinyinStringArray(newChar[i], defaultFormat)[0];
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    e.printStackTrace();
                }
            }else{
                pinyinStr += newChar[i];
            }
        }
        return pinyinStr;
    }

    //图片转化成base64字符串
    public static String GetImageStr(String imgFile) {
        //将图片文件转化为字节数组字符串，并对其进行Base64编码处理
        InputStream in = null;
        byte[] data = null;
        //读取图片字节数组
        try
        {
            in = new FileInputStream(imgFile);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        //对字节数组Base64编码
        return Base64.encodeBase64String(data);
    }

    /**
     *
     * 审核通过 或不通过发送短信提示
     */

    private String sendMessage(String name,String phone,String gtname,String sendback)throws Exception {
        String info = null;
        try{

            //公司短信发送
            String url= "http://api.sms.cn/sms/";
            String parme="";
            if(sendback!=null){
                parme="ac=send&uid=qxspj&pwd=8d18d2eb316841db0998eeb67362ba4c&mobile="+phone
                        + "&content=" + name + "您好:您申请的个体工商户《"+gtname+"》审核未通过。原因:" + sendback + "【"+Global.getCityName()+"行政审批局】";
            }else{
                parme="ac=send&uid=qxspj&pwd=8d18d2eb316841db0998eeb67362ba4c&mobile="
                        + phone + "&content=" + name + "您好:您申请的个体工商户《"+gtname+"》审核通过,请及时打印营业执照【"+Global.getCityName()+"行政审批局】";
            }
            String result= HttpUtils.sendGet(url,parme);
            System.err.println(result);


        /*//矿区短信发送
        HttpClient httpclient = new HttpClient();
            PostMethod post = new PostMethod("http://api.ums86.com:8899/sms/Api/Send.do");//
            post.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "gbk");
            post.addParameter("SpCode", "247007");
            post.addParameter("LoginName", "jxxzspj");
            post.addParameter("Password", "kqxzspj147");
        if(sendback==null) {
            post.addParameter("MessageContent", name + "您好:您申请的个体工商户《" + gtname + "》审核通过,请及时打印营业执照。");
            post.addParameter("UserNumber", phone);
            post.addParameter("SerialNumber", "");
            post.addParameter("ScheduleTime", "");
            post.addParameter("f", "1");
        }else{
            post.addParameter("MessageContent", name + "您好:您申请的个体工商户《" + gtname + "》审核未通过,原因："+sendback);
            post.addParameter("UserNumber", phone);
            post.addParameter("SerialNumber", "");
            post.addParameter("ScheduleTime", "");
            post.addParameter("f", "1");
        }
        httpclient.executeMethod(post);
        info = new String(post.getResponseBody(),"gbk");
        System.out.println(info);*/



        }catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }




    /**
     * 下载档案 页面
     */
    @GetMapping( "/download/{id}")
    public String download (@PathVariable("id")String id,Model model)
    {
        System.err.println("下载:"+id);
        model.addAttribute("id", id);
        model.addAttribute("gtgsyw",gtgsywMapper.selectById(Long.valueOf(id)));
        return prefix+"/download.html";
    }
    private static String strNetImageToBase64;
    public static String getImg(String urlgs){
        final ByteArrayOutputStream data = new ByteArrayOutputStream();
        try {
            // 创建URL
            URL url = new URL(urlgs);
            final byte[] by = new byte[1024];
            // 创建链接
            final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
            try {
                InputStream is = conn.getInputStream();
                // 将内容读取内存中
                System.err.println(111);
                int len = -1;
                while ((len = is.read(by)) != -1) {
                    data.write(by, 0, len);
                }
                System.err.println(222);
                // 对字节数组Base64编码
                BASE64Encoder encoder = new BASE64Encoder();
                strNetImageToBase64 = encoder.encode(data.toByteArray());
                System.out.println("网络图片转换Base64:" + strNetImageToBase64);
                // 关闭流
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return  strNetImageToBase64;
//            InputStream is =conn.getInputStream();
//            int len=-1;
//
//            while ((len=is.read(by))!=-1)
//            {
//                data.write(by,0,len);
//            }
//            is.close();
//
//            BASE64Encoder encoder = new BASE64Encoder();
//            return  encoder.encode(data.toByteArray());
        //strNetImageToBase64 = encoder.encode(data.toByteArray());
    }
  /*  /// <summary>
    /// 获取网络图片输出为Base64
    /// </summary>
    /// <param name="aPhotoUrl">图片url</param>
    private String GetPhotoInfo(String PeId)
    {
        try
        {
            // PeId = PeId.Substring(0, 6) + "00" + PeId.Substring(11, PeId.Length - 12) + "G";
            // string aPhotoUrl = Global.getConfig("ruoyi.gsdz")+":8005/gtdj/licence.do?method=toTowDimCode&appNo=&peId=" + PeId + "&certTypeId=42";
            //string aPhotoUrl = Global.getConfig("ruoyi.gsdz")+":8005/gtdj/licence.do?method=toTowDimCode&appNo=&uniScid=" + PeId + "&certTypeId=42";
            String aPhotoUrl = Global.getConfig("ruoyi.gsdz")+":8005/gtdj/licence.do?method=toTowDimCode&appNo=&uniScid=" + PeId + "&certTypeId=41";
            //string aPhotoUrl = "http://121.28.134.43:9001/Code.png";
            WebRequest myrequest = WebRequest.Create(aPhotoUrl);
            WebResponse myresponse = myrequest.GetResponse();
            Stream imgstream = myresponse.GetResponseStream();
            System.Drawing.Image img = System.Drawing.Image.FromStream(imgstream);
            //img.Save(Server.MapPath("test.jpg"),System.Drawing.Imaging.ImageFormat.Jpeg);
            MemoryStream ms = new MemoryStream();
            img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            response.ClearContent(); //需要输出图象信息 要修改HTTP头
            Response.ContentType = "image/png";
            //Response.BinaryWrite(ms.ToArray());
            String BaseCode = Convert.ToBase64String(ms.ToArray());
            return BaseCode;
        }
        catch (Exception e)
        {
            return null;
            //Response.Write(e.ToString());
        }
    }
*/
    /**
     * 访问页面返回二维码
     * @param xycod 信用代码
     * @return
     */
    public String QRcode(String xycod,HttpServletResponse response){
        String result="";
        BufferedReader in = null;
        try {
            String url=Global.getConfig("ruoyi.gsdz")+":8005/gtdj/licence.do?method=toTowDimCode&appNo=&uniScid=" + xycod + "&certTypeId=41";
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            connection.setRequestProperty("Content-type","image/png");
            new MimeType("Content-type:image/png");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                System.err.println("line:"+line);
                result += line;
            }
        } catch (Exception  e) {
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }
    /**
     * 导出单个word
     * @param id
     * @param down
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @GetMapping("/test/toWord")
    public ModelAndView toWord(@RequestParam("id") String id ,String down,HttpServletRequest request, HttpServletResponse response) throws IOException{
        System.err.println("id:"+id);
        System.err.println("down:"+down);
        File file = gtgsywService.createDoc(id,down);
        System.err.println("file:"+file);
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("UTF-8");
        java.io.BufferedInputStream bis = null;
        java.io.BufferedOutputStream bos = null;
        try {
            long fileLength = file.length();
            response.setContentType("application/msword");
            if(down.equals("1")){
                response.setHeader("Content-disposition", "attachment; filename="
                        + URLEncoder.encode("准予登记通知书.doc", "utf-8"));
            }else if (down.equals("2")){
                response.setHeader("Content-disposition", "attachment; filename="
                        + URLEncoder.encode("封皮.doc", "utf-8"));
            }else if (down.equals("3")){
                response.setHeader("Content-disposition", "attachment; filename="
                        + URLEncoder.encode("申请书.doc", "utf-8"));
            }else if (down.equals("4")){
                response.setHeader("Content-disposition", "attachment; filename="
                        + URLEncoder.encode("个体工商户党建情况统计表.doc", "utf-8"));
            }else if (down.equals("5")){
                response.setHeader("Content-disposition", "attachment; filename="
                        + URLEncoder.encode("审批事项告知承诺书.doc", "utf-8"));
            }else if (down.equals("6")) {
                response.setHeader("Content-disposition", "attachment; filename="
                        + URLEncoder.encode("住所（经营场所）信息申报表.doc", "utf-8"));
            }
            response.setHeader("Content-Length", String.valueOf(fileLength));
            bis = new BufferedInputStream(new FileInputStream(file));
            bos = new BufferedOutputStream(response.getOutputStream());
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {bis.close();}
            if (bos != null) {bos.close();}
        }
        System.err.println("下载完成");
        return null;
    }

    /**
     *
     * 导出zip压缩包
     * @param id
     * @param down
     * @param request
     * @param response
     * @return
     * @throws IOException
     *
     */
    @GetMapping("/test/toWordZip")
    public ModelAndView toWordZip(@RequestParam("id") String id ,String[] down,HttpServletRequest request, HttpServletResponse response) throws IOException{
        File file = null;
        File zipfile=null;
        File directory=null;
        InputStream fin = null;
        ServletOutputStream out = null;
        Gtgsyw gt=gtgsywMapper.selectById(Long.valueOf(id));
        java.io.BufferedInputStream bis = null;
        java.io.BufferedOutputStream bos = null;
        try {
            Configuration configuration = null;
            if(configuration==null){
                configuration = new Configuration(Configuration.VERSION_2_3_23);
                configuration.setDefaultEncoding("utf-8");
                configuration.setClassForTemplateLoading(this.getClass(), "");
            }
            out = response.getOutputStream();
            gt.setCodeName(gt.getNsxzq()+gt.getZwzh()+gt.getMingchenghangye()+gt.getZuzhixingshi());
            String path=null;
            if(!gt.getZwzh().equals("***")){
                path=Global.getDownloadPath()+"/"+gt.getCodeName();
            }else{
                path=Global.getDownloadPath()+"/无字号";
            }

            directory=new File(path);
            directory.mkdirs();
            for(int i=1;i<down.length+1;i++){
                String name="";
                if(i==1){
                    name="6.准予登记通知书";
                }else if (i==2){
                    name="1.封皮";
                }else if(i==3){
                    name="2.申请书";
                }else if(i==4){
                    name="4.个体工商户党建情况统计表";
                }else if(i==5){
                    name="5.审批事项告知承诺书";
                }else if(i==6){
                    name="3.住所（经营场所）信息申报表";
                }
                file = gtgsywService.MulticreateDoc(id,i+"",directory.getPath()+"/"+name+".doc");
            }
            //压缩目录
            ZipUtil.createZip(path, path+"zip.zip");
            //根据路径获取刚生成的zip包文件
            zipfile=new File(path+"zip.zip");
            response.setHeader("Content-disposition", "attachment; filename="
                    + URLEncoder.encode(gt.getCodeName()+".zip", "utf-8"));
            fin=new FileInputStream(zipfile);
            byte[] buffer = new byte[512]; // 缓冲区
            int bytesToRead = -1;
            // 通过循环将读入的Word文件的内容输出到浏览器中
            while ((bytesToRead = fin.read(buffer)) != -1) {
                out.write(buffer, 0, bytesToRead);
            }
        } catch (Exception e) {
            System.err.println("出错");
            e.printStackTrace();
        } finally {
            try {
                if (fin!=null) {fin.close();}
                if (out!=null) {out.close();}
                if (zipfile!=null) {zipfile.delete();}
                if (directory!=null) {
                    //递归删除目录及目录下文件
                    ZipUtil.deleteFile(directory);
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        System.err.println("下载完成");
        return null;
    }



    /**
     *
     * 导出zip压缩包
     * @param id
     * @param down
     * @param request
     * @param response
     * @return
     * @throws IOException
     *
     */
    @GetMapping("/test/toZip")
    public ModelAndView tozip(@RequestParam("id") String id ,String[] down,HttpServletRequest request, HttpServletResponse response) throws IOException{

        gtgsywService.downloadZip(id,down,request,response);
        System.err.println("下载完成");
        return null;
    }



    /**
     * 下载某个时间段之内的所有zip
     * @return
     */
    @GetMapping("/toPdfZip")
    public void topdf(@RequestParam("start") String start, @RequestParam("end")String end, HttpServletRequest request, HttpServletResponse response) throws IOException{


        gtgsywService.downloadMonthZip( start,end,request,response);
    }



    /**
     * 行业树形结构
     * @return
     */
    @GetMapping("/selectTrade")
    @ResponseBody
    public List<Ztree> treeTrade() {
        System.err.println("下拉选");
        List<Ztree> ztrees = gtgsywService.selectTradeTree();
        return ztrees;
    }
    //添加便捷语
    @PostMapping("/addeasy")
    @ResponseBody
    public AjaxResult addeasy( String add)
    {
        System.err.println("添加便捷语add:"+add);
        return toAjax(gtgsywService.addeasy(add));
    }
    /**
     * 树形数据 页面
     * @return
     */
    @GetMapping("/selectDept")
    public String selectDeptTree() {
        System.err.println("进来了");
        return prefix + "/bmtree.html";
    }



    /**
     * 同步txt文件
     */
    @GetMapping("/gtDateSysc")
    @ResponseBody
    public AjaxResult gtDateSysc(@RequestParam("id") String id,HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.err.println("导出txt文件Gtgsyw:"+id);
        String filePath = "C://WuZiHao.txt";//无字号
        String filePath1 = "C://YouZiHao.txt";//有字号
        String xzqdm=Global.getConfig("ruoyi.sjqhdm");//行政区代码
        String xzqdm1=Global.getConfig("ruoyi.qhdm");//行政区代码
        String postCode=Global.getConfig("ruoyi.cityPostcode");//邮政编码
        Integer ismc=null;
        //根据id查询gtgsyw 所有信息
        Gtgsyw gt=gtgsywMapper.selectGtgsywById(Long.valueOf(id));
        SysUser user = ShiroUtils.getSysUser();
        GtgsYwUser gtgsYwUser=gtgsYwUserService.selectGtgsYwUserByRemark(user.getRemark());
        if(gtgsYwUser == null){
            return error("该账号未绑定工商户籍账号");
        }
        //经营人出生年月日
        String  Birthday="";
        if(gt.getJingyingcard()!=null && gt.getJingyingcard().equals("")){
            String year=gt.getJingyingcard().substring(6, 10);
            String month = gt.getJingyingcard().substring(10, 12);
            String date = gt.getJingyingcard().substring(12, 14);
            Birthday = year + "-" + month + "-" + date;
        }
        //
        String identity="01";
        if(gt.getZyzk().equals("待业")){
            identity="03";
        }else{
            identity="01";
        }
        //是否是党员
        int background=13;
        if(gt.getZzmm().equals("党员")){
            background=01;
        }else {
            background=13;
        }
        //个体工商户信息
        String Name="";
        if(gt.getZwzh().equals("***")){
            Name=gt.getZwzh();
        }else{
            Name= Global.getCityName() +gt.getZwzh()+gt.getMingchenghangye()+gt.getZuzhixingshi();
        }
        String xingbie=null;
        if(gt.getXingbie().equals("男")){
            xingbie="1";
        }else {
            xingbie="2";
        }
        if(gt.getZwzh().equals("***")){
            ismc=0;
        }else{
            ismc=1;
        }
        //经营场所属于
        String jycssy="";
        if(gt.getJycssy()==1){
            jycssy="非住宅";
        }else if(gt.getJycssy()==2){
            jycssy="住宅";
        }
        String uuid= UUID.randomUUID().toString().replace("-","");

        System.err.println("uuid:"+uuid);
        String userDetail="&loginName="+gtgsYwUser.getUsername()+"&password="+gtgsYwUser.getPassword()+"&authId="+
                gtgsYwUser.getAuthid()+"&loginDeptId="+gtgsYwUser.getDetpid()+"&loginUserId="+gtgsYwUser.getUserid();
        System.err.println(userDetail);
        String str="";
        String zwzh=gt.getZwzh();
        if(!gt.getZwzh().equals("***")){
            zwzh=Global.getCityName()+zwzh+gt.getMingchenghangye()+gt.getZuzhixingshi();
        }
        str +="ismc=0&";
        str += "flowId=450011&appTypeId=02&appCaseType=020601&appNo=&ifTempSave=1" +
                "&temp-date=" + URLEncoder.encode(getNowDate(gt.getShenqingdate()), "utf-8");
        //提交的材料
        str += "&peAppendixHandinSwitch=on&handIn=1&peAppendixId=&appendixId=020000&appendixName="+URLEncoder.encode("个体工商户设立登记申请书","utf-8")+"&receiveDate=" + URLEncoder.encode(getNowDate(gt.getShenqingdate()),"utf-8");
        str += "&peAppendixHandinSwitch=on&handIn=1&peAppendixId=&appendixId=020001&appendixName="+URLEncoder.encode("设立登记审核表","utf-8")+"&receiveDate=" + URLEncoder.encode(getNowDate(gt.getShenqingdate()),"utf-8");
        str += "&peAppendixHandinSwitch=on&handIn=1&peAppendixId=&appendixId=020002&appendixName="+URLEncoder.encode("经营场所证明及附件","utf-8")+"&receiveDate=" + URLEncoder.encode(getNowDate(gt.getShenqingdate()),"utf-8");
        str += "&peAppendixHandinSwitch=on&handIn=1&peAppendixId=&appendixId=020006&appendixName="+URLEncoder.encode("名称预先核准通知书（经名称预先核准的须提交）","utf-8")+"&receiveDate=" + URLEncoder.encode(getNowDate(gt.getShenqingdate()),"utf-8");
        str += "&peAppendixHandinSwitch=on&handIn=1&peAppendixId=&appendixId=020004&appendixName="+URLEncoder.encode("个体工商户身份证明复印件","utf-8")+"&receiveDate=" + URLEncoder.encode(getNowDate(gt.getShenqingdate()),"utf-8");
        str += "&peAppendixHandinSwitch=on&handIn=1&peAppendixId=&appendixId=020005&appendixName="+URLEncoder.encode("个体工商户登记委托代理人证明","utf-8")+"&receiveDate=" + URLEncoder.encode(getNowDate(gt.getShenqingdate()),"utf-8");
        str += "&peAppendixHandinSwitch=on&handIn=1&peAppendixId=&appendixId=020003&appendixName="+URLEncoder.encode("前置审批的批准文件、许可证或许可证明","utf-8")+"&receiveDate=" + URLEncoder.encode(getNowDate(gt.getShenqingdate()),"utf-8");
        str += "&peAppendixHandinSwitch=on&handIn=1&peAppendixId=&appendixId=020007&appendixName="+URLEncoder.encode("设立需提交的其他材料","utf-8")+"&receiveDate=" + URLEncoder.encode(getNowDate(gt.getShenqingdate()),"utf-8");
        //委托人信息
        str += "&cetfNoApplyQuery=&applicantName=&peId=&agentbiaoSiNameChecked=&agent=&uuid="+URLEncoder.encode(uuid,"utf-8")+"&telephoneApply=&mobileApply=&cetfTypeApply=&cetfTypeShApply=&cetfNoApply=&agentPerson=&linkmanQQ=&appMode=1" +
                "&approveDateCompare=&licenAcceptType=&recipientType=&postcode=&recipientAddress=";
        str += "&nameTrad=&sponsorType=4&tradPiny=&peName=" +URLEncoder.encode(zwzh,"utf-8") + "&nameId=&directAccept=1&directAcceptClick=&nameAppNo=&regNo=&peTypeId=1&validPeType=&totalPersn="
                + URLEncoder.encode(String.valueOf(gt.getCongyerenshu()),"utf-8") + "&unemploymentNum=&offJobNum=&cptlTotal=" + URLEncoder.encode(gt.getZijinshue(),"utf-8") + "&areaId="+URLEncoder.encode(xzqdm,"utf-8")+"&country="+URLEncoder.encode(xzqdm1,"utf-8")+"&streetName=&neigbor=&road=";
        str += "&addressBase=" + URLEncoder.encode(gt.getJingyingchangsuo(),"utf-8") + "&telephone=" + URLEncoder.encode(gt.getJingyingrenphone(),"utf-8") + "&postcodeBase="+URLEncoder.encode(postCode, "utf-8")+"&equities=02&fjArea=";
        str += "&cityFlag=1&areaOrganId1="+ URLEncoder.encode(xzqdm,"utf-8") +"&areaOrganId2="+ URLEncoder.encode(xzqdm1,"utf-8") +"&areaOrganId3=&areaOrganId="+ URLEncoder.encode(xzqdm1,"utf-8") +"&region=&licenseTypeZB=1";
        str += "&licZbCnt=1&licenseTypeFB=1&licFbCnt=1&archivesNo=&isProvideDzyyzz=1&licCardCnt=1&memoBase=";
        str += "&industryCode111=&industryPhy=&industryCode1=&industryCode=&industryCode22=&validTradeScope=&industryCode2=&industryCode3=&foodTrdTypeId=9900";
        str += "&trdScope=" + URLEncoder.encode(gt.getJingyingfanwei(),"utf-8") + "&dzhyAppNo=&estPartyFlag=2&estPartyTime=&partyNum=&leaderSign=2&viewEstPartyOldValue=null";
        str += "&persnNameOperator=" + URLEncoder.encode(gt.getJingyingren(),"utf-8") + "&persnNameChecked="+URLEncoder.encode(gt.getJingyingren(),"utf-8")+";"+gt.getJingyingcard()+"&uuid="+URLEncoder.encode(uuid,"utf-8")+"&fjPersonType=01" +
                "&nationalityId=&identityType=&cetfTypeOperator=1&cetfTypeShOperator=&cetfNoOperator=" + URLEncoder.encode(gt.getJingyingcard(),"utf-8") + "&sexIdOperator=" + URLEncoder.encode(xingbie,"utf-8") + "&birthdayOperator=" + URLEncoder.encode(Birthday,"utf-8");
        str += "&nationId=01&educationId=&identityProof=&identityFileName=&identityFileNo=&cetfIssueDate=&cerDateStart=&cerDateEnd=&notOrg=&notDocNo=&identityId=03&backgroundId=" + URLEncoder.encode(String.valueOf(background),"utf-8")+
                "&addressOperator=" + URLEncoder.encode(gt.getJiatingzhuzhi(),"utf-8") + "&mobileOperator=" + URLEncoder.encode(gt.getJingyingrenphone(),"utf-8") + "&telephoneOperator=&postcodeOperator="+URLEncoder.encode(postCode, "utf-8")+"&mail="+URLEncoder.encode("无","utf-8");
        str += "&memoOperator=&practitionTemp=&practitionCetfType=&practitionCetfId=&permitInfoTemp=&permitFileTemp=&organId="+ URLEncoder.encode(xzqdm1,"utf-8") +"";
        str += "&staffName="+URLEncoder.encode(gtgsYwUser.getName(),"utf-8")+"&userId="+gtgsYwUser.getUserid()+"&deptId="+gtgsYwUser.getDetpid()+"&subscriptionDate=" + URLEncoder.encode(getDate(gt.getShenqingdate()),"utf-8") +
                "&statusId=&preStatusId=null&actnId=4501&resultId=01&realOrgan=&rejectFile=&acceptNotice=01&textOpnn=&tokenDate=&ismc=0"+userDetail;
      /*  }else{

            str += "nameApp.nameType=5&nameApp.appType=000010&nameApp.appNo=&operType=11&nameInfo.isBranch=0&nameApp.lockVersion=&changeItems=&nameApp.groupAppNo=&btnVal=";
            str += "&nameBanJson=";
            str += "&nameEntyQueryJson=&nameAppQueryJson=";
            str += "&industryPhyStr=&industryCodeStr=&nameBanJsonGroup=&nameEntyQueryJsonGroup=&nameAppQueryJsonGroup=&easyNameType=";
            //有字号个体户信息
            str += "&nameInfo.sponsorType=4&nameInfo.indDistrictType=&nameInfo.nameDistrict="+ URLEncoder.encode(Global.getCityName(), "utf-8")+"&nameInfo.nameTrad=" + URLEncoder.encode(gt.getZwzh(), "utf-8") + "&nameInfo.nameId=";
            str += "&nameBackupList[0].nameTrad=" + URLEncoder.encode(gt.getZwzh1(), "utf-8") + "&nameBackupList[0].tradPiny=";
            str += "&nameBackupList[1].nameTrad=" + URLEncoder.encode(gt.getZwzh2(), "utf-8") + "&nameBackupList[1].tradPiny=";
            str += "&nameBackupList[2].nameTrad=" + URLEncoder.encode(gt.getZwzh3(), "utf-8") + "&nameBackupList[2].tradPiny=";
            str += "&ifChecked=0&ifCheckedGroup=1";
            str += "&nameInfo.tradPiny=&nameInfo.indDesc=" + URLEncoder.encode(gt.getMingchenghangye(), "utf-8") + "&nameOther.indPhy=&nameOther.industryCode=&industryCodeTest=&nameInfo.nameInd=&indPhyArrs=&industryCodeArrs=&nameInfo.nameOrgForm=" + URLEncoder.encode(gt.getZuzhixingshi(), "utf-8") + "&nameInfo.etpsName=" + URLEncoder.encode(Name, "utf-8") + "&nameInfoEnty.nameId=";
            str += "&nameInfo.regOrgan="+URLEncoder.encode(xzqdm1, "utf-8")+"&nameInfo.apoOrgan="+URLEncoder.encode(xzqdm1, "utf-8")+"&nameInfo.threadId=5&nameInfo.subObjType=00&nameInfo.etpsType=9500&nameOther_firstNameDistrict="+URLEncoder.encode(xzqdm, "utf-8")+"&nameOther_secondNameDistrict="+URLEncoder.encode(xzqdm1, "utf-8")+"&nameOther.addressDistrict="+URLEncoder.encode(xzqdm1, "utf-8");
            str += "&nameInvestorList[0].invtName=" + URLEncoder.encode(gt.getJingyingren(), "utf-8") + "&ftz="+URLEncoder.encode(gt.getJingyingchangsuo().replace("河北省石家庄市",""), "utf-8")+"&nameOther.address=" + URLEncoder.encode(gt.getJingyingchangsuo().replaceAll("河北省石家庄市", ""), "utf-8") + "&nameInfo.orgForm=1&nameOther.phone=" + URLEncoder.encode(gt.getJingyingrenphone(), "utf-8") + "&nameOther.postcode=&nameInvestorList[0].cetType=1&nameInvestorList[0].cetId=" + URLEncoder.encode(gt.getJingyingcard(), "utf-8") + "";
            str += "&nameInvestorList[0].nationalityId=&nameInvestorList[0].identityType=&nameInvestorList[0].cerDateStart=&nameInvestorList[0].cerDateEnd=&nameInvestorList[0].identityProof=&nameInvestorList[0].identityFileName=&nameInvestorList[0].identityFileNo=&nameInvestorList[0].cetfIssueDate=&nameInvestorList[0].notOrg=&nameInvestorList[0].notDocNo=";
            str += "&nameOther.cptlTotal=" + URLEncoder.encode(gt.getZijinshue(), "utf-8") + "&nameOther.trdScope=" + URLEncoder.encode(gt.getJingyingfanwei(), "utf-8") + "&nameInfo.memo=&appendixTemp=";
            str += "&nameAppendixVoList[0].appendixUid=&nameAppendixVoList[0].appendixName="+URLEncoder.encode("个体工商户名称预先核准申请书", "utf-8")+"&nameAppendixVoList[0].subDate=" + URLEncoder.encode(getNowDate(gt.getShenqingdate()), "utf-8") + "";
            str += "&nameAppendixVoList[1].appendixUid=&nameAppendixVoList[1].appendixName="+URLEncoder.encode("指定代表或者委托代理人的证明", "utf-8")+"&nameAppendixVoList[1].subDate=" + URLEncoder.encode(getNowDate(gt.getShenqingdate()), "utf-8") + "";
            str += "&nameAppendixVoList[2].appendixUid=&nameAppendixVoList[2].appendixName="+URLEncoder.encode("经营者的身份证复印件", "utf-8")+"&nameAppendixVoList[2].subDate=" + URLEncoder.encode(getNowDate(gt.getShenqingdate()), "utf-8") + "";
            str += "&nameAppendixVoList[3].appendixUid=&nameAppendixVoList[3].appendixName="+URLEncoder.encode("经营者签署的《委托代理人证明》及委托代理人身份证复印件", "utf-8")+"&nameAppendixVoList[3].subDate=" + URLEncoder.encode(getNowDate(gt.getShenqingdate()), "utf-8") + "";
            str += "&nameAppendixVoList[4].appendixUid=&nameAppendixVoList[4].appendixName="+URLEncoder.encode("特殊的申请名称，名称登记机关可以要求投资人提交相关的说明或者证明材料", "utf-8")+"&nameAppendixVoList[4].subDate=" + URLEncoder.encode(getNowDate(gt.getShenqingdate()), "utf-8") + "";
            str += "&nameApp.appMode=1&nameApp.appDate=" + URLEncoder.encode(getNowDate(gt.getShenqingdate()), "utf-8") + "&nameApp.ifNet=0&nameApp.agentName=&nameApp.phone=&nameApp.mobilePhone=&nameApp.cetfType=&nameApp.cetfId=&nameAppNode.result=&nameAppNode.preStatusDate=" + URLEncoder.encode(getNowDate(gt.getShenqingdate()), "utf-8") + "&nameAppNode.memo="+URLEncoder.encode("申请材料齐全，符合法定形式，拟同意受理，请领导审批。", "utf-8")+"&nameApp.opinion="+URLEncoder.encode("申请材料齐全，符合法定形式，拟同意受理，请领导审批。", "utf-8")+
                    "&ismc="+ismc+userDetail;
        }*/
        logger.debug(str);
        String msg = "";
        try {
            msg = HttpUtils.sendPost(Global.getConfig("ruoyi.pyip")+"/selectInfo",str);
        } catch (RuntimeException e){
            logger.error("请求出错："+e);
        }
        System.err.println(msg);
        try{
            Map map = (Map) JSONUtils.parse(msg);
            if(map.get("code").equals("0")){
                return AjaxResult.success("同步成功!");
            }else {
                return AjaxResult.error("同步中");
            }
        }catch (RuntimeException e){
            logger.error("转换json返回值出错：",e);
        }finally{
            return success("同步成功!");
        }


    }


    /**
     * 同步txt文件
     */
    @GetMapping("filetxt")
    @ResponseBody
    public AjaxResult writeFile(@RequestParam("id") String id,HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.err.println("导出txt文件Gtgsyw:"+id);
        String filePath = "C://WuZiHao.txt";//无字号
        String filePath1 = "C://YouZiHao.txt";//有字号
        String xzqdm="130100";//行政区代码
        String xzqdm1="130107";//行政区代码
        //根据id查询gtgsyw 所有信息
        Gtgsyw gt=gtgsywMapper.selectGtgsywById(Long.valueOf(id));
        //经营人出生年月日
        String  Birthday="";
        if(gt.getJingyingcard()!=null && gt.getJingyingcard().equals("")){
            String year=gt.getJingyingcard().substring(6, 10);
            String month = gt.getJingyingcard().substring(10, 12);
            String date = gt.getJingyingcard().substring(12, 14);
            Birthday = year + "-" + month + "-" + date;
        }
        //
        String identity="01";
        if(gt.getZyzk().equals("待业")){
            identity="03";
        }else{
            identity="01";
        }
        //是否是党员
        int background=13;
        if(gt.getZzmm().equals("党员")){
            background=01;
        }else {
            background=13;
        }
        //个体工商户信息
        String Name="";
        if(gt.getZwzh().equals("***")){
            Name=gt.getZwzh();
        }else{
            Name= Global.getCityName() +gt.getZwzh()+gt.getMingchenghangye()+gt.getZuzhixingshi();
        }
        String xingbie=null;
        if(gt.getXingbie().equals("男")){
            xingbie="1";
        }else {
            xingbie="2";
        }
        //经营场所属于
        String jycssy="";
        if(gt.getJycssy()==1){
            jycssy="非住宅";
        }else if(gt.getJycssy()==2){
            jycssy="住宅";
        }
        String uuid= UUID.randomUUID().toString().replace("-","");
        AjaxResult aj = null;


        System.err.println("uuid:"+uuid);
        String str="";
        if(gt.getZwzh().equals("***")){
            str += "flowId=450011&appTypeId=02&appCaseType=020601&appNo=&ifTempSave=1&temp-date=" + getNowDate(gt.getShenqingdate());
            //提交的材料
            str += "&peAppendixHandinSwitch=on&handIn=1&peAppendixId=&appendixId=020000&appendixName=个体工商户设立登记申请书&receiveDate=" + getNowDate(gt.getShenqingdate());
            str += "&peAppendixHandinSwitch=on&handIn=1&peAppendixId=&appendixId=020001&appendixName=设立登记审核表&receiveDate=" + getNowDate(gt.getShenqingdate());
            str += "&peAppendixHandinSwitch=on&handIn=1&peAppendixId=&appendixId=020002&appendixName=经营场所证明及附件&receiveDate=" + getNowDate(gt.getShenqingdate());
            str += "&peAppendixHandinSwitch=on&handIn=1&peAppendixId=&appendixId=020006&appendixName=名称预先核准通知书（经名称预先核准的须提交）&receiveDate=" + getNowDate(gt.getShenqingdate());
            str += "&peAppendixHandinSwitch=on&handIn=1&peAppendixId=&appendixId=020004&appendixName=个体工商户身份证明复印件&receiveDate=" + getNowDate(gt.getShenqingdate());
            str += "&peAppendixHandinSwitch=on&handIn=1&peAppendixId=&appendixId=020005&appendixName=个体工商户登记委托代理人证明&receiveDate=" + getNowDate(gt.getShenqingdate());
            str += "&peAppendixHandinSwitch=on&handIn=1&peAppendixId=&appendixId=020003&appendixName=前置审批的批准文件、许可证或许可证明&receiveDate=" + getNowDate(gt.getShenqingdate());
            str += "&peAppendixHandinSwitch=on&handIn=1&peAppendixId=&appendixId=020007&appendixName=设立需提交的其他材料&receiveDate=" + getNowDate(gt.getShenqingdate());
            //委托人信息
            str += "&cetfNoApplyQuery=&applicantName=&peId=&agentbiaoSiNameChecked=&agent=&uuid="+uuid+"&telephoneApply=&mobileApply=&cetfTypeApply=&cetfTypeShApply=&cetfNoApply=&agentPerson=&linkmanQQ=&appMode=1&=&=&approveDateCompare=&licenAcceptType=&recipientType=&postcode=&recipientAddress=";
            str += "&nameTrad=&sponsorType=4&tradPiny=&peName=" + gt.getZwzh() + "&nameId=&directAccept=1&directAcceptClick=&nameAppNo=&regNo=&peTypeId=1&validPeType=&totalPersn=" + gt.getCongyerenshu() + "&unemploymentNum=&offJobNum=&cptlTotal=" + gt.getZijinshue() + "&areaId="+xzqdm+"&country="+xzqdm1+"&streetName=&neigbor=&road=";
            str += "&addressBase=" + gt.getJingyingchangsuo() + "&telephone=" + gt.getJingyingrenphone() + "&postcodeBase=050000&equities=02&fjArea=";//&cityFlag=1
            str += "&cityFlag=1&areaOrganId1="+ xzqdm +"&areaOrganId2="+ xzqdm1 +"&areaOrganId3=&areaOrganId="+ xzqdm1 +"&region=&licenseTypeZB=1";
            str += "&licZbCnt=1&licenseTypeFB=1&licFbCnt=1&archivesNo=&isProvideDzyyzz=1&licCardCnt=1&memoBase=";
            str += "&industryCode111=&industryPhy=&industryCode1=&industryCode=&industryCode22=&validTradeScope=&industryCode2=&industryCode3=&foodTrdTypeId=9900";
            str += "&trdScope=" + gt.getJingyingfanwei() + "&dzhyAppNo=&estPartyFlag=2&estPartyTime=&partyNum=&leaderSign=2&viewEstPartyOldValue=null";
            str += "&persnNameOperator=" + gt.getJingyingren() + "&persnNameChecked="+gt.getJingyingren()+";"+gt.getJingyingcard()+"&uuid="+uuid+"&fjPersonType=01&nationalityId=&identityType=&cetfTypeOperator=1&cetfTypeShOperator=&cetfNoOperator=" + gt.getJingyingcard() + "&sexIdOperator=" + xingbie + "&birthdayOperator=" + Birthday + "";
            str += " &nationId=01&educationId=&identityProof=&identityFileName=&identityFileNo=&cetfIssueDate=&cerDateStart=&cerDateEnd=&notOrg=&notDocNo=&identityId=03&backgroundId=" + background + "&addressOperator=" + gt.getJiatingzhuzhi() + "&mobileOperator=" + gt.getJingyingrenphone() + "&telephoneOperator=&postcodeOperator=050000&mail=无";
            str += "&memoOperator=&practitionTemp=&practitionCetfType=&practitionCetfId=&permitInfoTemp=&permitFileTemp=&organId="+ xzqdm1 +"";
            str += "&staffName=张凌&userId=a0a0e3995a3c0143015a4593169a0060&deptId=13010800025&subscriptionDate=" + getDate(gt.getShenqingdate()) + "&statusId=&preStatusId=null&actnId=4501&resultId=01&realOrgan=&rejectFile=&acceptNotice=01&textOpnn=&tokenDate=";
            aj = new AjaxResult(AjaxResult.Type.SUCCESS,str);
            aj.put("filename",filePath);
        }else{
            str += "nameApp.nameType=5&nameApp.appType=000010&nameApp.appNo=&operType=11&nameInfo.isBranch=0&nameApp.lockVersion=&changeItems=&nameApp.groupAppNo=&btnVal=";
            str += "&nameBanJson=";
            str += "&nameEntyQueryJson=&nameAppQueryJson=";
            str += "&industryPhyStr=&industryCodeStr=&nameBanJsonGroup=&nameEntyQueryJsonGroup=&nameAppQueryJsonGroup=&easyNameType=";
            //有字号个体户信息
            str += "&nameInfo.sponsorType=4&nameInfo.indDistrictType=&nameInfo.nameDistrict="+Global.getCityName()+"&nameInfo.nameTrad=" + gt.getZwzh() + "&nameInfo.nameId=";
            str += "&nameBackupList[0].nameTrad=" + gt.getZwzh1() + "&nameBackupList[0].tradPiny=";
            str += "&nameBackupList[1].nameTrad=" + gt.getZwzh2() + "&nameBackupList[1].tradPiny=";
            str += "&nameBackupList[2].nameTrad=" + gt.getZwzh3() + "&nameBackupList[2].tradPiny=";
            str += "&ifChecked=0&ifCheckedGroup=1";
            str += "&nameInfo.tradPiny=&nameInfo.indDesc=" + gt.getMingchenghangye() + "&nameOther.indPhy=&nameOther.industryCode=&industryCodeTest=&nameInfo.nameInd=&indPhyArrs=&industryCodeArrs=&nameInfo.nameOrgForm=" + gt.getZuzhixingshi() + "&nameInfo.etpsName=" + Name + "&nameInfoEnty.nameId=";
            str += "&nameInfo.regOrgan="+xzqdm1+"&nameInfo.apoOrgan="+xzqdm1+"&nameInfo.threadId=5&nameInfo.subObjType=00&nameInfo.etpsType=9500&nameOther_firstNameDistrict="+xzqdm+"&nameOther_secondNameDistrict="+xzqdm1+"&nameOther.addressDistrict="+xzqdm1;
            str += "&nameInvestorList[0].invtName=" + gt.getJingyingren() + "&ftz=中国（四川）自由贸易试验区&nameOther.address=" + gt.getJingyingchangsuo() + "&nameInfo.orgForm=1&nameOther.phone=" + gt.getJingyingrenphone() + "&nameOther.postcode=&nameInvestorList[0].cetType=1&nameInvestorList[0].cetId=" + gt.getJingyingcard() + "";
            str += "&nameInvestorList[0].nationalityId=&nameInvestorList[0].identityType=&nameInvestorList[0].cerDateStart=&nameInvestorList[0].cerDateEnd=&nameInvestorList[0].identityProof=&nameInvestorList[0].identityFileName=&nameInvestorList[0].identityFileNo=&nameInvestorList[0].cetfIssueDate=&nameInvestorList[0].notOrg=&nameInvestorList[0].notDocNo=";
            str += "&nameOther.cptlTotal=" + gt.getZijinshue() + "&nameOther.trdScope=" + gt.getJingyingfanwei() + "&nameInfo.memo=&appendixTemp=";
            str += "&nameAppendixVoList[0].appendixUid=&nameAppendixVoList[0].appendixName=个体工商户名称预先核准申请书&nameAppendixVoList[0].subDate=" + getNowDate(gt.getShenqingdate()) + "";
            str += "&nameAppendixVoList[1].appendixUid=&nameAppendixVoList[1].appendixName=指定代表或者委托代理人的证明&nameAppendixVoList[1].subDate=" + getNowDate(gt.getShenqingdate()) + "";
            str += "&nameAppendixVoList[2].appendixUid=&nameAppendixVoList[2].appendixName=经营者的身份证复印件&nameAppendixVoList[2].subDate=" + getNowDate(gt.getShenqingdate()) + "";
            str += "&nameAppendixVoList[3].appendixUid=&nameAppendixVoList[3].appendixName=经营者签署的《委托代理人证明》及委托代理人身份证复印件&nameAppendixVoList[3].subDate=" + getNowDate(gt.getShenqingdate()) + "";
            str += "&nameAppendixVoList[4].appendixUid=&nameAppendixVoList[4].appendixName=特殊的申请名称，名称登记机关可以要求投资人提交相关的说明或者证明材料&nameAppendixVoList[4].subDate=" + getNowDate(gt.getShenqingdate()) + "";
            str += "&nameApp.appMode=1&nameApp.appDate=" + getDate(gt.getShenqingdate()) + "&nameApp.ifNet=0&nameApp.agentName=&nameApp.phone=&nameApp.mobilePhone=&nameApp.cetfType=&nameApp.cetfId=&nameAppNode.result=&nameAppNode.preStatusDate=" + getNowDate(gt.getShenqingdate()) + "&nameAppNode.memo=申请材料齐全，符合法定形式，拟同意受理，请领导审批。&nameApp.opinion=申请材料齐全，符合法定形式，拟同意受理，请领导审批。";
            //流程起始

            aj = new AjaxResult(AjaxResult.Type.SUCCESS,str);
            aj.put("filename",filePath1);
        }
        return aj;
    }




    public static String getNowDate(java.util.Date dateDate) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String dateString = formatter.format(dateDate);
        return dateString;
    }
    public static String getDate(java.util.Date dateDate) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = formatter.format(dateDate);
        return dateString;
    }
    /**
     * 调用对方接口方法
     * @param path 对方或第三方提供的路径
     * @param data 向对方或第三方发送的数据，大多数情况下给对方发送JSON数据让对方解析
     */
    public static void interfaceUtil(String path,String data) {
        try {
            URL url = new URL(path);
            //打开和url之间的连接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            PrintWriter out = null;
            System.err.println(path);
            /**设置URLConnection的参数和普通的请求属性****start***/

            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");

            /**设置URLConnection的参数和普通的请求属性****end***/

            //设置是否向httpUrlConnection输出，设置是否从httpUrlConnection读入，此外发送post请求必须设置这两个
            //最常用的Http请求无非是get和post，get请求可以获取静态页面，也可以把参数放在URL字串后面，传递给servlet，
            //post与get的 不同之处在于post的参数不是放在URL字串里面，而是放在http请求的正文内。
            conn.setDoOutput(true);
            conn.setDoInput(true);

            conn.setRequestMethod("GET");//GET和POST必须全大写
            /**GET方法请求*****start*/
            /**
             * 如果只是发送GET方式请求，使用connet方法建立和远程资源之间的实际连接即可；
             * 如果发送POST方式的请求，需要获取URLConnection实例对应的输出流来发送请求参数。
             * */
            conn.connect();

            /**GET方法请求*****end*/

            /***POST方法请求****start*/

            /*out = new PrintWriter(conn.getOutputStream());//获取URLConnection对象对应的输出流

            out.print(data);//发送请求参数即数据

            out.flush();//缓冲数据
            */
            /***POST方法请求****end*/

            //获取URLConnection对象对应的输入流
            InputStream is = conn.getInputStream();
            //构造一个字符流缓存
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String str = "";
            while ((str = br.readLine()) != null) {
                str=new String(str.getBytes(), StandardCharsets.UTF_8);//解决中文乱码问题
                System.out.println(str);
            }
            //关闭流
            is.close();
            //断开连接，最好写上，disconnect是在底层tcp socket链接空闲时才切断。如果正在被其他线程使用就不切断。
            //固定多线程的话，如果不disconnect，链接会增多，直到收发不出信息。写上disconnect后正常一些。
            conn.disconnect();
            System.out.println("完整结束");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
