package com.ruoyi.system.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.util.StringUtil;
import com.ruoyi.common.config.Global;
import com.ruoyi.common.core.domain.Ztree;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ZipUtil;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.file.WordToPdf;
import com.ruoyi.common.utils.sql.SqlUtil;
import com.ruoyi.system.domain.Gtgsyw;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.domain.Trade;
import com.ruoyi.system.domain.auditTh;
import com.ruoyi.system.mapper.GtgsywMapper;
import com.ruoyi.system.service.IGtgsywService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import net.sf.jsqlparser.expression.StringValue;
import org.jsoup.helper.DataUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.unit.DataUnit;
import sun.misc.BASE64Decoder;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.zip.ZipOutputStream;

import static com.ruoyi.common.utils.ImgUtils.convertFileToBase64;

/**
 * 待审核Service业务层处理
 *
 * @author xu
 * @date 2019-08-22
 */
@Service
public class GtgsywServiceImpl implements IGtgsywService {
    @Autowired
    private GtgsywMapper gtgsywMapper;

    /**
     * 查询待审核
     *
     * @param id 待审核ID
     * @return 待审核
     */
    @Override
    public Gtgsyw selectGtgsywById(Long id) {
        return gtgsywMapper.selectGtgsywById(id);
    }

    /**
     * 根据id查询身份证照片正反面
     *
     * @param id 查询的id
     * @return
     */
    @Override
    public List<String> selectidentityPhoto(String id) {
        return gtgsywMapper.selectidentityPhoto(id);
    }

    /**
     * 查询照片
     * @param bsid
     * @return
     */
    @Override
    public List<Map>  selectPhotosByBsid(String bsid){
        return gtgsywMapper.selectPhotosByBsid(bsid);
    }
/**
     * 根据id查询身份证照片正反面
     *
     * @param id 查询的id
     * @return
     */
    @Override
    public List<Map> selectidentityPhotos(String id) {
        return gtgsywMapper.selectidentityPhotos(id);
    }

    /**
     * //根据id修改状态为审核中
     *
     * @param id
     * @param userId
     * @return
     */
    @Override
    public int updateFlg(Long id, Long userId) {
        //如果当前状态为0(待审核)就修改成3(审核中)
        if (gtgsywMapper.selectById(id).getFlg() == 0) {
            return gtgsywMapper.updateFlg(id.toString(), gtgsywMapper.selectUserName(userId),userId+"");
        } else {
            return 0;
        }

    }


    /**
     * 查询待审核列表
     *
     * @param gtgsyw 待审核
     * @return 待审核
     */
    @Override
    public List<Gtgsyw> selectGtgsywList(Gtgsyw gtgsyw) {
        //当前登录管理员的名字
        gtgsyw.setEcode(gtgsywMapper.selectUserName(gtgsyw.getId()));
        startPage();
        //判断当前登录人是否是超级管理员
        //是:查看所有审核中的商户
        //否:只看自己审核中的商户
        if(!gtgsyw.getHangye2().equals("")) {
            String Seime = gtgsyw.getHangye1() + " 00:00:00";
            String Eeime = gtgsyw.getHangye2() + " 23:59:59";
            gtgsyw.setHangye1(Seime);
            gtgsyw.setHangye2(Eeime);
        }
        return gtgsywMapper.selectGtgsywListAll(gtgsyw);
    }
    @Override
    public List<Gtgsyw> selectGtgsywAllList(Gtgsyw gtgsyw) {
        return gtgsywMapper.selectGtgsywByFlg(gtgsyw);
    }
    /**
     * 将长时间格式时间转换为字符串 yyyy-MM-dd HH:mm:ss
     *
     * @param dateDate
     * @return
     */
    public static String dateToStrLong(Date dateDate) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = formatter.format(dateDate);
        return dateString;
    }
    //排序
    private void startPage() {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) {
            String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
            PageHelper.startPage(pageNum, pageSize, orderBy);
        }
    }

    /**
     * 搜索退回表(退回单独一个表)
     *
     * @param gtgsyw   搜索参数
     * @param codename 搜搜个体工商户名称参数
     * @return
     */
    @Override
    public List<auditTh> selectauditTh(Gtgsyw gtgsyw, String codename) {
        return gtgsywMapper.selectauditTh(gtgsyw, codename);
    }

    /**
     * 查询申请来源字典
     *
     * @return
     */
    @Override
    public List<String> selectDiction() {
        return gtgsywMapper.selectDiction();
    }

    /**
     * 新增待审核
     *
     * @param gtgsyw 待审核
     * @return 结果
     */
    @Override
    public int insertGtgsyw(Gtgsyw gtgsyw) {
        return gtgsywMapper.insertGtgsyw(gtgsyw);
    }

    /**
     * 修改待审核
     *
     * @param gtgsyw 待审核
     * @return 结果
     */
    @Override
    public int updateGtgsyw(Gtgsyw gtgsyw) {
        return gtgsywMapper.updateGtgsyw(gtgsyw);
    }

    /**
     * 删除待审核对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteGtgsywByIds(String ids) {
        return gtgsywMapper.deleteGtgsywByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除待审核信息
     *
     * @param id 待审核ID
     * @return 结果
     */
    @Override
    public int deleteGtgsywById(Long id) {
        return gtgsywMapper.deleteGtgsywById(id);
    }

    /**
     * 修改待审核
     *
     * @param id 审核ID
     * @return
     */
    @Override
    public int updateById(Long id, Long flg) {
        return gtgsywMapper.updateById(id, flg);
    }

    /**
     * 保存不予受理
     *
     * @param id           不予受理id
     * @param returnReason 不予受理理由
     * @param userid       登录管理员id
     * @return
     */
    public int updateThContent(String id, String returnReason, Long userid) {
        Gtgsyw gt =new Gtgsyw();
        //修改id
        gt.setId(Long.valueOf(id));
        //审核管理员id
        gt.setShenherenid(userid.toString());
        //审核管理员
        String userName = gtgsywMapper.selectUserName(userid);
        gt.setShenherenname(userName);
        //审核时间
        gt.setShenhedate(new Date());
        //退回原因
        gt.setShenhenote(returnReason);
        //修改审核状态为2(退回)
        int i= gtgsywMapper.updateByIdFlg(gt);
        return i;
    }



    /**
     * 保存通过
     *
     * @param id     通过审核id
     * @param xycode 信用代码
     * @param book   书文号
     * @param reg    注册号
     * @param userId 审核人 id
     * @param QRcode 二维码
     * @return
     */
    @Override
    public int updatepass(String id, String xycode, String book, String reg, Long userId, String QRcode, HttpServletRequest request) {
        String userName = gtgsywMapper.selectUserName(userId);
        Gtgsyw gt = new Gtgsyw();
        //id
        gt.setId(Long.valueOf(id));
        //信用代码
        gt.setXinyongcode(xycode);
        //书文号
        gt.setZwzh1(book);
        //审核人
        gt.setShenherenname(userName);
        //审核人id
        gt.setShenherenid(userId + "");
        //注册号
        gt.setZhucehao(reg);
        //审核时间
        System.err.println("date:"+request.getParameter("shdate"));
        //base64
        gt.setErweimabase64(QRcode);
        //注册日期
        gt.setZhucetime(new Date());
//        //正本打印状态
//        gt.setIsprintF(Long.valueOf(0));
//        //副文打印状态
//        gt.setIsprint(Long.valueOf(0));
        return gtgsywMapper.updatepass(gt);
    }


    /**
     * 将短时间格式字符串转换为时间 yyyy-MM-dd
     *
     * @param strDate
     * @return
     */
    public static Date strToDate(String strDate) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        ParsePosition pos = new ParsePosition(0);
        Date strtodate = formatter.parse(strDate, pos);
        return strtodate;
    }
    /**
     * 下载单个word文件
     */
    @Override
    public File createDoc(String id, String down) throws FileNotFoundException {
        // 创建数据
        Map<String, Object> dataMap = new HashMap<String, Object>();
        Gtgsyw gt = gtgsywMapper.selectById(Long.valueOf(id));
//        Base64ToImage(gt.getJingyingcardtouxiang(), "D:\\" + gt.getJingyingren() + ".jpg");
        List<Map>  files=selectidentityPhotos(gt.getId().toString());//获取到身份证正反面
        String str = "iVBORw0KGgoAAAANSUhEUgAAAKMAAABKCAYAAADXJ+TKAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAADRSURBVHhe7dIxAQAADMOg+Tfd2cgBGrhBhIxkyEiGjGTISIaMZMhIhoxkyEiGjGTISIaMZMhIhoxkyEiGjGTISIaMZMhIhoxkyEiGjGTISIaMZMhIhoxkyEiGjGTISIaMZMhIhoxkyEiGjGTISIaMZMhIhoxkyEiGjGTISIaMZMhIhoxkyEiGjGTISIaMZMhIhoxkyEiGjGTISIaMZMhIhoxkyEiGjGTISIaMZMhIhoxkyEiGjGTISIaMZMhIhoxkyEiGjGTISIaMZMhIhoxEbA8iDcZ+yy2tAwAAAABJRU5ErkJggg==";
        String yzbm = Global.getConfig("ruoyi.cityPostcode");
        if(gt.getQianming()!=null&&!gt.getQianming().equals("")) {
//            str = gt.getQianming().split(",")[1];
            str = convertFileToBase64(
                    Global.getProfile()+String.valueOf(gt.getQianming())
                            .replace("/profile",""));
        }
        String city = Global.getCityName();
        String template = "";
        //下载准予登记通知书
        if (down.equals("1")) {
            dataMap.put("djname", gt.getJingyingren());
            List<?> eList = new ArrayList<>();
            Date date = gt.getShenqingdate();
            String dateStr = new SimpleDateFormat("yyyy年MM月dd日").format(date);
            dataMap.put("djdate", dateStr);
            dataMap.put("shuwh", gt.getZhucehao1());
            dataMap.put("gtname", gt.getNsxzq() + gt.getZwzh() + gt.getMingchenghangye() + gt.getZuzhixingshi());
            dataMap.put("eList", eList);
            // 获取模板
            template = "/templates/准予登记通知书.ftl";
        } else if (down.equals("2")) {
            List<?> eList = new ArrayList<>();
            //下载封皮
            gt.setCodeName(gt.getNsxzq() + gt.getZwzh() + gt.getMingchenghangye() + gt.getZuzhixingshi());
            dataMap.put("pfmc", gt.getCodeName());
            dataMap.put("fpadmin", gt.getZhucehao());
            dataMap.put("fpname", gt.getShenherenname());
            Date date = gt.getShenqingdate();
            String dateStr = new SimpleDateFormat("yyyy年MM月dd日").format(date);
            dataMap.put("fpdate", dateStr);
            dataMap.put("eList", eList);
            dataMap.put("city",city);
            // 获取模板
            template = "/templates/fengpi.ftl";
        } else if (down.equals("3")) {
            List<?> eList = new ArrayList<>();
            //下载申请书
            //申请书
            dataMap.put("sqzhucehao", gt.getZhucehao());
            //姓名
            dataMap.put("sqname", gt.getJingyingren());
            //性别
            dataMap.put("sqgender", gt.getXingbie());
            //身份证正反面
            int numf=0;
            for (Map fi:files) {

//                String [] st= String.valueOf(fi.get("FilePath")).split(",");

                if(numf==1&&fi.get("CailiaoName").equals("身份证扫描件")){
                    dataMap.put("sfz1",convertFileToBase64(
                            Global.getProfile()+String.valueOf(fi.get("FilePath"))
                                    .replace("/profile","")));
                }else if (fi.get("CailiaoName").equals("身份证扫描件")) {
                    numf++;
                    dataMap.put("sfz2",convertFileToBase64(
                            Global.getProfile()+String.valueOf(fi.get("FilePath"))
                                    .replace("/profile","")));
                }else if (fi.get("CailiaoName").equals("网络平台店铺经营证明")) {
                    //证明
                    dataMap.put("typeSrc", convertFileToBase64(
                            Global.getProfile()+String.valueOf(fi.get("FilePath"))
                                    .replace("/profile","")));
                }
            }
            //头像
            if(gt.getJingyingcardtouxiang()!=null&&gt.getJingyingcardtouxiang()!="") {
                gt.setJingyingcardtouxiang(convertFileToBase64(
                        Global.getProfile()+gt.getJingyingcardtouxiang()
                                .replace("/profile","")));
                dataMap.put("sqhead", gt.getJingyingcardtouxiang());
            }else{
//                String [] st1=gt.getPaizhao().split(",");
                gt.setJingyingcardtouxiang(convertFileToBase64(
                        Global.getProfile()+gt.getPaizhao()
                                .replace("/profile","")));
                dataMap.put("sqhead", gt.getJingyingcardtouxiang());
            }
            //身份证号
            dataMap.put("sqcard", gt.getJingyingcard());
            //住所
            dataMap.put("sqsite", gt.getJiatingzhuzhi());
            //电话
            dataMap.put("sqphone", gt.getJingyingrenphone());
            //政治面貌
            dataMap.put("sqface", gt.getZzmm());
            //民族
            dataMap.put("sqnation", gt.getMinzhu());
            //文化程度
            dataMap.put("sqcult", gt.getWhcd());
            //职业状况
            dataMap.put("sqzhiye", gt.getZyzk());
            //名称
            gt.setCodeName(gt.getNsxzq() + gt.getZwzh() + gt.getMingchenghangye() + gt.getZuzhixingshi());
            dataMap.put("sqmcname", gt.getCodeName());
            //备用字号1
            dataMap.put("sqtypeone", gt.getZwzh1());
            //备用字号2
            dataMap.put("sqtypetwo", gt.getZwzh2());
            //经营范围
            dataMap.put("sqscope", gt.getJingyingfanwei());
            //经营场所
            dataMap.put("sqmanagesite",gt.getJingyingchangsuo().replaceAll("河北省"+Global.getSuperCity(),""));
            //从业人数
            dataMap.put("sqperson", gt.getCongyerenshu());
            //资金
            dataMap.put("sqmoney", gt.getZijinshue());

            //经营者签名
            dataMap.put("sqsignature", str);
            Date date = gt.getShenqingdate();
            String dateStr = new SimpleDateFormat("yyyy年MM月dd日").format(date);
            //审核时间
            dataMap.put("sqdate", dateStr);
            //证件类型
            dataMap.put("sqcardtype", "身份证");
            //准核人签字
            dataMap.put("sqauditname", gt.getShenherenname());

            //书文号
            dataMap.put("sqbookhao", gt.getZhucehao1());
            //信用代码
            dataMap.put("sqxycode", gt.getXinyongcode());
            //注册号
            dataMap.put("sqreghao", gt.getZhucehao());
            //字号
            dataMap.put("sqreghao1", gt.getZhucehao1());
            //行业
            dataMap.put("sqhangye", gt.getHangye());
            //门店类型
            dataMap.put("type", gt.getType());
            //邮政编码
            dataMap.put("yzbm", yzbm);

            //受理人
            dataMap.put("slr", gt.getShenherenname());

            //同意
            dataMap.put("sqtongyi", "同意");
            // 获取模板
            /*template = "/templates/sqa.ftl";  //模板文件的地址*/
            template = "/templates/s请.ftl";  //模板文件的地址
            dataMap.put("eList", eList);

        } else if (down.equals("4")) {
            //个体工商户党建情况统计表
            List<?> eList = new ArrayList<>();
            //商户名称
            gt.setCodeName(gt.getNsxzq() + gt.getZwzh() + gt.getMingchenghangye() + gt.getZuzhixingshi());
            dataMap.put("gsmcname", gt.getCodeName());
            //注册号
            dataMap.put("gsreghao", gt.getZhucehao());
            //预备党员
            dataMap.put("gsyubeiyuan", "0");
            //是否为党员
            int party = gt.getIsdy();
            if (party == 0) {
                dataMap.put("gsdangyuans", "");
                dataMap.put("gsdangyuann", "√");
            }
            if (party == 1) {
                dataMap.put("gsdangyuans", "√");
                dataMap.put("gsdangyuann", "");
            }
            //经营人签字
            dataMap.put("gsqianming", str);
            //填报日期
            Date date = gt.getShenqingdate();
            String dateStr = new SimpleDateFormat("yyyy年MM月dd日").format(date);
            dataMap.put("gsdate", dateStr);
            dataMap.put("eList", eList);
            // 获取模板
            template = "/templates/gstj.ftl";  //模板文件的地址
        } else if (down.equals("5")) {
            //审批事项告知承诺书
            //商户名称
            gt.setCodeName(gt.getNsxzq() + gt.getZwzh() + gt.getMingchenghangye() + gt.getZuzhixingshi());
            dataMap.put("cnmcname", gt.getCodeName());
            //营业人签名
            dataMap.put("cnqianming", str);
            //日期
            Date date = gt.getShenqingdate();
            String dateStr = new SimpleDateFormat("yyyy年MM月dd日").format(date);
            dataMap.put("cndate", dateStr);
            dataMap.put("city",city);

            template = "/templates/cns.ftl";  //模板文件的地址
        } else if (down.equals("6")) {
            //住所（经营场所）信息申报表
            //商户名称
            gt.setCodeName(gt.getNsxzq() + gt.getZwzh() + gt.getMingchenghangye() + gt.getZuzhixingshi());
            dataMap.put("sbmcname", gt.getCodeName());
            //经营场所
            dataMap.put("sbmanagesit", gt.getJingyingchangsuo().replaceAll("河北省"+Global.getSuperCity(),""));
            //房屋规划用途
            dataMap.put("city",city);
            dataMap.put("fwghyt",gt.getFwghyt() );
            //是否军产
            int Isjc = gt.getIsjc();
            if (Isjc == 0) {
                dataMap.put("isjs", "否");
            } else {
                dataMap.put("isjs", "是");
            }
            //签名
            dataMap.put("sbqianming", str);
            //日期
            Date date = gt.getShenqingdate();
            //门店类型
            dataMap.put("type", gt.getType());
            //电脑所在地
            dataMap.put("zhuzhi", gt.getJiatingzhuzhi());
            String dateStr = new SimpleDateFormat("yyyy年MM月dd日").format(date);
            dataMap.put("sbdate", dateStr);
            template = "/templates/申报.ftl";  //模板文件的地址
        }

        String templatePath = template.substring(0, template.lastIndexOf("/"));
        String templateName = template.substring(template.lastIndexOf("/") + 1);
        System.err.println("templateName:" + templateName);
        Configuration configuration = null;
        if (configuration == null) {
            configuration = new Configuration(Configuration.VERSION_2_3_23);
            configuration.setDefaultEncoding("utf-8");
            configuration.setClassForTemplateLoading(this.getClass(), templatePath);
        }
        Template t = null;
        /* String name = "temp"+(int)(Math.random()*1000)+".doc";*/
        String name = templateName;
        System.err.println("name:" + name);
        File file = new File(name);
        try {
            t = configuration.getTemplate(templateName);
            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(name), StandardCharsets.UTF_8));
            t.process(dataMap, out);
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }
        return file;
    }


    /**
     * 下载zip压缩包
     */
    @Override
    public File MulticreateDoc(String id, String down, String filename) throws FileNotFoundException {
        File f = new File(filename);
        Writer w = null;
        FileOutputStream fos = null;
        String city = Global.getCityName();
        // 创建数据
        Map<String, Object> dataMap = new HashMap<String, Object>();
        Gtgsyw gt = gtgsywMapper.selectById(Long.valueOf(id));
        List<Map>  files=selectidentityPhotos(gt.getId().toString());//获取到身份证正反面
//        Base64ToImage(gt.getJingyingcardtouxiang(), "D:\\" + gt.getJingyingren() + ".jpg");
        String str = "iVBORw0KGgoAAAANSUhEUgAAAKMAAABKCAYAAADXJ+TKAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAADRSURBVHhe7dIxAQAADMOg+Tfd2cgBGrhBhIxkyEiGjGTISIaMZMhIhoxkyEiGjGTISIaMZMhIhoxkyEiGjGTISIaMZMhIhoxkyEiGjGTISIaMZMhIhoxkyEiGjGTISIaMZMhIhoxkyEiGjGTISIaMZMhIhoxkyEiGjGTISIaMZMhIhoxkyEiGjGTISIaMZMhIhoxkyEiGjGTISIaMZMhIhoxkyEiGjGTISIaMZMhIhoxkyEiGjGTISIaMZMhIhoxkyEiGjGTISIaMZMhIhoxEbA8iDcZ+yy2tAwAAAABJRU5ErkJggg==";
        String yzbm= Global.getConfig("ruoyi.cityPostcode");
        if(gt.getQianming()!=null&&!gt.getQianming().equals("")) {
//            str = gt.getQianming().split(",")[1];
            str = convertFileToBase64(
                    Global.getProfile()+String.valueOf(gt.getQianming())
                            .replace("/profile",""));
        }
//        Base64ToImage(str, "D:\\" + gt.getJingyingren() + "签名.jpg");
        String template = "";
        //下载准予登记通知书
        if (down.equals("1")) {
            dataMap.put("djname", gt.getJingyingren());
            List<?> eList = new ArrayList<>();
            Date date = gt.getShenqingdate();
            String dateStr = new SimpleDateFormat("yyyy年MM月dd日").format(date);
            dataMap.put("djdate", dateStr);
            dataMap.put("shuwh", gt.getZhucehao1());
            dataMap.put("gtname", gt.getNsxzq() + gt.getZwzh() + gt.getMingchenghangye() + gt.getZuzhixingshi());
            dataMap.put("eList", eList);
            // 获取模板
            template = "/templates/准予登记通知书.ftl";
        } else if (down.equals("2")) {
            List<?> eList = new ArrayList<>();
            //下载封皮
            dataMap.put("city",city);
            gt.setCodeName(gt.getNsxzq() + gt.getZwzh() + gt.getMingchenghangye() + gt.getZuzhixingshi());
            dataMap.put("pfmc", gt.getCodeName());
            dataMap.put("fpadmin", gt.getZhucehao());
            dataMap.put("fpname", gt.getShenherenname());
            Date date = gt.getShenqingdate();
            String dateStr = new SimpleDateFormat("yyyy年MM月dd日").format(date);
            dataMap.put("fpdate", dateStr);
            dataMap.put("eList", eList);
            // 获取模板
            template = "/templates/fengpi.ftl";
        } else if (down.equals("3")) {
            List<?> eList = new ArrayList<>();
            //下载申请书
            //申请书
            dataMap.put("sqzhucehao", gt.getZhucehao());
            //姓名
            dataMap.put("sqname", gt.getJingyingren());
            //性别
            dataMap.put("sqgender", gt.getXingbie());

            //邮政编码
            dataMap.put("yzbm", yzbm);
            //头像
            if(gt.getJingyingcardtouxiang()!=null){
                gt.setJingyingcardtouxiang(convertFileToBase64(
                        Global.getProfile()+gt.getJingyingcardtouxiang()
                                .replace("/profile","")));
                dataMap.put("sqhead", gt.getJingyingcardtouxiang());
            }else{

                gt.setJingyingcardtouxiang(convertFileToBase64(
                        Global.getProfile()+gt.getPaizhao()
                                .replace("/profile","")));
                dataMap.put("sqhead", gt.getJingyingcardtouxiang());
            }


            //身份证号
            dataMap.put("sqcard", gt.getJingyingcard());
            //住所
            dataMap.put("sqsite", gt.getJiatingzhuzhi());
            //电话
            dataMap.put("sqphone", gt.getJingyingrenphone());
            //政治面貌
            dataMap.put("sqface", gt.getZzmm());
            //民族
            dataMap.put("sqnation", gt.getMinzhu());
            //文化程度
            dataMap.put("sqcult", gt.getWhcd());
            //职业状况
            dataMap.put("sqzhiye", gt.getZyzk());
            //名称
            gt.setCodeName(gt.getNsxzq() + gt.getZwzh() + gt.getMingchenghangye() + gt.getZuzhixingshi());
            dataMap.put("sqmcname", gt.getCodeName());
            //备用字号1
            dataMap.put("sqtypeone", gt.getZwzh1());
            //备用字号2
            dataMap.put("sqtypetwo", gt.getZwzh2());
            //经营范围
            dataMap.put("sqscope", gt.getJingyingfanwei());
            //经营场所
            dataMap.put("sqmanagesite", gt.getJingyingchangsuo().replaceAll("河北省"+Global.getSuperCity(),""));
            //从业人数
            dataMap.put("sqperson", gt.getCongyerenshu());
            //资金
            dataMap.put("sqmoney", gt.getZijinshue());

            //经营者签名
            dataMap.put("sqsignature", str);
            Date date = gt.getShenqingdate();
            String dateStr = new SimpleDateFormat("yyyy年MM月dd日").format(date);
            //审核时间
            dataMap.put("sqdate", dateStr);
            //证件类型
            dataMap.put("sqcardtype", "身份证");
            //准核人签字
            dataMap.put("sqauditname", gt.getShenherenname());
            //身份证正反面
            int numf=0;
            for (Map fi:files) {

                //  String [] st= String.valueOf(fi.get("FilePath")).split(",");
                if(numf==1&&fi.get("CailiaoName").equals("身份证扫描件")){
                    dataMap.put("sfz1",convertFileToBase64(
                            Global.getProfile()+String.valueOf(fi.get("FilePath"))
                                    .replace("/profile","")));
                }else if (fi.get("CailiaoName").equals("身份证扫描件")) {
                    numf++;
                    dataMap.put("sfz2",convertFileToBase64(
                            Global.getProfile()+String.valueOf(fi.get("FilePath"))
                                    .replace("/profile","")));
                }else if (fi.get("CailiaoName").equals("网络平台店铺经营证明")) {
                    //证明
                    dataMap.put("typeSrc", convertFileToBase64(
                            Global.getProfile()+String.valueOf(fi.get("FilePath"))
                                    .replace("/profile","")));
                }
            }
            //书文号
            dataMap.put("sqbookhao", gt.getZhucehao1());
            //信用代码
            dataMap.put("sqxycode", gt.getXinyongcode());
            //注册号
            dataMap.put("sqreghao", gt.getZhucehao());
            //行业
            dataMap.put("sqhangye", gt.getHangye());
            //同意
            dataMap.put("sqtongyi", "同意");
            //门店类型
            dataMap.put("type", gt.getType());

            //受理人
            dataMap.put("slr", gt.getShenherenname());
            //字号
            dataMap.put("sqreghao1", gt.getZhucehao1());
            // 获取模板
            /*template = "/templates/sqa.ftl";  //模板文件的地址*/
            template = "/templates/s请.ftl";  //模板文件的地址
            dataMap.put("eList", eList);

        } else if (down.equals("4")) {
            //个体工商户党建情况统计表
            List<?> eList = new ArrayList<>();
            //商户名称
            gt.setCodeName(gt.getNsxzq() + gt.getZwzh() + gt.getMingchenghangye() + gt.getZuzhixingshi());
            dataMap.put("gsmcname", gt.getCodeName());
            //注册号
            dataMap.put("gsreghao", gt.getZhucehao());
            //预备党员
            dataMap.put("gsyubeiyuan", "0");
            //是否为党员
            int party = gt.getIsdy();
            if (party == 0) {
                dataMap.put("gsdangyuans", "");
                dataMap.put("gsdangyuann", "√");
            }
            if (party == 1) {
                dataMap.put("gsdangyuans", "√");
                dataMap.put("gsdangyuann", "");
            }
            //经营人签字
            dataMap.put("gsqianming", str);
            //填报日期
            Date date = gt.getShenqingdate();
            String dateStr = new SimpleDateFormat("yyyy年MM月dd日").format(date);
            dataMap.put("gsdate", dateStr);
            dataMap.put("eList", eList);
            // 获取模板
            template = "/templates/gstj.ftl";  //模板文件的地址
        } else if (down.equals("5")) {
            dataMap.put("city",city);
            //审批事项告知承诺书
            //商户名称
            gt.setCodeName(gt.getNsxzq() + gt.getZwzh() + gt.getMingchenghangye() + gt.getZuzhixingshi());
            dataMap.put("cnmcname", gt.getCodeName());
            //营业人签名
            dataMap.put("cnqianming", str);
            //日期
            Date date = gt.getShenqingdate();
            String dateStr = new SimpleDateFormat("yyyy年MM月dd日").format(date);
            dataMap.put("cndate", dateStr);

            template = "/templates/cns.ftl";  //模板文件的地址
        } else if (down.equals("6")) {
            dataMap.put("city",city);
            //住所（经营场所）信息申报表
            //商户名称
            gt.setCodeName(gt.getNsxzq() + gt.getZwzh() + gt.getMingchenghangye() + gt.getZuzhixingshi());
            dataMap.put("sbmcname", gt.getCodeName());
            //经营场所
            dataMap.put("sbmanagesit",gt.getJingyingchangsuo().replaceAll("河北省"+Global.getSuperCity(),""));
            //房屋规划用途
            dataMap.put("fwghyt", gt.getFwghyt());
            //是否军产
            int Isjc = gt.getIsjc();
            if (Isjc == 0) {
                dataMap.put("isjs", "否");
            } else {
                dataMap.put("isjs", "是");
            }
            //签名
            dataMap.put("sbqianming", str);
            //门店类型
            dataMap.put("type", gt.getType());
            //电脑所在地
            dataMap.put("zhuzhi", gt.getJiatingzhuzhi());
            //日期
            Date date = gt.getShenqingdate();
            String dateStr = new SimpleDateFormat("yyyy年MM月dd日").format(date);
            dataMap.put("sbdate", dateStr);
            template = "/templates/申报.ftl";  //模板文件的地址
        }

        String templatePath = template.substring(0, template.lastIndexOf("/"));
        String templateName = template.substring(template.lastIndexOf("/") + 1);
        System.err.println("templateName:" + templateName);
        Configuration configuration = null;
        if (configuration == null) {
            configuration = new Configuration(Configuration.VERSION_2_3_23);
            configuration.setDefaultEncoding("utf-8");
            configuration.setClassForTemplateLoading(this.getClass(), templatePath);
        }
        Template t = null;
        String name = templateName;
        System.err.println("name:" + name);
        File file = new File(name);
        try {
            fos = new FileOutputStream(f);
            w = new OutputStreamWriter(fos, StandardCharsets.UTF_8);

            t = configuration.getTemplate(templateName);
            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(name), StandardCharsets.UTF_8));
            t.process(dataMap, w);
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        } finally {
            try {
                fos.close();
                w.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        return file;
    }

    /**
     * 查询行业分类数据
     *
     * @return
     */
    @Override
    public List<Ztree> selectTradeTree() {
        List<Trade> tradeList = gtgsywMapper.selectTradeTree();
        List<Ztree> ztreeList = new ArrayList<>();
        for (Trade trade : tradeList) {
            Ztree ztree = new Ztree();
            ztree.setId(trade.getDataDictionaryDetailId());
            ztree.setpId(trade.getParentId());
            ztree.setName(trade.getFullName());
            ztree.setTitle(trade.getFullName());
            ztreeList.add(ztree);
        }
        return ztreeList;
    }

    /**
     * 添加便捷语
     */
    @Override
    public int addeasy(String add) {

        return gtgsywMapper.addeasy(add);
    }


    /**
     * 查询便捷语
     */
    @Override
    public List<String> selecteasy() {
        return gtgsywMapper.selecteasy();
    }



    /**
     * 根据Bsid查询唯一信息
     *
     * @param card 身份证号码
     * @param bsid 唯一标识码
     * @return 信息
     */
    @Override
    public Gtgsyw selectByCB(String card, String bsid) {
        return gtgsywMapper.selectByCB(card, bsid);
    }

    /**
     * 根据身份证查询
     *
     * @param card
     * @return 身份证信息
     */
    @Override
    public List<Gtgsyw> selectByCard(String card) {
        return gtgsywMapper.selectByCard(card);
    }

    /**
     * 查询用户信息
     *
     * @param bsid
     * @return
     */
    @Override
    public Gtgsyw selectByBsid(String bsid) {
        return gtgsywMapper.selectGtgsywByBsid(bsid);
    }


    @Override
    public Gtgsyw selBack(Long tid) {
        return gtgsywMapper.selGtgsywBack(tid);
    }


    /**
     * id查询退回表
     */
    @Override
    public auditTh selectByIdTh(Long id) {
        return gtgsywMapper.selectByIdTh(id);
    }
    /**
     * 直接查询所有的信息
     * @return
     */
    public  List<Map>  selectByNumb(String Date){

        return gtgsywMapper.selectByNumb(Date);
    }
    public List<Map>  selectToflg(){
        return gtgsywMapper.selectToflg();
    }

    public  Integer[]  selectByflgDate(){
        return gtgsywMapper.selectByflgDate();
    }


    /**
     * 下载某时间内所有的zip
     * @return
     */
    public  String  downloadMonthZip(String start,String end,HttpServletRequest request, HttpServletResponse response) throws IOException {

//        File monthZip =new File(Global.getDownloadPath()+"/"+start+".zip");
        ZipOutputStream zos = null;
        Integer day= Math.toIntExact(DateUtils.getDatePoorDay(DateUtils.parseDate(end), DateUtils.parseDate(start)));
        List<String> files= new ArrayList<>();
        ServletOutputStream out = null;
        String downloadPath=Global.getDownloadPath();
        //转成时间计算差了多少天
        File sourceDir=new File(downloadPath);
        for(int i=0;i<DateUtils.getDatePoorDay(DateUtils.parseDate(end),DateUtils.parseDate(start))+1;i++){
            Date st=DateUtils.parseDate(start);
            Calendar cal = Calendar.getInstance();
            cal.setTime(st);//设置起时间
            cal.add(Calendar.DATE, i);//增加一天
            st=cal.getTime();
            File file=new File(downloadPath+"/"+DateUtils.dateMonth(st));

            if(file.exists()) {
                files.add((downloadPath + "/" + DateUtils.dateMonth(st)));
            }
        }
        File dayZip=new File(downloadPath+"/"+start+"至"+end+".zip");
        if (!dayZip.exists()) {
            try {
                ZipUtil.toZip(files, downloadPath + "/" + start + "至" + end + ".zip", true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        InputStream fin = null;
        out = response.getOutputStream();
        response.setHeader("Content-disposition", "attachment; filename="
                + URLEncoder.encode(start+ "至" + end +".zip", "utf-8"));
        fin = new FileInputStream(downloadPath+"/"+start+ "至" + end +".zip");
        byte[] buffer = new byte[512]; // 缓冲区
        int bytesToRead = -1;
        // 通过循环将读入的Word文件的内容输出到浏览器中
        while ((bytesToRead = fin.read(buffer)) != -1) {
            out.write(buffer, 0, bytesToRead);
        }
        System.err.println("Zip整合成功");
        return null;
    }



    /**
     * 单次下载pdf zip
     * @param id gtgsyw id
     * @param down .ftl
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @Override
    public String downloadZip(String id,String[] down,HttpServletRequest request, HttpServletResponse response ) throws IOException {
        File isExit=null;
        InputStream fin = null;
        ServletOutputStream out = null;
        Gtgsyw gt=gtgsywMapper.selectById(Long.valueOf(id));
        java.io.BufferedInputStream bis = null;
        java.io.BufferedOutputStream bos = null;
        String isfile="";
        System.err.println("时间:"+gt.getUpdatetime());
        if(!gt.getZwzh().equals("***")){
            isfile=Global.getDownloadPath()+"/"+ DateUtils.dateMonth(gt.getUpdatetime())+"/"+gt.getNsxzq() + gt.getZwzh() + gt.getMingchenghangye() + gt.getZuzhixingshi()+"pdf.zip";
        }else{
            isfile=Global.getDownloadPath()+"/"+ DateUtils.dateMonth(gt.getUpdatetime())+"/"+gt.getJingyingren()+"无字号"+"pdf.zip";
        }
        isExit =new File(isfile);
        //判断要下载的压缩包是否存在
        if (isExit.exists()){
            out = response.getOutputStream();
            response.setHeader("Content-disposition", "attachment; filename="
                    + URLEncoder.encode(gt.getNsxzq() + gt.getZwzh() + gt.getMingchenghangye() + gt.getZuzhixingshi()+ ".zip", "utf-8"));
            fin = new FileInputStream(isExit);
            byte[] buffer = new byte[512]; // 缓冲区
            int bytesToRead = -1;
            // 通过循环将读入的Word文件的内容输出到浏览器中
            while ((bytesToRead = fin.read(buffer)) != -1) {
                out.write(buffer, 0, bytesToRead);
            }
        }else {
            File file = null;
            File zipfile = null;
            File directory = null;
            File directory1 = 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;
                String pdfPath = null;
                if (!gt.getZwzh().equals("***")) {
                    path = Global.getDownloadPath() + "/" + DateUtils.dateMonth(gt.getUpdatetime())+"/"+ gt.getCodeName() + "word";
                    pdfPath = Global.getDownloadPath() + "/" + DateUtils.dateMonth(gt.getUpdatetime())+"/"+ gt.getCodeName() + "pdf";
                } else {
                    path = Global.getDownloadPath() + "/" + DateUtils.dateMonth(gt.getUpdatetime())+"/"+ gt.getJingyingren() + "无字号" + "word";
                    pdfPath = Global.getDownloadPath() + "/" + DateUtils.dateMonth(gt.getUpdatetime())+"/"+ gt.getJingyingren() + "无字号" + "pdf";
                }

                directory = new File(path);
                directory1 = new File(pdfPath);
                directory.mkdirs();
                directory1.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 = MulticreateDoc(id, i + "", directory.getPath() + "/" + name + ".doc");
                    String wordPath = directory.getPath() + "/" + name + ".doc";

                    System.err.println(wordPath);
                    if (StringUtils.isEmpty(wordPath)) {
                        System.err.println("参数为空");
                    } else {
                        File file1 = new File(wordPath);
                        if (file1.exists()) {
                            try {
                                WordToPdf.doc2pdf(wordPath);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        } else {
                            System.err.println("文件不存在");
                        }
                    }
                }
                //压缩目录
                ZipUtil.createZip(pdfPath, pdfPath + ".zip");
                //根据路径获取刚生成的zip包文件
                zipfile = new File(pdfPath + ".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 (directory != null) {
                        //递归删除目录及目录下文件
                        ZipUtil.deleteFile(directory);
                        ZipUtil.deleteFile(directory1);
                    }
                    if (fin != null) {
                        fin.close();
                    }
                    if (out != null) {
                        out.close();
                    }
                //   if (zipfile!=null) {zipfile.delete();}
                } catch (Exception e2) {
                    e2.printStackTrace();
                }
            }
        }

        return null;
    }


    /**
     * 定时任务生成zip
     * @param id gtywgs id
     * @return
     * @throws IOException
     */
    @Override
    public String creatZip(Integer id) throws IOException {
        File isExit=null;
        InputStream fin = null;
        ServletOutputStream out = null;
        Gtgsyw gt=gtgsywMapper.selectById(Long.valueOf(id));
        java.io.BufferedInputStream bis = null;
        java.io.BufferedOutputStream bos = null;
        String isfile="";
        String[] down= {"1","2","3","4","5","6"};
        System.err.println("时间:"+gt.getUpdatetime());
        if(!gt.getZwzh().equals("***")){
            isfile=Global.getDownloadPath()+"/"+ DateUtils.dateMonth(gt.getUpdatetime())+"/"+gt.getNsxzq() + gt.getZwzh() + gt.getMingchenghangye() + gt.getZuzhixingshi()+"pdf.zip";
        }else{
            isfile=Global.getDownloadPath()+"/"+ DateUtils.dateMonth(gt.getUpdatetime())+"/"+gt.getJingyingren()+"无字号"+"pdf.zip";
        }
        isExit =new File(isfile);
        //判断要下载的压缩包是否存在
        if (!isExit.exists()||isExit.length()<600*1024){

            // 路径为文件且不为空则进行删除
            if (isExit.isFile() && isExit.exists()) {
                isExit.delete();
            }
            File directory = null;
            File directory1 = null;
            try {
                Configuration configuration = null;
                if (configuration == null) {
                    configuration = new Configuration(Configuration.VERSION_2_3_23);
                    configuration.setDefaultEncoding("utf-8");
                    configuration.setClassForTemplateLoading(this.getClass(), "");
                }
                gt.setCodeName(gt.getNsxzq() + gt.getZwzh() + gt.getMingchenghangye() + gt.getZuzhixingshi());
                String path = null;
                String pdfPath = null;
                if (!gt.getZwzh().equals("***")) {
                    path = Global.getDownloadPath() + "/" + DateUtils.dateMonth(gt.getUpdatetime())+"/"+ gt.getCodeName() + "word";
                    pdfPath = Global.getDownloadPath() + "/" + DateUtils.dateMonth(gt.getUpdatetime())+"/"+ gt.getCodeName() + "pdf";
                } else {
                    path = Global.getDownloadPath() + "/" + DateUtils.dateMonth(gt.getUpdatetime())+"/"+ gt.getJingyingren() + "无字号" + "word";
                    pdfPath = Global.getDownloadPath() + "/" + DateUtils.dateMonth(gt.getUpdatetime())+"/"+ gt.getJingyingren() + "无字号" + "pdf";
                }

                directory = new File(path);
                directory1 = new File(pdfPath);
                directory.mkdirs();
                directory1.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.住所（经营场所）信息申报表";
                    }
                   MulticreateDoc(id.toString(), i + "", directory.getPath() + "/" + name + ".doc");
                    String wordPath = directory.getPath() + "/" + name + ".doc";

                    System.err.println(wordPath);
                    if (StringUtils.isEmpty(wordPath)) {
                        System.err.println("参数为空");
                    } else {
                        File file1 = new File(wordPath);
                        if (file1.exists()) {
                            try {
                                WordToPdf.doc2pdf(wordPath);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        } else {
                            System.err.println("文件不存在");
                        }
                    }
                }
                //压缩目录
                ZipUtil.createZip(pdfPath, pdfPath + ".zip");
            } 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);
                        ZipUtil.deleteFile(directory1);
                    }
                } catch (Exception e2) {
                    e2.printStackTrace();
                }
            }
        } else {
            return "存在的zip无需再生成";
        }
        return null;
    }
    public List<Map> selectByMonth(){
        return gtgsywMapper.selectByMonth();
    }
    /**
     * 查询最大的zzcode
     */
    @Override
    public String selectMaxZzCode(){

        return gtgsywMapper.selectMaxZzCode();
    }

}

